text:
Help me restructure code for multitasking Neopixel + IR remote + arduino
First of all, I'm completely new to both arduino, and programing. Second, as for a good newbie, i'm trying to build a fairly complicated project. So, any help and suggestion is welcome. The goal is: light up a shelf, with 2x 1m led strip, with 2 different "fire" animation. And remote control the arduino to switch between effects and colors.
The state of the project so far https://circuits.io/circuits/2459366-arduino-ir-with-neopixel
I learned one arduino is not enough to decode IR signals and drive led strips. So, I'm using two. Successfully merged 2 sketches: one, that receives, decodes and sends the IR signal to another arduino.
And based on tutorial https://learn.adafruit.com/multi-tasking-the-arduino-part-3/put-it-all-together-dot-dot-dot
I managed to control the LEDs via IR remote control. Here is code currently using (a bit bloated since its contains all the effect from the tutorial.)
Here is code so far:
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#define I2C_SLAVE_ADDRESS 8

// Remote control button codes
const unsigned int BUTTON_1 = 0xFD08F7;
const unsigned int BUTTON_2 = 0xFD8877;
const unsigned int BUTTON_3 = 0xFD48B7;
const unsigned int BUTTON_4 = 0xFD28D7;
const unsigned int BUTTON_5 = 0xFDA857;
const unsigned int BUTTON_6 = 0xFD6897;
const unsigned int BUTTON_7 = 0xFD18E7;
const unsigned int BUTTON_8 = 0xFD9867;
const unsigned int BUTTON_9 = 0xFD58A7;
const unsigned int BUTTON_UP = 0xFD50AF;
const unsigned int BUTTON_DOWN = 0xFD10EF;
const unsigned int BUTTON_VOL = 0xFD906F;

int t = 0; // variable for switching led rings with the remote
int b = 255; // brigtness starting value
// IR received code
unsigned int irCode = 0;            //ir code ends here
// Pattern types supported:
enum  pattern { NONE, RAINBOW_CYCLE, THEATER_CHASE, COLOR_WIPE, SCANNER, FADE, FIRE };
// Patern directions supported:
enum  direction { FORWARD, REVERSE };

// NeoPattern Class - derived from the Adafruit_NeoPixel class
class NeoPatterns : public Adafruit_NeoPixel
{
    public:

    // Member Variables:
    pattern  ActivePattern;  // which pattern is running
    direction Direction;     // direction to run the pattern

    unsigned long Interval;   // milliseconds between updates
    unsigned long lastUpdate; // last update of position

    uint32_t Color1, Color2;  // What colors are in use
    uint16_t TotalSteps;  // total number of steps in the pattern
    uint16_t Index;  // current step within the pattern

    void (*OnComplete)();  // Callback on completion of pattern

    // Constructor - calls base-class constructor to initialize strip
    NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)())
    :Adafruit_NeoPixel(pixels, pin, type)
    {
        OnComplete = callback;
    }

    // Update the pattern
    void Update()
    {
        if((millis() - lastUpdate) > Interval) // time to update
        {
            lastUpdate = millis();
            switch(ActivePattern)
            {
                case RAINBOW_CYCLE:
                    RainbowCycleUpdate();
                    break;
                case THEATER_CHASE:
                    TheaterChaseUpdate();
                    break;
                case COLOR_WIPE:
                    ColorWipeUpdate();
                    break;
                case SCANNER:
                    ScannerUpdate();
                    break;
                case FADE:
                    FadeUpdate();
            case FIRE:
                    RainbowCycleUpdate();
                    break;
                default:
                    break;
            }
        }
    }

    // Increment the Index and reset at the end
    void Increment()
    {
        if (Direction == FORWARD)
        {
           Index++;
           if (Index >= TotalSteps)
            {
                Index = 0;
                if (OnComplete != NULL)
                {
                    OnComplete(); // call the comlpetion callback
                }
            }
        }
        else // Direction == REVERSE
        {
            --Index;
            if (Index <= 0)
            {
                Index = TotalSteps-1;
                if (OnComplete != NULL)
                {
                    OnComplete(); // call the comlpetion callback
                }
            }
        }
    }

    // Reverse pattern direction
    void Reverse()
    {
        if (Direction == FORWARD)
        {
            Direction = REVERSE;
            Index = TotalSteps-1;
        }
        else
        {
            Direction = FORWARD;
            Index = 0;
        }
    }

    // Initialize for a RainbowCycle
    void RainbowCycle(uint8_t interval, direction dir = FORWARD)
    {
        ActivePattern = RAINBOW_CYCLE;
        Interval = interval;
        TotalSteps = 255;
        Index = 0;
        Direction = dir;
    }

    // Update the Rainbow Cycle Pattern
    void RainbowCycleUpdate()
    {
        for(int i=0; i< numPixels(); i++)
        {
            setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
        }
        show();
        Increment();
    }

    // Initialize for a Theater Chase
    void TheaterChase(uint32_t color1, uint32_t color2, uint8_t interval, direction dir = FORWARD)
    {
        ActivePattern = THEATER_CHASE;
        Interval = interval;
        TotalSteps = numPixels();
        Color1 = color1;
        Color2 = color2;
        Index = 0;
        Direction = dir;
   }

    // Update the Theater Chase Pattern
    void TheaterChaseUpdate()
    {
        for(int i=0; i< numPixels(); i++)
        {
            if ((i + Index) % 3 == 0)
            {
                setPixelColor(i, Color1);
            }
            else
            {
                setPixelColor(i, Color2);
            }
        }
        show();
        Increment();
    }

    // Initialize for a ColorWipe
    void ColorWipe(uint32_t color, uint8_t interval, direction dir = FORWARD)
    {
        ActivePattern = COLOR_WIPE;
        Interval = interval;
        TotalSteps = numPixels();
        Color1 = color;
        Index = 0;
        Direction = dir;
    }

    // Update the Color Wipe Pattern
    void ColorWipeUpdate()
    {
        setPixelColor(Index, Color1);
        show();
        Increment();
    }

    // Initialize for a SCANNNER
    void Scanner(uint32_t color1, uint8_t interval)
    {
        ActivePattern = SCANNER;
        Interval = interval;
        TotalSteps = (numPixels() - 1) * 2;
        Color1 = color1;
        Index = 0;
    }

    // Update the Scanner Pattern
    void ScannerUpdate()
    {
        for (int i = 0; i < numPixels(); i++)
        {
            if (i == Index)  // Scan Pixel to the right
            {
                 setPixelColor(i, Color1);
            }
            else if (i == TotalSteps - Index) // Scan Pixel to the left
            {
                 setPixelColor(i, Color1);
            }
            else // Fading tail
            {
                 setPixelColor(i, DimColor(getPixelColor(i)));
            }
        }
        show();
        Increment();
    }

    // Initialize for a Fade
    void Fade(uint32_t color1, uint32_t color2, uint16_t steps, uint8_t interval, direction dir = FORWARD)
    {
        ActivePattern = FADE;
        Interval = interval;
        TotalSteps = steps;
        Color1 = color1;
        Color2 = color2;
        Index = 0;
        Direction = dir;
    }

    // Update the Fade Pattern
    void FadeUpdate()
    {
        // Calculate linear interpolation between Color1 and Color2
        // Optimise order of operations to minimize truncation error
        uint8_t red = ((Red(Color1) * (TotalSteps - Index)) + (Red(Color2) * Index)) / TotalSteps;
        uint8_t green = ((Green(Color1) * (TotalSteps - Index)) + (Green(Color2) * Index)) / TotalSteps;
        uint8_t blue = ((Blue(Color1) * (TotalSteps - Index)) + (Blue(Color2) * Index)) / TotalSteps;

        ColorSet(Color(red, green, blue));
        show();
        Increment();
    }

    // Calculate 50% dimmed version of a color (used by ScannerUpdate)
    uint32_t DimColor(uint32_t color)
    {
        // Shift R, G and B components one bit to the right
        uint32_t dimColor = Color(Red(color) >> 1, Green(color) >> 1, Blue(color) >> 1);
        return dimColor;
    }

    // Set all pixels to a color (synchronously)
    void ColorSet(uint32_t color)
    {
        for (int i = 0; i < numPixels(); i++)
        {
            setPixelColor(i, color);
        }
        show();
    }

    // Returns the Red component of a 32-bit color
    uint8_t Red(uint32_t color)
    {
        return (color >> 16) & 0xFF;
    }

    // Returns the Green component of a 32-bit color
    uint8_t Green(uint32_t color)
    {
        return (color >> 8) & 0xFF;
    }

    // Returns the Blue component of a 32-bit color
    uint8_t Blue(uint32_t color)
    {
        return color & 0xFF;
    }

    // Input a value 0 to 255 to get a color value.
    // The colours are a transition r - g - b - back to r.
    uint32_t Wheel(byte WheelPos)
    {
        WheelPos = 255 - WheelPos;
        if(WheelPos < 85)
        {
            return Color(255 - WheelPos * 3, 0, WheelPos * 3);
        }
        else if(WheelPos < 170)
        {
            WheelPos -= 85;
            return Color(0, WheelPos * 3, 255 - WheelPos * 3);
        }
        else
        {
            WheelPos -= 170;
            return Color(WheelPos * 3, 255 - WheelPos * 3, 0);
        }
    }

   // brightness, need some improvements probably
   void incbrigtness() {
   if (b >= 255) {
      b = 255;
   setBrightness(b);}
   else {b = b + 10;
   setBrightness(b);}
   }

   void decbrigtness() {
   if (b <= 5) {
      b = 5;
   setBrightness(b);}
   else {b = b - 10;
   setBrightness(b);}
   }

};

void Ring1Complete();
void Ring2Complete();

void receiveEvent(int numBytes) {//decode the ir signal
  byte byte1 = Wire.read();
  byte byte2 = Wire.read();
  irCode = byte2;
  irCode = irCode << 8;
  irCode = irCode | byte1;
}

// Define some NeoPatterns for the two rings and the stick
//  as well as some completion routines
NeoPatterns Ring1(24, 6, NEO_GRB + NEO_KHZ800, &Ring1Complete); // led parameters
NeoPatterns Ring2(24, 7, NEO_GRB + NEO_KHZ800, &Ring2Complete);

// Initialize everything and prepare to start
void setup()
{
   Serial.begin(9600);
   Serial.println("my-main-program starting!");
   Wire.begin(I2C_SLAVE_ADDRESS);
   Wire.onReceive(receiveEvent);
   Serial.println("my-main-program successfully started!");
 }
// Main loop
void loop()
{
    // Update the rings.
   if (irCode) {             //Reads the ir code
    handleButton(irCode);
    irCode = 0;
  }
 Ring1.Update();
 Ring2.Update();
 }

void handleButton(unsigned int irCode) {
  switch (irCode) {
   case BUTTON_UP:      // button up  will control led stip 1, button 2 will control let strip 2, button 3 both.
      t = 1;
     Serial.println(t);
     break;
   case BUTTON_DOWN:
      t = 2;
     Serial.println(t);
      break;
   case BUTTON_VOL:
     t = 0;
      Serial.println(t);
     break;
   case BUTTON_1:
     if (t == 1) {    // this also needs some improvements
      Serial.println(t);
     Ring1.TheaterChase(Ring1.Color(0,255,0), Ring1.Color(0,0,50), 100);
      }
     else if (t == 2) {
     Serial.println(t);
     Ring2.TheaterChase(Ring1.Color(255,0,0), Ring1.Color(0,50,0), 100);
      }
     else {      // some random effects for testing
     Serial.println(t);
      Ring1.TheaterChase(Ring1.Color(0,0,255), Ring1.Color(50,0,0), 100);
     Ring2.TheaterChase(Ring1.Color(0,0,255), Ring1.Color(50,0,0), 100);
      }
   break;
    case BUTTON_2:
      Serial.println("2");
       Ring1.Scanner(Ring1.Color(255,0,0), 55);
     break;
    case BUTTON_3:
     Ring1.ColorWipe(Ring1.Color(0,255,255), 55);
     Serial.println("3");
      break;
    case BUTTON_4:
      Ring1.Scanner(Ring1.Color(0,255,255), 55);
     Serial.println("4");
      break;
    case BUTTON_5:
      Serial.println("5");
      break;
    case BUTTON_6:
      Serial.println("6");
      break;
    case BUTTON_7:
      Serial.println("7");
      break;
    case BUTTON_8:         //  test the brightness here.
   Ring1.incbrigtness();
   Serial.println(b);
     break;
    case BUTTON_9:
   Ring1.decbrigtness();
   Serial.println(b);
     break;
    default:
      Serial.print("Unrecognized code received: 0x");
      Serial.println(irCode, HEX);
      break;
  }
}

//------------------------------------------------------------
//Completion Routines - get called on completion of a pattern
//------------------------------------------------------------

// Ring1 Completion Callback
void Ring1Complete() //dont really need to do anything specific after loop ended so should go back to update.
{Ring1.Update(); }

void Ring2Complete()
{Ring2.Update(); }

The problem:
What I need is help, how to restructure 2 different effects. to fit into the above code. Loops replaced wilth millis() and delay with an updater.
here is the first, fire code by danesparza:
#include <Adafruit_NeoPixel.h>
#define PIN 6

Adafruit_NeoPixel strip = Adafruit_NeoPixel(29, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.setBrightness(brightness);
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {

  //  Uncomment one of these RGB (Red, Green, Blue) values to
  //  set the base color of the flame.  The color will flickr
  //  based on the initial base color

  //  Regular (orange) flame:
  //  int r = 226, g = 121, b = 35;

  //  Purple flame:
  //  int r = 158, g = 8, b = 148;

  //  Green flame:
  int r = 74, g = 150, b = 12;

  //  Flicker, based on our initial RGB values
  for(int i=0; i<strip.numPixels(); i++) {
    int flicker = random(0,55);
    int r1 = r-flicker;
    int g1 = g-flicker;
    int b1 = b-flicker;
    if(g1<0) g1=0;
    if(r1<0) r1=0;
    if(b1<0) b1=0;
    strip.setPixelColor(i,r1,g1, b1);
  }
  strip.show();

  //  Adjust the delay here, if you'd like.  Right now, it randomizes the
  //  color switch delay to give a sense of realism
  delay(random(10,113));
}

And a ripple effect that needs a restructure by suhajdab
#include <Adafruit_NeoPixel.h>
#define PIN 2
#define Pixels 24
#define BG 1
Adafruit_NeoPixel strip = Adafruit_NeoPixel(Pixels, PIN, NEO_GRB + NEO_KHZ800);

int color;
int center = 0;
int step = -1;
int maxSteps = 16;
float fadeRate = 0.6;
int diff;

//background color
uint32_t currentBg = random(256);
uint32_t nextBg = currentBg;

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop () {
  ripple();
}

void ripple() {
  if (BG){
    if (currentBg == nextBg) {
      nextBg = random(256);
    }
    else if (nextBg > currentBg) {
      currentBg++;
    } else {
      currentBg--;
    }
    for(uint16_t l = 0; l < Pixels; l++) {
      strip.setPixelColor(l, Wheel(currentBg, 0.1));
    }
  } else {
    for(uint16_t l = 0; l < Pixels; l++) {
      strip.setPixelColor(l, 0, 0, 0);
    }
  }

  if (step == -1) {
    center = random(Pixels);
    color = random(256);
    step = 0;
  }

  if (step == 0) {
    strip.setPixelColor(center, Wheel(color, 1));
    step ++;
  }
  else {
    if (step < maxSteps) {
      strip.setPixelColor(wrap(center + step), Wheel(color, pow(fadeRate, step)));
      strip.setPixelColor(wrap(center - step), Wheel(color, pow(fadeRate, step)));
      if (step > 3) {
        strip.setPixelColor(wrap(center + step - 3), Wheel(color, pow(fadeRate, step - 2)));
        strip.setPixelColor(wrap(center - step + 3), Wheel(color, pow(fadeRate, step - 2)));
      }
      step ++;
    }
    else {
      step = -1;
    }
  }

  strip.show();
  delay(50);
}

int wrap(int step) {
  if(step < 0) return Pixels + step;
  if(step > Pixels - 1) return step - Pixels;
  return step;
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos, float opacity) {

  if(WheelPos < 85) {
    return strip.Color((WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity, 0);
  }
  else if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color((255 - WheelPos * 3) * opacity, 0, (WheelPos * 3) * opacity);
  }
  else {
    WheelPos -= 170;
    return strip.Color(0, (WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity);
  }
}

So, can someone help me how to include these 2 effects based on the tutorial (unfortunately not much help on my current skill level) to the first code? Much appreciated.

You see in the second part is a void ripple(){, which is just like a void loop(){ but only runs when it is called.
You can merge these codes by placing an if-statement after your void loop(){ to check if it needs to run the loop or the ripple. You can simply use a boolean for this. For example:`
void loop(){
  if(state == true){  //I've called the boolean state
    ripple();  //this calls the ripple function, and runs void ripple()
  }

  //here's the rest of the loop, this runs if state != true.
  //you can change state wherever you'd like.
}

You could even create a new function based on what's currently in your loop. Example:
void loop(){
  if(state == 1){
    originalLoop(); //what's originally in your loop, but now as a separate function
  }
  else if(state == 2){
    ripple();
  }

  //rest of the loop in which you can change state to 1 or 2 however you like
}

Hope this helps a bit :)

Also why are you using two Arduinos? Just use an external power source to power the NeoPixels and use one Arduino to basically do everything.

Because there are many topics how IR signal decoding and Neopixel wont work together, cause IR are based on interrupts, while Neopixel disables it.  And mainly cause i couldnt find  a good example where one arduino runs  both.


text:
Lcd display shield, no characters
So, I've been trying to make an Lcd display shield I got from ebay to work with arduino. Using this very simple code:
#include <LiquidCrystal.h>

#define RSPin 8
#define EnablePin 9
#define DS4 4
#define DS5 5
#define DS6 6
#define DS7 7

#define LCDColumns 16
#define LCDRows 2

LiquidCrystal lcd(RSPin, EnablePin,DS4,DS5,DS6,DS7);

void setup()
{
  lcd.begin(LCDColumns, LCDRows); //Configure the LCD
  lcd.setCursor(0,0);
  lcd.print("Hello, World!");
}

void loop()
{

}

Actually I've tried several simple examples, checked pins physically to make sure I'm using the right order, But no luck. backlight is on, no characters at all. Am I missing something? Or should just contact the seller to send another shield.

My guess: wrong contrast settings (on blue potentiometer)

I've tried rotate it, doesnt seems to do anything

So, after some close inspection I noticed that the blue potentiometer wasnt soldered in correctly. Also, its needs to be turned quiet a lot to have some effect. Might replace it completely. But now it works!

Usually, PCB based potentiometers require many turns (~25) to cover the full range.  If a pot has been used a lot, a poor soldering joint will indeed come loose.  A super poor soldering joint comes loose without any help from the pot.

source: Stack Exchange

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

sort: votes


text:
Getting "Undefined reference to vtable for {classname}
I have a large collection of libraries that compile correctly but won't link. I am using Visual Micro for Visual Studio 2015. Here is the complete collection of error messages:
CommandPattern3.cpp.o:In function `DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
CommandPattern3.cpp.o:In function `__static_initialization_and_destruction_0
CommandPattern3.ino:undefined reference to `DualMotorRomeo  ~DualMotorRomeo()
collect2.exe*:error: ld returned 1 exit status

Error compiling for board Arduino/Genuino Mega w/ ATmega2560 (Mega 2560)

I have been through the code with a fine toothed comb, but cannot see what references are undefined.
Is there some Windows 10 utility that can examine the vTables and help me find what is missing?
The code base is too large to post, but I can provide a ZIP file with all the code in it for anyone willing to help.

The linker is trying hard to help you. Check DualMotorRomeo.h and that there is a destructor (might need to be virtual depending on the inheritance?).

I don't have the header file for DualMotorRomeo, but the linker is saying that a destructor has been declared (~DualMotorRomeo()) in the class header, but no destructor has been defined. If you didn't write DualMotorRomeo then the library needs to be updated.
Until then, simply add the following to one of your source files:
DualMotorRomeo::~DualMotorRomeo() {
} // DualMotorRomeo::~DualMotorRomeo()

That will also fix the vtable linker errors - the vtable will be included in the compiled file with this declared in it.

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


text:
Will Funduino Joystick Shield work on a Mega?
I am trying to get a Funduino Joystick Shield working with an Arduino Mega and I need to use the WiFi capability. The specs I have found for the Funduino (see https://protosupplies.com/product/funduino-joystick-shield-v1-a/) use the standard UNO pins for the RF24: 9..13, The Mega uses pins in the high 40s for this interface. Is there a way to make this work?

The MEGA pins needed to support the SPI interface used by the nRF24L01 are 50, 51 and 52. I can easily assign these pins in my software, but to physically connect them, I need to understand where the other end of the wires goes. Do I disconnect the WiFi header create a separate header? This seems like a bit of a kludge to me. It' easy to say, "Just use these pins..." but not so easy to determine HOW to use them.

The shield will work on Mega, except of the SPI connection for the nRF24L01 connector. The shield expects SPI on pins 11, 12, 13 and Mega has them on 50, 51, 52. Other shields use the SPI pins on the ICSP header to have compatibility with different boards. This shield doesn't connect to the ICSP header.
You can wire the nRF24L01 to SPI pins on 50, 51, 52.

Thanks for the partial clarity. My question is now, HOW do I do this rewire given that the Funduino is sitting on top of the Mega, blocking all access to the pins.

Does the hardware automatically reroute the ports to pins 50-52 allowing me to just change how the nRF24 is addressed in  software?

@BobJones, as I see it, pins 50 to 53 for SPI and usual CS are not covered

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


text:
Problem with passing string pointer from child to parent
I am trying to pass a pointer to a const char * from a child to its parent, but I am clearly not understanding how to do this correctly. Here is the code which contains three classes:
1) parent
2) Alpha (child)
3_ Beta (child)
#pragma once
class Parent {
protected:
    char *childName;

public:
    Parent ( char* _childName ) {
        childName = _childName;
    }

    char *getChildName () {
        return childName;
    }
};

class Alpha: public Parent {
protected:
    const char* alphaName = "ALPHA";

public:
    Alpha (): Parent ( alphaName ) {
        Serial.print ( F ( "My name is " ) );
        Serial.println ( getChildName () );
    }
};

class Beta: public Parent {
protected:
    const char* betaName = "BETA";

public:
    Beta (): Parent ( betaName ) {
        Serial.print ( F ( "My name is " ) );
        Serial.println ( getChildName () );
    }
};

Alpha *alpha;
Beta *beta;
void setup () {
    Serial.begin ( 115200 );
    while (!Serial.availableForWrite ()) {}

    alpha = new Alpha ();
    beta = new Beta ();
}

void loop() {}

And here is the output I get:
My name is �
My name is �˵

try to add const to all char*. on what mcu architecture do you compile and run it?

I tried your code, after adding the missing const to have it compile, and I get the expected output: "My name is ALPHA\r\nMy name is BETA\r\n".

A long time ago a senior programmer told me the correct way of defining literals was to do const char betaName[] = "BETA"; unfortunately I can't remember the precise details but it was to do with the way the memory was allocated.  HOWEVER this was back in the 90's so hopefully the compilers are better now.

The short version is that const will entice the compiler to use program memory (which is usually more abundant) to store the value rather then data memory (which is usually less abundant).  Notice all the "qualifiers" I used?  This is because different compilers and platforms combinations will likely have different results.

The problem here is that alphaName and betaName are member variables. That means they are initialized during the Alpha and Beta constructors. However, the superclass constructor of Parent is always called first, before calling the child class constructors. Result: Parent::Parent(char *) is called with an uninitialized pointer.
Here is your code on the Compiler Explorer: https://godbolt.org/z/otAuQU
As you can see, Alpha::Alpha() compiles to the following:
call Parent::Parent(char*)
ldd r24,Y+1
ldd r25,Y+2
ldi r18,lo8(.LC0)
ldi r19,hi8(.LC0)

.LC0 is the string "ALPHA".
The solution here is to make the names static. That way, they are initialized before the parent constructor is called.
class Parent {
  protected:
    const char *const childName;

  public:
    Parent(const char* childName) : childName(childName) {}

    const char *getChildName () const {
        return childName;
    }
};

class Alpha : public Parent {
  protected:
    constexpr static const char *alphaName = "ALPHA";

  public:
    Alpha() : Parent(alphaName) {
        Serial.print(F("My name is "));
        Serial.println(getChildName());
    }
};

This compiles to:
ldi r22,lo8(.LC0)
ldi r23,hi8(.LC0)
call Parent::Parent(char const*)

As others have mentioned, pointers to string literals should always be const. The only reason this doesn't give an error is because the Arduino folks decided that it was a good idea to compile everything with -fpermissive ...
Mutating a string literal is undefined behavior, so an error.

And the award goes to tttapa who has now fried a few of my remaining brain cells with his precise and correctly working code sample. Thanks, tttapa! And now I have a lot of code that needs fixing.

@BobJones, I think using const char* should be enough and Edgar Bonet reported it working in a comment. But we don't know the platform you are using

@Juraj, I think that's still undefined behavior. The reason that it appears to be working is that the compiler optimizes it because it knows that it will be constant. However, there is no guarantee that the pointer should be initialized before calling the parent constructor, it's just a happy coincidence.

C++ reference "Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished." https://en.cppreference.com/w/cpp/language/initializer_list

@Juraj, I'm not talking about the constructor body, I'm talking about the Parent constructor. First the Parent::Parent(const char *) constructor gets called, the Parent member variables are initialized (childName), then data members of Alpha are initialized (alphaName), and finally, the body of Alpha::Alpha() is executed.
I just tested the original code with added const on an UNO with version 1.6.23 of the AVR Core. It doesn't work. When the names are static, it does work.

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


text:
Fastest communication between Arduino and PC
I am using an Arduino 2 which collects data from a set of microphones and stores it in an array of unsigned short of 40000 elements and sends them to the PC via Serial USB.
It is working but I'd like to obtain more speed without any errors.
Can you suggest me the best way to do it? Even changing communication.
Thank you

Which USB serial are you using? The ATMega port or the native USB port?

And what baud rate, and what encoding?  How fast does it currently go, and how much faster do you want (well, need) to achieve?

I am using the programming port.

115200 Baudrate, I would like to obtain the best performances for a semi-real time application. I am currently using Serial.println(value1, value2, value3, ...,value8)\n.  In PC parsing of the datas I sometimes get errors because it sends two different row in the same. Thank you

So, again, how fast does it currently go, and how fast do you need it to go?  At 115kbps, you could in principle, suitably encoded, send 40k 16bit values in about 5.5 seconds.  How long is it taking in your implementation, and how long do you want it to take? Everyone wants the best performance (and the least effort and the lowest cost and the highest reliability). Give us a clue.

Switch to using SerialUSB instead and use the other USB port. The baud rate is meaningless then - it runs at the speed of the USB port, which is a lot faster than serial (Linux reports it as 480Mbps, though I can't see an 84MHz chip doing that...).
void setup() {
    SerialUSB.begin(115200); // The number is irrelevant but it needs something in there
}

void loop() {
    SerialUSB.println(millis());
    delay(100);
}

For greater throughput you could devise some packet-based binary protocol to optimize your data flow to use less bytes.

seems legit.  How to do it?

SerialUSB.begin(115200); SerialUSB.println("Whatever"). And plug into the other socket of course.

Why the delay? Is to avoid errors or just to simulate stuff?

That is just a simple example so you can see the port working. The delay has no purpose other than to allow your eyes to register what they are seeing before it is gone.

SPI: technically no upper limit so long as both parties can keep up and the wires are good enough. Mbps easily doable.

I am already using SPI for communication between Arduino and an ADC shield. Can I use it anyway and how?

spi targeting is controlled by the _CS pin(s). Multiple spi devices can hang off the same bus - assuming your shield is properly designed.


text:
What's the problem with baudrate?
I was trying to evaluate the speed of communication between pc and Arduino, using this code in Arduino:
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Ciao Arduino");
}

and this in Python:
import time, serial

arduino = serial.Serial('/dev/cu.usbmodem1421', 250000)

time.sleep(3)
count = 0
start = time.time()
while True:
   a = arduino.readline()
   print a
   count = count+1
   time1 = time.time()
   if time1-start >1 :
      print "--" + str(count)
      print a
      count = 0
      start=time1

Wich print out how many readline() he managed to do to evaluate the speed in further project.
And I realized two things:

The program is working even with different baudrate
and with correct baudrate(For ex. 300-300 or 250000-25000) the baudrate is irrelevant(and wrong), I mean the 300 baudrate makes 20000 readline() and the 250000 make 5000 of them.

What's the problem? thank you

On the Micro I can understand that being the case. You tagged Uno as well. Are you sure you have experienced that on the Uno?

On a direct USB CDC/ACM connection (as you get on the Micro) there is no such thing as baud rate.
Any baud rate setting performed by the host (the PC) is merely an instruction to the device (the Arduino) to say "I would like you to operate at this speed", not "I would like you to communicate with me at this speed".
It is used in situations where the PC may want to set the baud rate of a real UART interface within the device, such as when the ATMega16U2 is used as a USB interface on the Uno - in that case the PC tells the 16U2 that it wants to communicate at, say, 115200 baud, and the 16U2 sets its UART (the one that communicates with the ATMega328P) to 115200 baud. The actual PC to ATMega16U2 (or ATMega32U4 in the case of the Micro) is at the native USB 2 bulk packet rate.

It is also used as a "reset" instruction to the ATMega32U4 - if the CDC/ACM port is opened by the PC at 1200 baud and then immediately closed again the 32U4 resets and enters the bootloader. This makes programming (usually) easy, as long as the program on the chip hasn't crashed and left the USB interface in an unusable condition (as sometimes happens).

Another question: It is right to think that the native usb used with micro is way faster than the ATMega16U2? Now I am using the Arduino Uno, and it makes(at 400'000 baudrate) 2855 readline(), while the Micro achieved 20'000.

No, the USB is the same on both. The bottleneck is the connection between the two chips on the Uno which runs at the baud rate you specify, and is limited to less than the rate of USB.

Is there any difference between Android setting baud-rate when connecting to Arduino via USB/serial and putty setting baud-rate when connecting to (virtual) COM-port (Arduino again)...?


text:
How to create a smooth change in voltage?
We are given two voltages A and B between 0 and 5V.
So how do I generate a smooth/continuous analog change in
voltage from A to B in a predefined time? The current with that varying voltage is 1 ma or less. The output voltage value is described by a simple quadratic (aX^2)+(bx)+c, at time x seconds.
If that not possible using an Arduino - what is the nearest  solution to it? It seems that it would require an RC circuit?
When I mean smooth/continous I mean it doesn't move in "digital steps" or to use an analogy with resistance instead of voltage - it would be like the way resistance changes when a potentiometer is turned between two places, in a given time, by hand.
A potential solution would be to make a circuit that generate arbitrary voltage between 0 and 5v, some how, at a point in time. For each subsequent small change in time, the change in time is constant, generate the desired voltage from a sketch. If the change of time is small and constant, will putting in a high pass RC filter work? Though I'm not sure of a circuit that can create an arbitrary voltage, or arbitrary voltage resolution or how good the RC filter approximates the quadratic smoothness. I don't know the answer.

If your only constraint is that the change be smooth, then an RC circuit would do the trick, with the proviso that the voltage will approach 5v asymptotically but never truly get there. Are there in fact other constraints, such as you want the voltage to increase linearly, so after half the time you have half the voltage?

What kind of load will be attached to it? An RC filter will not work well with highish loads. You need to buffer it using an opamp. Alternatively add an DAC chip to your circuit.

@MarkSmith The asympotitic behaviour is not really a problem (because I think  you can use an opamp to rescale from between greater than 0 and less than 5 volts). .But I would prefer a solution without op-amps. Regarding the linear behaviour -I updated the question.

@Gerben It sounds like the answer may be in your comment (use RC filter and OP amp).

The quadratic requirement is quite significant - I can't think of any way to get that with an RC circuit, op-amp or no op-amp.

@MarkSmith  I think there got to be a way to do it -but I dont know how good my potential solution given in the question is.

Depending on the speed and power requirements, real, physical components will smooth per their equivalent RC component circuits.  If you want it smoother, or if you want control over the shape between the "digital steps", use a higher resolution DAC to minimize the deviations between your ideal curve and the output.

I'm not sure that there exists a perfect solution for what you want.  Generating the correct output voltage for time is easy.  Just keep track of time and use the formula you wrote to compute the correct voltage you should be at.  Then you can use a PWM output.  However, this isn't going to be perfect since it is made with pulses rather than a continuous output.  On the Uno the pulses are at 490Hz or 980Hz depending on which pin you use.  Use an RC filter and you can then make it continuous - when you tell it output 2.5V you get 2.5V rather than 0 then 5 then 0 then 5 in short bursts.  But, you're still going to get discrete steps based on the resolution of the ADC - for an Arduino Uno, it's 255 steps I believe.  You could get a separate DAC chip to increase this and can probably get enough steps that their small enough you won't notice.  Some versions of the arduino like the due have 12bit analog output and higher frequency, which should help.

It all depends on how literally you want to interpret the requirement of "continuous".  You could have a million-bit DAC and it'd still be discrete, but the intervals would be tiny.  8-bit might be "continuous enough", depending on the application.

@MarkSmith It all depends on how literally you want to interpret the requirement of "continuous" I wonder if that is really provably true. Because you could base an answer on the following idea- you could get a servo to turn a potentiometer to turn a cam-that encodes the shape of the quadratic functrion. And using the resistance with ohms law you can answer the question is some circumstances.

@Pete OK, I could have worded that better. You can make it continuous by putting a capacitor in to low-pass filter out the step - in fact given small-enough steps, even stray capacitances will do that. But the smoothing is just smoothing - it doesn't make the voltage equal the function. If you "zoom in" far enough, you'll see the errors. It's just a case of when it stops mattering.


text:
Interrupts on the Arduino NG
I am a newbie to using arduino.
I am using an arduino NG  (using an atmega8). One of the pins is a button that triggers an interrupt.
The problem I am trying to solve is that I want an arduino NG to store the timestamp (we are using mills as a timer -no need to consider the 50 day rollover error here) when the interrupt pin is pressed.
The timer of the interrupts in milliseconds is stored in an array and there are up to 100 such interrupt button presses.
After searching around I didnt find any information for using interrupts with atmega8 on arduino NG (though there is information of how to use interrupts on atmega168 with arduino NG ).
So my question is: Is this problem solvable with an atmega8 arduino NG? Does the atmega8 arduino NG have interrupts? Just need one interrupt. And what would be the code to read an interrupt on atmega8 version of arduino NG?

Why do you believe that the ATmega8 is that different from the ATmega168 given that the Arduino libraries are designed to abstract away details?

@IgnacioVazquez-Abrams regarding interrupts atmega8 is different168 there-so that may imply the the same code wont work -and I couldnt find any examples when searching

Does the atmega8 arduino NG have interrupts?-

Page 1 of the datasheet:

Yes, it has interrupts.

just need one interrupt.

Page 46 of the datasheet:

It looks like you have 19 of them.

regarding interrupts atmega8 is different168 there-so that may imply the the same code wont work -and I couldnt find any examples when searching

Try using the Arduino libraries. If that doesn't work post your code.

ATmega8-family chips have 19 interrupt vectors, vs 26 in ATmega48/88/168/328-family chips.  (See Table 16.1, Interrupt Vectors in ATmega8A, in chapter 16 of ATmega8 documentation; and see Table 12.1, Interrupt Vectors in ATmega48A and ATmega48PA; Table 12.2, Interrupt Vectors in ATmega88A and ATmega88PA; and Table 12-4, Reset and Interrupt Vectors in ATmega168A and ATmega168PA, in chapter 12 of the ATmega48/88/168/328-family datasheet.)
Both families have INT0 and INT1 External Interrupt Request pins, so if either of those is the pin your application depends on, it should work ok on an ATmega8 system.
I don't see any mention of pin-change-interrupts in ATmega8 documentation so an application depending on PCI's probably wouldn't work.

You should check against the datasheet;

Does the atmega8 arduino NG have interrupts?-just need one interrupt.

It has two external interrupts.

And what would be the code to read an interrupt on atmega8 version of arduino NG?

google or read the datasheet. It is fairly simple to set up and use.


text:
Using 8bit ports as 8bit I/O variable (while using USB,I2C, SPI and Serial) - keyboard
I am seeking HW.
I would like to make keyboard with enhanced functions (RGB backlite, macros, programmed profiles etc) driven by some small MCU (Arduino Micro Pro or something similar).
To support communication, it needs to use I2C and SPI(for display and other devices), use USB (to communicate with PC) and use Serial to communicate with other Arduinos/MCUs.
The main function would be scanning keyboard matrix (like from 8x8 to 16x8 in maximal variant). The matrix would use diodes for NKRO (not ghosting, any key combination possible).
It would be really nice to have HW, where I could use 3 full ports as input (or as output) with benefit of reading/writing them with only one assembly instruction for 8bit manipulation, not to cycle over array of pins and manipulate each one independently (digitalRead/digitalWrite, which use tons of instructions to determine ports and pin and then combine them together to obtain one 8bit variable). Something like:
byte dataout,datain1,datain2;
PORT_A=dataout;
datain1=PORT_B;
datain2=PORT_C;

Does anyone know, if there is such nonexpensive MCU and which type it is?
On typical Arduino each port is "poluted" by some importaint communications pins, so none of them can be used as full 8bit I/O.
Second question: Is there a reason, why are the most used communication pins spread over range of different ports and not collected on one port, while leaving other ports as full 8bit GPIO useable?
Thank for all answers.

Seems mostly a problem of how many pins you need for your keyboard. You didn't state, how many pins you need. You seem to need an MCU with native USB support.

Define "Non-Expensive"...

Personally I'm a fan of the PIC32. It has 16 bit IO ports not 8 bit (though not all pins are populated on all ports), so you could LATE = dataout; datain = PORTB; for example.

@chrisl Yes, I want to make USB keyboard for PC (and also use it for other purposes so need to suppor I2C, SPI and UART too) Except this, I want for the keyboard 8+8 pins (for matrix 64 keys) or better 8+16 pins (for full keyboard with aditional keys like macros, multimedia, layout switches etc.)

Personally I do not see the need to save some instructions. Mostly you want combined ports to achieve high performance, but a keyboard is operated by a human normally, which is VERY slow compared to an MCU scanning all keys. Or do you need microsecond latency?

You can use shift registers (both parallel-in-serial-out and serial-in-parallel-out) connected to the SPI bus. You can then transmit one or two bytes over SPI, which is extremely fast (8 MHz clock on even the most basic Arduinos). You can daisy chain two shift registers if you want 16 inputs.
As others have mentioned, you don't really have to worry about the speed of human input devices.

@Majenko nonexpensive - I am using some Arduinos from aliexpress, about 2-3EUR each and at worst I can add some shift register for few cents to expand pin count and be able to do the work. On Arduino shop the same are about 8-20$. Both works well. So something around this range (say 1-30$?, not 100+$)

tttapa+MichelKeijzers: I know that, but was also thinking about some "code elegance" as why do 8 loops of about 50 instructions each for what could be done by just two instructions as well (so in like 200x less). I know I can do it somehow anyway and do all others tasks also somehow  (like the USB and manipulation of 20+ WS2812B
LED and OLED display and rot. encoder and who knows what else I came with) to not be excesivelly slow, but it counts together fast and I would like for once do it effective, not just pile library over library and compensate unnecessery ineffectiveness with faster HW.

You could read and entire port, and apply a mask, so only the bits you're interested in remain. Slightly more code, but faster than 16 digitalReads. But I'm counting that you'd need 32 GPIO pins, plus USB, So I think that's the problem you should focus on.

@Majenko is there some PIC32, which you would recomend me for start? Having USB and beat AVR32U4 is enought for me to give it try :) (So probably some cheaper model would be more than enought)

@Gerben for my current try it is 2 (I2C display+communication PD0-1) + 4 SPI (PB0-3) + USB (D+ D-) + 2 Serial (PD2-3) + 16 GPIO (PB4-7,PD4-7, PC6-7,PF0-1,4-7 ) - from that 16 GPIO I would use 8 as inputs, 1 for LEDs, 3 as outputs for 3-to-8 decoder (as only 1 row is active at each time) and have 4 free, or I would use 7 as outputs for 8x7 matrix which works for normal keyboard (128 keys, no external chip).

@gilhad You could do worse than the Fubarino SD

@Majenko thank you :) Looks interesting :) I will try it :)

If you use a diode separated key matrix, I don't see a way to press two or three keys at once if you don't implement a anti ghosting algorithm in your controller. To work, the capturing of the pins must be very fast. Nearly at once. And the mcu must be fast enough to find even a really short delay for pressing two or three keys. If there is a delay we, assume a human pressed the keys. That's anti ghosting. An expensive way of avoiding ghost keys is reading all keys separate  into a chain of shift registers. Or build a DAC with a resitore chain and read the analog value. One Channel = 10 Bits

To answer your second question: The pin setup depends on the internal layout of the chip. It is easier the have functional groups in their own blocks, e.g. the clock logic and the shift registers. The manufacturer chooses the pin position the way, it needs the shortest wiring of the gold wires and also it should avoid crossing wires.

@PeterPaulKiefer Key matrix input is read in the way, tah you attach signal to one row, then read all collumns to see, if signal is there. If it is there, then the key on crossing of row and collumn is pressed. Then continou with other row and after you check all rows, you know, which keys are pressed. Ghosting happens, if there are no diodes and user press keys on 3 crossings, that forms rectangle. Then even for the unpressed crossing is there signal, as it travels over the rest 3 and "ghost key" is detected, as we see the signal there, even if the key is not pressed. No speed helps here.

If there ARE diodes, then pressing the 3 keys does not make way for the 4. as diodes disallow the signal freelly travel to other rows. Even slow mcu can read that safely (as long as it does that faster, then human free the keys - say in 0.1s = eternity for mcu. Faster mcu can get more precise time of pressing, nothin more). No special algorithmus is needed here too. Normal matrix works fine. See also this answer: https://arduino.stackexchange.com/questions/66691/which-kind-of-diodes-i-should-use-in-buttons-keys-matrix-input-making-gaming-k/66710#66710

It was late, I was tired, sorry I forgot the "don't" : My intention was to write: "If you don't use a diode separated key matrix, ....".  You're right that you have to press at  least 3 keys to get the ghost effect. And of cause two of the pressed keys must be on the row that is powered "ghostly" by the third pressed key. Mea culpa, thinking while writing is helpful. ;-) By the way, I have already created some keyboards, it's not my main business but from time to time ... . They have to work in harsh environments. Sometimes for some reasons I'm not allowed to place diodes in the key matrix.

One of these projects required me to allow the user to press a maximum of four keys out of sixty four and I was not allowed to use diodes. In the end we solved it by using a 16 Bit shift register. We powered the rows and read the cols and we had to handle the ghost keys. We used an algorithm that was called the anti ghosting algorithm in the literature we studied. This checks whether the signals of the pressed keys comes quick enough to interpret it as a ghost signal or if the user had really pressed the keys.

We did not check how quick the user released the key we check for the very fast time the power jumps from one row to the "ghost" row. The smaller the checked  time intervals, the more reliable is the recognition of a keys. And that you dream of testing in the nano second scale. But even with this algorithm the reading was not reliable because sometimes we were not fast enough or the the keys were pressed in an an unlucky order. We detect user pressed keys as ghost keys. Then we tried to build a Resistor based DAC. with 7 channels to read the 64 Keys. This works fine but failed in production.

It failed in production because there was strong EMI. And the analog inputs got unreliable. At the end we capitulated and used four of the sixteen bit shift registers to read each key separately. The was the long story of the short comment above. I didn't what to teach you how keyboards work. I just want to show you what we had done, so could used it for your decisions . I'm not a native English speaker. In fact my English is very poor. So I did not recognize, that I made some errors, and I had not written with the precision I would write if I write German texts. But I promise, I'll  practice

@PeterPaulKiefer Yes, "don't" can make big difference sometimes :) My English is also far from perfect (4. language learned) - and I am from Czech. Your answer confused me, so I went to longer explanation. At the end there is none disagreement between us :)

Yes, that's right ! And I forgot: Thank you for pointing me to the errors. ........ And there is still one thing. You wrote, you want to connect the keyboard using USB (among other methods). If you intent to use the keyboard as a HID device (which you should ;-) ), the board you'll choose should be able for this. I know that the Leonardo and the DUE have this feature. Here is a link that explain the usage for a keyboard: https://www.arduino.cc/reference/en/language/functions/usb/keyboard/

And if you choose for a e.g. Mega as suggested in one answer, this video might be helpful: https://www.youtube.com/watch?v=bTlM27jzOIQ

@PeterPaulKiefer I am using Micro so far, which have also HW USB ability :) http://micro-corner.gilhad.cz/blog/Arduino/progs/KlikiMouse3/images/klikimouse.s.jpg http://micro-corner.gilhad.cz/blog/Arduino/progs/KlikiMouse3/2019-04-29-Arduino-progs-Klikimouse3.html as it is pretty cheap from Aliexpress :)

Funny, I saw this part so often in the internet stores but was not aware of that feature. It has a 32u4 MCU. Thank you for pointing me to it. So you will use this in addition to a bigger MCU that can read the keyboard inputs? Or do you plan to use shift registers (aka port expander; like the MCP23S17)?

If you are interested in other brands: Do you know the STM32 Nucleo F-series?  These are boards with STM32 ARM M0-M4 MCUs in a price range from 10 to 20 dollars with arduino headers and own headers (Morpho) with a full pin out ~ 55 IO Pins. They have also a rich set of communication interfaces. Here is a link to the F3 series MCU https://www.st.com/en/microcontrollers-microprocessors/stm32f3-series.html. (Oh and they have a flexible interconnect matrix. Choose your pins ;-) )

@PeterPaulKiefer I would probably use much cheaper 74HC138 or 74HC595 for output or 74HC165 for inputs :) or just use Blue Pill as I did for old PS/2 keyboard :) http://download.gilhad.cz/STM-keyboard.s.jpg

I'd go with a Mega2560. Up to 86 IO if you use a board that breaks out all IO pins, otherwise 70 on the Arduino version. With a little attention to the physical chip pin mapping to the board you can have several full 8-bit ports while also using SPI, I2C, and Serial via one of 4 UARTs. I'd recommend keeping Tx(0)/Rx(0) free for comm's with PC via USB adapter for code download/debug. Tx1/Rx1, Tx2/Rx2, Tx3/Rx3 are them free for 0/5V level comm's, or other levels via USB adapter, RS232 adapter, etc.

The expander MCP23S17 (spi), with a CS, is a good extention (16 I/O configurable)
That should do it !


text:
How get assembler/preprocessed code for library
I am using https://github.com/sudar/Arduino-Makefile project with https://github.com/ladislas/Bare-Arduino-Project to compile my Arduino projects from Linux command line. I put as much as possible functionality to libraries for reuse (and use the same libraries from many projects too).
Now I had run to some problems and I am not sure, if I am using the language (C/wiring/...) properly, as a lot of #define macros are used. I think, that seeing the resulting code would help me greeatly in finding, wheather some specific lines are compiled into what I want them to be compiled. I am interested mainly in the library code, even if it would mean to dump full program together with all used standard libraries. (I can find my way in large files.)
I would prefere intermediate files, as I suppose they could contain more info than just dissassembled .HEX file, but if this assumption is not correct, and I can get the same from .HEX, than I can use that way as well.
Question: How to get intermediate files (Ideally both "plain C" after preprocessing all macros AND "plain ASM" after compiling the code) ideally with corresponding lines of original code as comments inside.
Subquestion: In the above, how to disable optimalisation as much as possible, to get the code more verbatim similar to original C (I know, that it would hurt both speed and size and I do not care - I just want to be sure compiler does undertand my code the same way as I myself and if not, then see, where I made mistakes)
Thanks for all suggestions :)

seeing the resulting code would help me greeatly in finding, wheather some specific lines are compiled into what I want them to be compiled. - what, exactly, do you "want" them to be compiled into? The compiler generally compiles your C++ code accurately into machine code. Are you suggesting you could find flaws in the way it does that?

Exactly the other way. "Computer does every time exactly what you command it to do and never what you want it to do." I have some idea, I write a code and it does not work. So it means, there are some bugs. Some are in logic, some are in syntax, where I write command, which does something other, than I had in mind, when I wrote it. But seing the generated code means I see the same as computer and then I can see, that this value should not be here but there and should read this way. So that I wrote the command wrong. And should write it different way. Because I made some bad assumptions

http://stackoverflow.com/questions/42617079/how-to-pack-mix-of-up-to-4-uint-8t-and-int8-t-into-one-uint32-t

For example here http://stackoverflow.com/questions/42617079/how-to-pack-mix-of-up-to-4-uint-8t-and-int8-t-into-one-uint32-t I had bad types in the code, so it does not worked exactly as I needed. Writing some (uint8_t) here and (uint32_t) there solved problem. Finding where and what to write took much more time, than to do it then. Seeining the generated code can show me, where are bytes loaded to registers and where are converted to int16_t (which I did not want), then shifted, and that the shifts should be in 32-bits, not 16-bits blocks. Faster to read the result code, than to test values

One method I've used for creating assembly listings for Arduino sketches when using the Arduino IDE is as follows:
• Click Verify to compile the sketch
• Locate the the temporary build directory
• Use avr-objdump with -CSI... switches to decode the ELF file
Here are some commands you can put into a shell file to automate that procedure, on a Linux system:
item=*.ino
[ -z "$item" ] && echo ino file not found && exit
BDIR=/tmp/$(ls -t /tmp | egrep -m1 build.*tmp)
BASE=$(basename $item .ino)
avr-objdump -CSI$PWD $BDIR/$BASE.cpp.elf > $BASE.ino.asm

The above assumes the current working directory (ie, $PWD) is the directory with the sketch in it; variable item is the sketch name; variable BASE is the basename of the sketch, with .ino stripped off; $BDIR is the most-recently-used temporary build directory (which, on Ubuntu Linux systems, has a path that starts with /tmp/build); and the resulting deassembly is placed in $BASE.ino.asm for viewing.
To try this manually, as you may need to do on systems where the above shell commands don't work, say
avr-objdump -CSIddd bbb/sss.cpp.elf > sss.ino.asm

in a shell or at a command console, replacing ddd with the sketch's source directory name; bbb with the temporary build directory's name; and sss with the sketch's name.

Edit 2: Using Sudar's Arduino Makefile probably is the best starting point for looking at source code that has been pre-processed, or that has been compiled (into assembly language).  This makefile system is fairly easy to install and use.
When you have the makefile system  installed and working, you can generate  pre-processed code (code that's been run through the pre-processor to incorporate #include files and to expand macros) by adding the following line within a makefile:
CPPFLAGS += -E

The -E switch tells avr-gcc to stop after preprocessing.  According to man gcc its effect is:

Stop after the preprocessing stage; do not run the compiler proper.  The            output is in the form of preprocessed source code, which is sent to the            standard output.

To generate assembly language, add the following line within a makefile:
CPPFLAGS += -S

The -S switch tells avr-gcc to stop after compiling.  According to man gcc its effect is:

Stop after the stage of compilation proper; do not assemble.  The output is in the form of an assembler code file for each non-assembler input file specified. ... By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.

If you are skilled at makefile writing, it may be possible to add a target with rules to generate assembly or pre-processed code for inspection.  Actually, Sudar's Arduino Makefile appears to have assembly-listing targets and rules already (as below for .pde; others for .ino and .cpp) although I haven't gotten them to work:
# generated assembly
$(OBJDIR)/%.s: %.pde $(COMMON_DEPS) | $(OBJDIR)
        @$(MKDIR) $(dir $@)
        $(CXX) -x c++ -include $(ARDUINO_HEADER) -MMD -S -fverbose-asm $(CPPFLAGS) $(CXXFLAGS) $< -o $@

[I now see that Edgar Bonet has mentioned this too.]

Thanks, the -S flag is nice.  Do you know about way to get preprocessed files too? This one dissassemble the compiled code, but I would like also to see the preprocessed code, where macros are expanded, but it is still the text, not binary translated back. (so I can see eq. a=16|4|2, not just loading 22 to some memory location)

@gilhad, I wasn't sure what you meant by preprocessed.  See -s or -S flag to avr-gcc, I don't remember which, will look tomorrow

accepted & upvoted. Just for record it can be called from command line like CPPFLAGS+=' -E ' make  respective CPPFLAGS+=' -S ' make  after make clean (to force generating code for everything)

You can get the generated assembly by passing the -S option to
avr-g++. The makefile you are using has a rule for that, so you would
just type
make build-*/my_file.s

to get the assembly for my_file.cpp.
For the pre-processed C++, you use the -E option. There is no rule for
that in the makefile, so you will have to write yo own, or manually
invoke the compiler. At a minimum:
avr-g++ -mmcu=my_mcu -E my_file.cpp > my_file.i

You may want to add -DF_CPU=... -DARDUINO=... just like the makefile
does when compiling the same file.


text:
multiple definition of local variable in linking
I am trying to make my own library and it uses some local variables with the same name as some variables in ino. Compiler complains about it. I stripped it to (nonsence but simple) example
mylib.h:
#ifndef MYLIB_H
#define MYLIB_H
int doit();
#endif

mylib.cpp:
#include "mylib.h"
int value;
int doit(){
    return value++;
}

example.ino:
#include "mylib.h"
int value;
void setup(){
    value=3;
    pinMode(13,OUTPUT);

}
void loop() {
    digitalWrite(13,(value==doit()) );
}

compiling:
$ make
/usr/bin/avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p example.o mylib.o .lib/arduino.a -lm -o example.elf
mylib.o:(.bss.value+0x0): multiple definition of `value'
example.o:(.bss.value+0x0): first defined here
collect2: error: ld returned 1 exit status
/home/gilhad/GIT/HW/Arduino/minipro//../Arduino.mk:436: recipe for target 'example.elf' failed
make: *** [example.elf] Error 1

I am not usint the value in the .h file, so why it collides with similary named variable from another module?
Should not be it private to the module until exposed via .h file?

Try the keyword "static". https://stackoverflow.com/questions/572547/what-does-static-mean

Thank you, it completly explains my question (and some more). If you make it answer, I would accept + upvoted it, as it provided good inside for me to the whole problem :)

@MikaelPatel, can you explain why this works?  From my perspective, gihad should subscribe to creating Arduino libraries using C++ (not just C) and create a class where the library's private variables would be protected (not even seen) from the Arduino sketch.

As a fact of matter, it was not even my code, but my 13-years old nephew's. And he was trying to separate few common used functions (many of which had nothing common) away for his playing with some LEDs and displays, to use it in more versions of the same program (Hello world, Hello city and such). And few of that functions shared some settings (LedOn, Color, Value).

And it did not compile, so he asked me, why and I did not know. I would wrote it in totally different way and I would not hit such problem, but I could not find, why it is not working. And say "do it much complicated way and do not even ask why it does not work this way" is not good approach in teaching. Also it signalled, that I do not know something, which I should know.  And I am planning to write much complicated projects, so I want to know not only how make things nice, but also how it works under hooks when I want to poke really deep :)

I am not usint the value in the .h file, so why it collides with similary named variable from another module?
Should not be it private to the module until exposed via .h file?

The quick answer is that a source code file is not a separate unit. The last step in the build process is to link all the object file and create the executable binary. The linker will need to resolve all the symbols. In this case there are two definitions and the compiler cannot resolve the references. The linker can be told to ignore multiple definitions.
The keyword "static" will make the symbol local to the compiled unit (object file). As the keyword "external" tells the compiler that the definition is in another compiled unit. Header files is just a structuring convention. The language does not actually say anything about this. It is a pre-processor (cpp) in the build process that creates the combined source code for the compiler.
C++ (and OOP) adds a number of ways to control the visibility of symbols (aka encapsulation). In a class definition the keywords "public", "protected" and "private" may be used. Also the keyword "static" may be used. In this case it means that the symbol is defined globally for the class (class variable) and not per instance (member variable).
The keyword "static" in C/C++ is actually a "recent" development of the languages. In the early versions of C local symbols where prefixed with underscore "_local". This is still a common practice even though the object files contain much more scope information today.
Cheers!

The common practice is to write Arduino libraries using C++ classes:

The core of the header file consists of a line for each function in
  the library, wrapped up in a class along with any variables you need.

class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

In this way you can specify what is private (variables and methods only seen within the class) and what is public (variables and methods that can be seen outside the class).  In the given example, the variable called "_pin" is private to the class Morse.
In your case, you would want to make a private class variable called "value".  Because it is private, you are free to re-use the name when not inside the class.


text:
How to prevent file overwriting in processing?
i am working on this arduino project using processing. There are some sensor values which should be logged, but unfortunately my processing code rewrites the file after each cycle so that i get the last sensor value only. How do i prevent this from happening? I am using the ordinary method by the way. PrintWriter command followed by createWriter

PrintWriter pw = new PrintWriter(new FileOutputStream(
    new File("persons.txt"),
    true /* append = true */));
The true is the append mode flag.
Also check if you're using
pw.append(p.toString());
        pw.append("sdf");
https://stackoverflow.com/questions/8210616/printwriter-append-method-not-appending


text:
Servo broken? Explanation, Solution
I had a question, I tried to control a servo with the arduino, to the servo I attached a stick and at the end of the stick a little weight. After runing my code my servo tried to move the stick, but maybe it had not enough torque to move it so after that I paused the code. Then I tried to control the servo again without weight and this time it didn´t moved. Is it broken? why? Is there a posible solution? Thanks

There is really no way for us to tell. Its possible that its broken but if all you did was stall it I find that pretty unlikly.

How are you driving these servo's? Bear in kind that servos are quite different from regular motors... http://handyboard.com/hb/faq/hardware-faqs/dc-vs-servo/

Without seeing the code you are using, it is difficult to know if you are attempting to drive the servo correctly.
Remember, with a servo, the PWM signal is a positioning signal, not a duty cycle signal as used with speed control on regular dc motors.

You may have broken the gears if the servo was not rated for the load applied or if the servo was rotated too far (by software) 1ms and 2ms should be your (conservative) software limits, though most servos will work from 0.7ms to 2.3ms.

Servo is probably broken, or fried.
Same thing happened to me, that too twice!
First time, I had fried the servo(overpowered it).
Second time, one of the gears had broken.(finally I managed to salvage one total servo by using gears from fried one in the one with broken gears)
First, try a different way to control the servo. If the servo fails to respond, then try opening up the servo.You might be able to salvage something.

P.S. If the servo is fried, there is not much you could do, but if one of the gears is broken, KEEP THE BOARD, as you can use it with another motor using Transistor H-Bridge.

If you are using a H-Bridge, you should probably use MOSFETs instead of the usual BJTs so that you can use larger Motors


text:
Simulating touchscreen input using PWM
I'm porting a project from a teensy microcontroller to the arduino. Essentially the project uses a microcontroller to simulate touchscreen input for the Nintendo 3DS console. I am doing this by unplugging the touchscreen digitizer of my Nintendo 3DS and putting my arduino in its place. See the link below for the original teensy code and schematics that I'm trying to modify. (The oscilloscope picture below is also credit of author of the teensy code)
https://github.com/dekuNukem/3xtDS
This is a fairly generic touchscreen I'm trying to simulate input for, so I'm not sure what's going wrong. I am not sure if my schematic has a problem, or if the Arduino's PWM frequency limitation is the problem. The teensy code was setup to output at 90khz, while the highest I can possibly set my arduino is around 31khz. I believe this should be good enough because I believe the Nintendo 3DS only samples at around 100 microsecond intervals.
What I have done:

I'm connecting two of my arduino pins to the X+ and Y+ pins where the Nintendo touchscreen digitizer used to be.
I have used a voltage divider to change the arduino's output voltage from 5v to 1.8v, which is the VCC of the nintendo device.
I have used a 0.22uf capacitor and 1k resistor as a DAC to change the PWM output to analog.

I tried troubleshooting by:

using 68 & 120 ohm resistors in my voltage divider for smoother analog PWM response, instead of 68k & 120k resistors
adding a 1N914 diode between the capacitor and ground (since I am using ceramic capacitors, which are bidirectional)
eliminating the while(analogRead(senseY) < 46) line in my code and instead using a static delay of 100 microseconds

Touchscreen press I want to simulate (Yellow is Y+, blue is X+):

My Schematic:

Teensy code ported to arduino:
// I've included the setPwmFrequency() function listed on the arduino site,
// but I'm omitting it here for clarity reasons.

// The main change between the Teensy and arduino is that the teensy uses
// software to lower the PWM voltage from teensy's native 3.3v down to the
// nintendo's 1.8v, while I have instead used a voltage divider on the PWM
// output of the arduino.

// X+ pin of touchscreen.
int touchX = 9;

// Y+ pin of touchscreen.
int touchY = 10;

// Pin to monitor arduino's output of Y+
int senseY = 11;

void setup() {
  // -Change pins 9 and 10 to have 31,250 hz PWM frequency. This is the
  // highest I can set it. Teensy originally set their frequency to 90khz.
  // My difference in frequencies MIGHT be the cause of my problems.
  // I picked pins 9 and 10 because they won't affect timing for millis()
  // and delay.
  setPwmFrequency(9, 1);
  setPwmFrequency(10, 1);

  // Original teensy code set analog write resolution to 9bits.
  // This was necessary because the nintendo touchscreen is 320x240, which is greater than 255 for an 8bit resolution.
  // However, I don't mind this minor accuracy loss! arduino's analog resolution is accurate enough for me.
  pinMode(touchX, OUTPUT);
  pinMode(touchY, OUTPUT);
  analogWrite(touchX, 0);
  disable_touch_screen();
}

void touch_screen_click(unsigned int x, unsigned int y, unsigned int duration_ms) {
  // Calculate PWM value to write  based on the xy touchscreen coordinates we want.
  unsigned int x_potential = ((double)x / 320) * 255;
  unsigned int y_potential = ((double)y / 240) * 255;

  // Start outputting the x value.
  analogWrite(touchX, x_potential);

  // Pull Y+ to ground.
  enable_touch_screen();

  unsigned int start = millis();

  // Keep touch screen pressed for tap duration.
  while(millis() - start < duration_ms) {
    // wait until Y+ pin is in output mode
    // original teensy code checked for 512, which was half of the max value 1024.
    // we're outputting 1.8v with our circuit, but reading analog at 5v
    // so the value we check for is half of this max value: 1.8/5*255=92
    // I COULD have used arduino's Aref, but math is faster than soldering
    while(analogRead(senseY) < 46)
    delayMicroseconds(490);

    // now Y+ pin is in output mode
    analogWrite(touchY, y_potential);
    delayMicroseconds(180);

    // pull Y+ down again to keep interrupt going
    enable_touch_screen();
  }
  disable_touch_screen();
  analogWrite(touchX, 0);
  delay(50);
}

void disable_touch_screen() {
  analogWrite(touchY, 255);
}

// pull Y+ pin low to initialize 3DS's touch interrupt
void enable_touch_screen() {
  analogWrite(touchY, 0);
}

// the loop routine runs over and over again forever:
void loop() {

delay(800);
// tap at 150x150 for 100ms.
touch_screen_click(150, 150, 100);

delay(800);

// tap at 50x50 for 100ms.
touch_screen_click(50, 50, 100);
}

I'm trying to do the same thing with a Nintendo DSi, I'll be watching here :)

Why do you wish to monitor the Arduino's Output of Y+?

@Austin Burk  Which Arduino Board are you using?

I'm using an Arduino Uno.

I am monitoring the Y+ pin because the 3DS console sends the touchscreen interrupt on that pin, according to dekunukem's documentation: https://github.com/dekuNukem/3xtDS/blob/master/overview.pdf
From what I understand, he uses a bit of a hack to get this working by using only two of the four pins for the touchscreen. I believe the 3DS uses a standard 4-wire resistive touchscreen such as this: https://www.sparkfun.com/datasheets/LCD/HOW%20DOES%20IT%20WORK.pdf

I see no mistakes in the code. If you have teensy board, do what Igor Stoppa tells you to, if the fault is not due to the PWM frequency , then I shall have another look at the code.

Do you have an Oscilloscope? If you do, check the analog output that comes after the PWM to Analog converter. It could be an Electronics fault also.

How many free pins do you have on your Arduino board ? If you have 10 or more , and don't mind using 5BIT precision , I have a solution for any electronics fault.

@Mathsman100 I decided to get a teensy so I could rule out the PWM frequency being an issue. No luck, even using the original teensy schematics and code from dekunukem's GitHub page. Unfortunately I do not have an oscilloscope on hand, but I am considering getting one. I have 17 pins free on my arduino. 5bit precision would be a huge accuracy loss for the touchscreen I'm trying to simulate (which has a resolution of 320x240), but I don't mind trying 5bit if you have an idea to troubleshoot. I have already done some basic troubleshooting using a multimeter to verify voltage outputs.

Basically, the problem could be that the ADC is reading faulty readings as the PWM to Analog never works properly if using a fast Microprocessor.

Use this link for reference and comment here if you need any help, or after you try using an OP-AMP DAC(5to8-BIT, you could use 8BIT if possible, but I recommend 5 or 6) to tell the results.

Remember to use 1.8V as supply for OP-AMP and to convert the 5V to 1.8 volt before sending the signal to the Resistors before the input of the OpAmp.(Preferably use transistors for this, instead of Voltage dividers.)

Link for Buffer Image:Buffer

Please Note:I am only telling this for troubleshooting, this may not serve your purpose.

To confirm your analysis that the issue is caused by the lower pwm frequency on the Arduino, did you try reproducing the problem with the teensy? Just divide by 3 the PWM frequency on the Teensy and see if you get the same problems that you are experiencing with the Arduino.

Yes, I have recently purchased a teensy 3.1 specifically for troubleshooting this project and I unfortunately have the same result. This confuses me greatly, because I used the exact same electrical schematic and code listed in dekunukem's documentation that I was referring to. At this point, the only thing I haven't tried is using all 4 pins of the touchscreen rather than just the 2 pin exploit that dekunukem used: https://www.sparkfun.com/datasheets/LCD/HOW%20DOES%20IT%20WORK.pdf


text:
How to discard same string received at Arduino
I don't want the same string to be printed again and again. I'm getting the data into an Excel sheet.
byte readValue1=0;
byte readValue2=0;
int add=0;
int row=0;
int Zigbee1=0,Zigbee2=0,Zigbee3=0;
void setup() {
    Serial.begin(9600);
        Serial.println("CLEARDATA");
        Serial.println("LABEL,Time,Zigbee,a1,a2,a3,a4,a5,a6,a7");
        row++;
}

void loop(){
  String a1,a2,a3;
  String c1,c2,c3;
  int b;

  if (Serial.available()>21){
        if(Serial.read() == 0x7E) {
            for(int i=0; i<10; i++){
                byte discard = Serial.read();
            }
                        add = Serial.read();
                       if(add == 33)
                        {
                        a1 = func1();
                        if(a1==c1){
                          b=0;
                        }
                        else
                        {
                          b = a1.length();
                        }
                        if(b != 0)
                       {
                        Zigbee=1;
                        Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                        Serial.print(","); Serial.println(a1);
                        row++;
                        }
                        }
                      else if(add == 48)
                        {
                        a2 = func1();
                        b = a2.length();
                        if(b != 0)
                      {
                        Zigbee=2;
                        if(a2!=c2){
                       Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                       Serial.print(","); Serial.println(a2);
                        }
                        c2=a2;
                       row++;
                        }
                        }

                       else if(add == 69)
                        {
                          a3 = func1();
                          b = a3.length();
                          if(b != 0)
                         {
                          Zigbee=3;
                          Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                          Serial.print(","); Serial.println(a3);
                          row++;
                    }
                        }
}
}
}

Can you give sample of the output you are getting and the output you want?

i solved it out by using comparing the received bits in that frame..
here is my code..
                   if(add == 33)
                    {
                    a1 = func1();
                    b = a1.length();
                    if(b != 0)
                   {
                    Zigbee=1;
                    if(a1!=c1)
                    {
                    Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                    Serial.print(","); Serial.println(a1);
                    }
                    c1=a1;
                    row++;
                    }
                    }
                  else if(add == 48)
                    {
                    a2 = func1();
                    b = a2.length();
                    if(b != 0)
                  {
                    Zigbee=2;
                    if(a2!=c2){
                   Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                   Serial.print(","); Serial.println(a2);
                    }
                    c2=a2;
                   row++;
                    }
                    }

                   else if(add == 69)
                    {
                      a3 = func1();
                      b = a3.length();
                      if(b != 0)
                     {
                      Zigbee=3;
                      if(a3!=c3)
                     {
                      Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                      Serial.print(","); Serial.println(a3);
                     }
                     c3=a3;
                     row++;
                }
                    }

Only print the string when he has changed?
String previousString = "";
String newString = "";

if(newString != previousString){
   println(newString);
   previousString = newString;
}

I'm not sure if it's applicable in your situation, just the first thing that came to my mind. You (kinda) should make a function of it, so that you don't have to copy/paste it all the time and it'll look way better.
EDIT:
A fuction could be made like so:
String previousString = ""; //Put this above your setup code (global variables)

void NoSpamString(String input){ //Put this block before the setup
   if(input != previousString){
      println(input);
      previousString = input;
   }
}

You can then use: NoSpamString("text"); to print a line withouth spamming it.

Thanx.. i figured it out..

but i cant make a function coz i need to check the address of every zigbee .. and im not getting how to make a function.. im a newbie..

How did you solve it then? If you believe this answer is the right solution you can use the  ✓ on the left side of the answer.

No, actually i got the solution later on my own:p

You could consider posting the solution you made, as an answer. So that other people who visit this question can use it for their project


text:
Line Follow Vehicle
I know this is very common project and it's already been done, however, most of the guides don't have a clear instruction, and being this inexperienced, I struggle to understand exactly what's going on.
I'm currently working on a line following robot, but I'm largely inexperienced. For the most part, I'm going to be using SparkFun's Magician Chassis with Inventors Kit. The main sensor available is the Line Sensor Breakout(QRE113), which I have 3 of, but I'm not sure if whether I should use the Digital or Analog model.
Also, I'm having trouble finding how to wire this circuit. I know as much that, I have to connect the motors, diode, simple transistor(with emitter, collector, and base), some sort of resistors, and maybe a capacitor(this one I'm not too sure of). All of this has to be set on a breadboard, and be jointly connected to the arduino. I think there has to be two identical circuits on the breadboard for each motor, as the voltage of the sensor is expected to decrease when it encounters a white reflective surface(tape), this in turn will slow down the motor, which would allow the robot to turn in the direction of the tape, due to the other wheel not slowing down. One part of the circuit, should handle the motor drive circuit, this should be the output of the transistor, but I'm not sure how to use the arduino(redboard) to control the speeds of the motors using the sensors, which I think will go into the base of the emitter. Which pins should I use basically?
Apart from this, how will the code look? But I think this is dependent on how I wire it, right?
This is what I'm using...
https://www.sparkfun.com/products/12060
https://www.sparkfun.com/products/9453

You should, really, cut this complete project into smaller little projects.
Actually, first you should get clear what you want, there are a lot of possibilities.

Try to get one line sensor working
Try to get one motor working (check Pulse Width Modulation)
Try to get the two motors working and put them on the chassis.
Make the motors drive around a little, turn and reverse.
Get the three line sensors working (I think you're following a single line withouth crossroads etc.?)
Make your arduino check for changes in the pattern 0 1 0 respectively for the line sensors would mean that you're on the line. If the pattern is 0 0 1, you're driving off the line to the left.
Use the engines to adjust back onto the line.

I've actually done a project similiar to this one, but we used a motor-board instead. Driving the motors with a transistor&diode(&mosfet?) should indeed also be possible... but it'll get difficult once you want to be able to also reverse the motor (check H-Bridge motor driver).
For the patterns, you should make a switch case which checks the last pattern and keeps steering until he finds the right pattern again. But this can be achieved in many other ways.
Try to get a line sensor working, be sure to check some tutorials before you ask here and try to use different kinds of tape, blue tape didn't work for us :)
It's a really fun project, with lots of possibilities.

Below the schematics we used in the project.

We used a motor controller board.
Bluetooth module to receive command/routes from the server.
(LS) line sensors, 5 of them, to see crossroads/sideroads.
(Infrarood) IR sensors for collision detection.
(RS) I actually have no idea which sensors these are.
(Ultrasonic Sensor) Ping sensor to determine distance to other robots.

I can actually provide more reference material, but I would suggest you try it yourself (with the help of internet) and at the moment it starts to bother you, you should create a question specific for your problem. So as an example: You check some tutorials and FAQ on your line sensors, on how to get them working. After struggling for some time, you shouldn't drop the project but instead post a question with all details on this linesensor. So we can help you out to get that part working. Then you can happily move on towards the motors etc.

Thanks a lot guys.  I'll get back to you guys if I run into more problems.


text:
Difference between print() and println()
What is the difference between print( ) and println( )?
I see none when I run a code.

Really? Try a few of each in sequence and see if you see any difference.

Ya, now I see a difference

The answer to this question could have easily be found on the Arduino site.

The ln from println comes from line, meaning it will print a new line character at the end

print() prints whatever you send in.
println() does the same thing, only after using println, anything new that is printed gets printed in next line, I.e. a new line is formed.

Could you post your code please, as my answer is kind of incomplete now.

An easy way to see the difference is using Serial.print();/Serial.println();.
print();

will print out whatever you input wherever the cursor currently is. For example:
Serial.print("Test");
Serial.print("Words");

This will print:
TestWords_

The underscore marks where the cursor is (and therefore where the next print command will start). In contrast, the code:
Serial.println("Test");
Serial.println("Words");

will print the following:
Test
Words
_

You can also print multiple statements and then follow with println like so (note the space at the end/beginning of the strings):
Serial.print("These ");
Serial.print("Test");
Serial.println(" Words.");

to get the following output:
These Test Words.
_

You can also use println(); to add a newline character in general. If you would print a variable that doesn't return a newline character, println(); can be used for formatting. Example:
int x = 50;
Serial.print(x);
Serial.println();

This will print:
50
_

Finally, you can add in special characters like a tab \t inside your quotes for formatting. Example:
Serial.println("Test\tTest")

This will return:
Test    Test
_

Your answer tells us that println() function prints what's in the parenthesis then prints a newline character rather that printing a newline character first and then printing what's inside the parenthesis. Your idea of underscore for showing the cursor position is quite very nice. +1 for all that.

The print("aString") method prints just the string "aString", but does not move the cursor to a new line. Hence, subsequent printing instructions will print on the same line.
The println("aString") method prints the string "aString" and moves the cursor to a new line.
The println() method can also be used without parameters, to position the cursor on the next line.
Regards

print() print which you want but in one line.
For example,
Serial.print("Hello");

Then output in Serial Monitor look like,
HelloHelloHelloHelloHello

println() print same things but in new line.
For example,
Serial.println("Hello");

Then output in Serial Monitor look like,
Hello
Hello
Hello
Hello
Hello


text:
Alternative to Tone( )
Is there any way to make sounds using an Arduino without using the tone function?
It must be possible via this new method to control frequency of sound.

Do you want "sounds" or do you want "notes"?

I'm not sure, but does analogWrite(200); make a sound for you?

Why would you want to? Pretty much the only way, is to create a 50% duty cycle PWM at a certain frequency. And that is exactly what tone does. If you are interested in how it does that, you can look at the source code (https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Tone.cpp)

@Gerben reasons not to use tone: timer clash with other libraries; (apparently) increased code size; and potentially just to understand and explore the low level engineering

I've used a somewhat more complex method with some success, which uses 2 timers to play 8kHz sampled audio. The idea is that one of the timers runs at 8kHz to determine the PWM duty cycle of the other, which runs at as fast a frequency as possible.
While the original code uses a short stored sample (On an Arduino, you could store maybe 3 seconds of audio that way), my usages involved computing the audio on the fly by overlapping several sine waves or using table lookups with varying strides. As long as computation is kept simple, this just barely works.

You wrote that?  Thanks!!  That helped me so much a few months ago!

To clarify: I did not write the code on arduino.cc, but I used a modified version of it in some projects of my own.

Thanks a lot, but anyway, I got an answer myself.
I can use the simple delaymicroseconds( ) .
Also, I can use timer interrupts to do basically the same thing
And these are a lot less complicated than the other answers I got.


text:
Soldering issue with arduino
I am trying to solder arduino nano onto a perfboard/solderable breadboard using rosin core solder. The connection is only working some of the time, when I check with a multimeter (+) at pin 29 (in image below) I and (-) at pin 17 there is power at the top of the pin sticking out of the via/hole but there is 0 volts if I check at the actual joint (lower portion of the pin). I see a little flux residue around pin 29 that could indicate a little burning around the area could that be causing this, it is only very minor .. anyway I can fix it?

Also is it normal  to have a little yellow residue left over on the joints? I am new to soldering so not sure if a little flux reside is a bad thing on the joint...

If all you are going to do is solder wires to the perfboard, why not eliminate it and just solder to the Arduino Nano?

Fair play, that is a lot of flux residue. I am assuming you are using some quite chunky solder with lots of flux in it.
Flux is non-conductive, so the residue will be forming an insulating layer on the outside of the solder. That doesn't mean the joint is bad, only that you can't get to the joint because the flux residue is in the way.
If there is a conductive path between the tip of the pin and the pad next to it then all is fine. The fact that you can't see the signal through the outside layer of flux is neither here nor there.
If you want to clean it off you can use isopropyl alcohol (AKA PCB cleaner, AKA "rubbing alcohol") and use, for instance, a tooth brush to scrub it off.

Would a hotter iron burn off the excess flux, or otherwise dispel it better from the solder as it solidified?

Not really, no. That will just bake it on more and risk lifting the annulae of your holes.

Fair point. I have used 'rework solder' before which is bursting with flux and has a lower melting point, designed to flow as much as possible to help lift awkward components. That required lowering the tip temperature otherwise the flux would disappear too quick. It makes sense that it's more likely to bake on than bake off.

“The connection is only working some of the time” does seem to indicate bad solder connections.  (Another possibility is wires in wrong holes.)
To locate problems, clip (rather than hold) one lead of an ohmmeter (or a DVM set to Ohms), to a wire soldered to the beginning of the problematic chain of connections.  Then advance step by step along the chain, looking for an open junction.
To fix problems, obtain a solder sucker and/or solder wick, a hot fine-point soldering iron (preferably temperature controlled), and thin (eg 1-2mm) 60-40 tin-lead rosin-core solder.  Use the solder wick or solder sucker to remove the old solder from the joint.  Apply new solder to make a nice shiny proper solder joint.

Unless you're in the civilised parts of the world where you're not allowed to use lead... I use 0.7mm 97.1, 2.6, 0.3 Sn, Ag, Cu


text:
Fading RGB LED between 10 and 60 cm
What I want to achieve is that between 10 and 60 cm of my HCSR04 sensor the color fades from red to blue on my RGB LED in steps of 1 cm between 10 and 60 cm.
I have tried creating some own functions which calculate how much the analogWrite has to change every cm. Yet have had no succes..
I want to implement this function in the following code:

I hope my question is understandable...

Try using the Arduino map() function...

You should include the code as text rather than an image.
Also, I assume that the ranging works (and prints the distance), is that true?

@paul Indeed, the code above works as it should, I just have to implement the function I described.

analogWrite(Kleur1,distance);
analogWrite(Kleur2,1024-distance);

Theoretically, this is all you need.
You'll color the LED "kleur1" with the analog value of the distance, so it will become brighter when the distance is higher.
And you'll color the LED "kleur2" with the "inverted" analog value of the distance, so it will become less brighter when the distance is higher.
But this kind of depends on what the value is on your maximal distance etc.

Thanks for the answer! I am going to try this out somewhere this week!


text:
How do I repeat a piece of code
For a school assignment I need to make a LED blink on/of 3 times then stop.
Now I have come up with the following code:

I think it's ''clean'' enough for what it has to do, but I have a feeling that here must be a easier way to make the LED blink 3 times.
Question is: Is there a way to reapeat the part of code 3 times without copy&pasting it?

Other than with a loop?

Google "for loop C++".

@IgnacioVazquez-Abrams The thing is that it has to stop after 'blinking' 3 times. And there is no way to stop the loop, correct me if i'm wrong.

And? There are loops that can do that. Or have you not looked at any C++ tutorials yet?

@IgnacioVazquez-Abrams Only thing I found so far is a Exit(0); which makes the program stop. But then I still have to copy paste the code 3x becuase the loop otherwise stops after 1 on 1 off loop.

Thank you for his code.. just some follow-up.
If i want to stop the flashing when button press, what code need to add.
ex: LED flashing for 30s then when i press the button it will stop. thanks

Here you can use a loop. a classic for loop in C++ looks like this
for (int i = 0; i < n; i++)
{
    // content in between these brackets
}

where n is the amount of times you want to loop
you can also instantiate the i before the loop.
int i;
for (i = 0; i < n; i++)
{
    //content here
}

The code below should work. Toy around with it and see what you get.
int ledPin = 13;
int delayPeriod = 500;

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

    for (int i = 0; i < 3; i++){
        digitalWrite(ledPin, HIGH);
        delay(delayPeriod);
        digitalWrite(ledPin, LOW);
        delay(delayPeriod);
    }

another approach you can do is using a while loop. These kinds of loops will loop until a given parameter has been met. In your case you want an LED to stop blinking after 3 times.
int start = 0;
int stop = 3;

while (start <= stop){
    //content here
}

While loops will continue to go as long as the parameter is true. This means something like while(1) will continue to run forever.

Thanks! I tried the Int i; function and it works perfectly!

@tisaconundrum have you missed an increment or decrement in your while loop?

How can I change to code to work with if and else statements, so it wil work in the loop.

Another way is to declare a function. This method will give you more chance of using it in various ways.
    int LED_PIN = 13;

    void flashing(size_t times=1) { // By default it will flash once, you can chance this into your desire
        int delayPeriod = 500;
        for (size_t loop = 0; loop < (times*2); ++loop) {
          digitalWrite(LED_PIN, (loop % 2)?HIGH:LOW);// Use Modulus
          delay(delayPeriod);
        } // Thanks to [Matt][1] and [Edgar Bonet][2] for their comments
    }

    void setup() {
        pinMode(ledPin, OUTPUT);
        flashing(3);
    }

    void loop() {
        // Do something here
    }

I also came up with the idea of using a function, but you have to consider the overhead of calling it,  In this case I don't think its worth the cost.  Normal coding standards frown upon placing two statements on a single line.  Off the top of my head I couldn't say if a while or for was more efficient, but personally for a fixed number of iterations I would go for a for loop, if I had to do a while loop then I would set I to zero so I could do (i<times) which would be quicker than what you have.  All that said, its still a good answer.

A for loop is definitely better in terms of legibility.

You could also look at optimising the 4 lines of code inside you loop:
const int ledPin = 13;
const int delayPeriod = 500;
const size_t count = 3;

void setup()
{
    pinMode(ledPin, OUTPUT);
    for (size_t loop = 0; loop < (count*2); ++loop) // size_t because variable is never negative.
    {  // Two time count, because you only have half the code
        digitalWrite(ledPin, (loop % 2)?HIGH:LOW);// Use Modulus
        delay(delayPeriod);
    }
}

Sorry for the late respons! Thanks you for helping out, I will try this methode later tonight! I already made my code work with the previouse answer. This methode may be easier to read for others. Def going to take a look at it. Thanks again, Really appreciate the time and effort you took for responding!


text:
Connecting an optris to an arduino uno to send and receive hex strings
I have an optris CT IR sensor, data sheet below.
Is it possible to connect the Uno to the sensor, so I can send a hex string (01) and hopefully receive a hex string from the sensor (04 D3)?
https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0ahUKEwirjO3oxo7PAhVKDsAKHcjGAcMQFggvMAE&url=http%3A%2F%2Fwww.optris.com%2Foptris-ct-lt%3Ffile%3Dtl_files%2Fpdf%2FDownloads%2FCompact%2520Series%2FData%2520Sheet%2520optris%2520CT%2520LT.pdf&usg=AFQjCNEb-UKhxvfBE7k7k8zOgEZE9TOJbg&cad=rja
Commands below: (Go to examples section for 01, 04 D3)
https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwiM6_zAx47PAhXoIcAKHVdUCo8QFggoMAI&url=http%3A%2F%2Fwww.optris.co.uk%2Finterfaces%3Ffile%3Dtl_files%2Fdownloads%2FManuals%2Faddendums-de-en%2Fct-ctlaser-commands.pdf&usg=AFQjCNEkEtwUoiM6jsJYOnGD4-8Yo2Cprg&bvm=bv.132653024,d.ZGg
Thanks

Yes, there are interface options that are compatible with the Arduino. You just have to ensure that you choose the right model so you have the right interface available. Options include RS-232 (with a MAX232 adapter), RS-485 (with a suitable RS-485 shield), CAN (with a suitable CAN shield), Ethernet (with a suitable Ehernet shield) and maybe even the USB version (with the USB Host shield), though the latter is less likely to work.
Pick one that suits your needs best.