text:
Arduino IDE programming help
I am trying to write a program to control a stepper, and incorporate a selector switch and a rheostat.
The object is to make the stepper oscillate, and to be able to control the speed with the rheostat, and the amount of oscillation with the selector switch.
What would the best way to go about this?

By writing a program to do it.

So you want to use the rheostat as an analog controller then?-If so your program would use the analog pins. Uisng the info gathred from the analog pins you can control the stepper motor, though you may need to build a h bridge or use something similar

A stepper motor may well not be the right choice

"The object is to make the stepper oscillate" if you mean you want to make the stepper go back a fixed number of degrees in one direction then go foward a fixed number of degrees in the opposite direction-then yes a stepper with control circuit can do this. My interpretation of your question is your are using select switch to vary degrees in an oscillation and rheostat as analog controller for speed of oscillation. Right?

Majenko provided the correct answer in his comment: you just have to
write a program to do it! This site is not meant to provide you with a
ready made solution, but to give help if you run into an issue while
trying to solve the problem yourself.
That being said, before you attempt to write the program, you should
learn how to interface with the hardware you are using. Here are the
relevant Arduino tutorials:

The Button tutorial is about reading a push button, but you would
do exactly the same to read a switch
Reading a Potentiometer (analog input)
Stepper Speed Control will teach you how to control your
stepper motor

And then there is plenty of material available on the Web for each of
these topics.
Go through the tutorials, understand the programs given as examples,
make them work with your hardware, then put the pieces together to solve
your problem. If you run into an issue you cannot solve buy yourself,
then come back here with a specific question and show us what you have
attempted so far, including code and schematic. See also How do I ask
a good question?.

Here are the code fragments that would help you.
Connect the three wires from the potentiometer to your board. The first goes from one of the outer pins of the potentiometerto ground. The second goes from the other outer pin of the potentiometer to 5 volts. The third goes from the middle pin of the potentiometer to the analog pin A0.
Here is the connection schematic:

Here is the code to read the analog value from port A0:
int sensorValue = analogRead(A0);

this would assign a value ranging fro 0-1023 to sensorValue according to the position of the Pot.
int stepsPerRevolution = 200;
//this variable holds the no of steps the motor rotates to complete a full circle rotation.

int stepCount = 0;  // number of steps the motor has taken

stepsPerRevolution = map(sensorReading, 0, 1023, 0, 200);

// step 1/100 of a revolution:
myStepper.step(stepsPerRevolution / 100);

Here is an example program for controlling the direction of stepper using microswitches:
#define stepPin 2
#define dirPin 3
#define pinLimitswitchLeft 4  // these can be either left or right depending on motor wiring and dir pin.
#define pinLimitswitchRight 5 // these switches must be N.O. types
int stepDelay = 100; // this is the step delay in microseconds. Reduce this to speed up motor rotation and vice versa.

void setup()
{
    pinMode (stepPin, OUTPUT);
    pinMode (dirPin, OUTPUT);
    pinMode (pinLimitswitchLeft, INPUT_PULLUP);
    pinMode (pinLimitswitchRight, INPUT_PULLUP);
}

void loop()
{
    digitalWrite(dirPin, HIGH);  // set direction pin, the direction that the motor will rotate is dictated by it's wiring
    while (digitalRead(pinLimitswitchLeft) == HIGH) // move motor until left limit switch is pressed.
    {
        stepMotor();
    }

    digitalWrite(dirPin, LOW);  // set direction pin, the direction that the motor will rotate is dictated by it's wiring
    while (digitalRead(pinLimitswitchRight) == HIGH) // move motor until right limit switch is pressed.
    {
        stepMotor();
    }

}

void stepMotor()
{
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(stepDelay);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(stepDelay);
}

Change the control from the control switch to the number of steps taken by your motor when the switch is pressed and it will work as you require.
I have not included the header files.
Please edit the program as you require


text:
Calculate the time since arduino started working for a year
I want Calculate the time since arduino started working for a period of one year using arduino uno and when the period is over flip a light on

I'd use an RTC, as you only need one power outage for the system to fail (without an RTC).

Simplest solution would be to use millis(), but you will need to
somehow take care of the periodic rollover. Creating a lower frequency
software timer, as explained by Jot, is one solution. Another option is
to extend millis() to 64 bits:
uint64_t millis64()
{
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

You must call this function at least once every 49.7 days, otherwise it
will loose time. I would just call it on every loop iteration, like
this:
const uint64_t ONE_YEAR = 365.25 * 86.4e6;  // Julian year

void loop()
{
    if (millis64() >= ONE_YEAR) {
        // do some stuff...
    }
}

Besides the issue of a possible power failure, there is another caveat:
the Arduino Uno is clocked off a ceramic resonator. These are not very
accurate, and are typically specified to be within 0.5% of their nominal
frequency. This means that your “year” can be off by as much as
1.8 days. RTCs are clocked off a quartz crystal and are then far
more accurate. Ultimate accuracy could be achieved with a GPS receiver.

I would use a network card to talk to an NTP server. In setup(), fetch the time and save it to EEPROM if there's not one already saved. You can then ping the NTP server every day or every boot, comparing the saved date and responding as appropriate. This strategy avoids MCU timer slew, power-out milis() resets, and extra hardware (other than networking, which more and more projects have already anyway).

The function millis counts up to about 50 days. However, you can make a software timer with millis of, for example, 1Hz. With a unsigned long that counts the seconds, it is easy to count a year.
It will not be reliable. When the power is off, it starts again. A RTC (Real Time Clock) with its own battery is better.
Are you a good software engineer ? How can you be sure that it will work ?

source: Stack Exchange

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

sort: votes


text:
How to correctly read a string from Arduino serial port?
I'm trying to communicate with my Arduiono UNO via USB serial port, more precisely I'm trying to read a string like 125,0, I know it's full of article out there about this, but belive me I've tryied more or less everything, now I got a NODEJS server on a Raspberry Pi that looks like:
var express = require('express');
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);

var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyACM1", { baudrate: 115200 });

server.listen(8080);
app.use(express.static('public'));

var brightness1 = 0;
var brightness2 = 0;
var string;

io.sockets.on('connection', function (socket) {
    socket.on('led', function (data) {
        brightness1 = data.value1;
        brightness2 = data.value2;
        string = brightness1 +","+brightness2;
        var buf = new Buffer(1);
        buf.write(string);
        serialPort.write(buf);
        console.log(buf);
        console.log(string);
        io.sockets.emit('led', {value1: brightness1, value2: brightness2});

    });

So based on that, I'm sending a string over the serial and the console log showed above gives me that:
<Buffer 32>    //console.log(buf);
23,0           //console.log(string);

Wich I think it should be ok because I'm sending what I need a 32 and a 0, also if i don't know what it means the
Arduino side I used the sketch provided here and retouch it a bit based on my needs:
void setup()
{
  Serial.begin(115200);
}
void loop()
{
  while(!Serial.available());   //wait until a byte was received
      Serial.println(Serial.read());
      int a = Serial.parseInt();
      int b = Serial.parseInt();
      Serial.println(a);
      Serial.println(b);
      //analogWrite(3, a);
}

but the result of my Serial.print() are really incongruents, something like:
5--2224, which is totally nosense, my question so is WHY? Where I'm getting wrong? I read a lot around, am I missing something?

You sized your buffer with room for one single byte: it only gets the '2' of "23,0". The ASCII code for '2' is 0x32 (in hex). That's the meaning of <Buffer 32>.

@Edgar thanks for your reply! So basically my problem is on server side, so I just need to increase the buffer size to 7? Arduino side is all good right?

There is a problem server side, but then I am not sure how well the Arduino side would perform, especially if you don't control the timing of the sent bytes.

This is a common (and my favorite) approach:

Choose an “end of message” character. CR or LF can be good choices,
especially if you want to test your program with a terminal emulator.
On the Arduino, buffer all the received bytes until you see the end of
message.
When you see the end of message, handle the buffer to a function that
will parse and process it.

I would avoid parseInt() for anything but the simplest tests, because
it is both blocking and sensitive to the timing of the input.
For an example, you can take a look at this
Simple Arduino command line
interpreter
(look at loop()). It's non blocking, so you can add background
processing to perform while waiting for input characters.

I fully agree here with edgar Bonet.
I only want to add a link to a library I have written that does a line by line (based on end message CR and/or LF)
SerialStringReader
This library contains examples.
Note that for many reasons the library uses null terminated strinsg (also known as char arrays) and not the Arduino String class

How to correctly read a string from Arduino serial port?

You can use the function Serial.readString(). It will return a string that you typed from the serial monitor.

No, really. This way you will only get what is in the buffer now. If you read faster than the other end writes you will get just a piece

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

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


text:
Why I can't exit this while loop by reading from the Serial?
I'm trying to work with the FastLed libraries and i'm controlling a Led Stip via a WEMOS D1 MINI based on the ESP8266, what I'm trying to achieve is to jump from fastled animation to another one..those animations are inside a While loop as shown in the code, so , i thought to just read again from the serial in order to change an integer to exit those while loop, but for some reason is not working as expected. Anyone can help me to uderstand?
CRGB leds[NUM_LEDS];
int incomingByte = 0;
int exit = 0;
void setup() {
    Serial.begin(115200);
    delay( 1000 );
    FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
    FastLED.setBrightness(  BRIGHTNESS );
}

void loop()
{
    while (Serial.available()>0)
    {
      Serial.write("Serial.available");
       incomingByte = Serial.read();

       switch (incomingByte)
        {
          case '1':
            GreenYellow();
            break;

          case '2':
            Sparkle();
            break;
        }
    }
}

void Sparkle() {
    while(exit = 0){
        int Pixel = random(NUM_LEDS);
        setPixel(Pixel,random(255),random(255),random(255));
        FastLED.show();
        delay(50);
        setPixel(Pixel,0,0,0);
        if(Serial.available()>0){
            incomingByte = Serial.read();
            if(incomingByte != '2'){
                exit = 1;
            }
        }
    }
  }
}
void GreenYellow()
{
  for(int x =0; x< NUM_LEDS/2; x++){
    leds[x]= CRGB::Green;
  }

  for(int x =NUM_LEDS/2; x< NUM_LEDS; x++){
    leds[x]= CRGB::Yellow;
  }
  FastLED.show();
}

void setPixel(int Pixel, byte red, byte green, byte blue)
{
   leds[Pixel].r = red;
   leds[Pixel].g = green;
   leds[Pixel].b = blue;
   FastLED.show();
}
void setAll(byte red, byte green, byte blue) {
  for(int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  FastLED.show();
}

Bonus question: I read that there is no thread programming on the ESP2866 via the Arduino IDE, am I right?

The problem is that you check inside the two functions Sparkle and GreenYellow for another serial byte. Then when it's unequal, you move back to the while loop where you wait for the next serial byte, but I think you need to use the same one to decide to go to the correct function instead of waiting for a next serial byte.
Probably the easiest is to not read serial in the while loop but check the incomingByte global variable  (containing the last read byte, and e.g. 1 initially), and ONLY in the two functions set that global variable. Then, when returning to the while loop, you check that global variable to jump to the correct function.
So you make a setup function that sets the global variable to 1 (or you do it in the initialization itself):
int incomingByte = 1; // Start with GreenYellow

Then, in the loop function, you use:
void loop()
{
       switch (incomingByte)
        {
          case '1':
            GreenYellow();
            break;

          case '2':
            Sparkle();
            break;
        }
}

If you don't want to start in either one, then use 3 values (0, 1, 2), and ONLY in the loop function read the Serial byte, but don't read it in the functions.
This way it's a bit more cleaner as it separates the LED functionality with the Serial functionality.
The result (using the last method), results in the following code (compiles, not checked).
Comments:

Used an enumeration for the mode

Split functionality of serial data, processing the mode and RGB routines

I added some initialization lines (i.e. constants) to make it compile.
#include <FastLED.h>

#define NUM_LEDS 60 // number of led present in your strip
#define LED_PIN 6
#define BRIGHTNESS 100

enum EMode
{
  ModeNone,
  ModeSparkle,
  ModeGreenYellow
};

CRGB leds[NUM_LEDS];
EMode mode;

void ParseSerialData();
void ProcessMode();
void GreenYellow();
void Sparkle();
void setPixel(int Pixel, byte red, byte green, byte blue);

void setup()
{
    Serial.begin(115200);
    delay( 1000 );
    FastLED.addLeds<WS2811, LED_PIN, EOrder::RGB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
    FastLED.setBrightness(  BRIGHTNESS );
    mode = EMode::ModeNone;
}

void loop()
{
  ParseSerialData();
  ProcessMode();
}

void ParseSerialData()
{
  while (Serial.available() > 0)
  {
    Serial.write("Serial.available");
    char incomingByte = Serial.read();

    switch (incomingByte)
    {
    case '1':
      mode = EMode::ModeGreenYellow;
      break;

    case '2':
      mode = EMode::ModeSparkle;
      break;

    default:
      // Ignore
      break;
    }
  }
}

void ProcessMode()
{
  switch (mode)
  {
  case EMode::ModeNone:
    // Do nothing
    break;

  case EMode::ModeGreenYellow:
    GreenYellow();
    break;

  case EMode::ModeSparkle:
    Sparkle();
    break;

  default:
    // Ignore
    break;
  }
}

void Sparkle()
{
    int Pixel = random(NUM_LEDS);
    setPixel(Pixel,random(255),random(255),random(255));
    FastLED.show();
    delay(50);
    setPixel(Pixel,0,0,0);
}

void GreenYellow()
{
  for(int x =0; x< NUM_LEDS/2; x++)
  {
    leds[x]= CRGB::Green;
  }

  for(int x =NUM_LEDS/2; x< NUM_LEDS; x++)
  {
    leds[x]= CRGB::Yellow;
  }
  FastLED.show();
}

void setPixel(int Pixel, byte red, byte green, byte blue)
{
   leds[Pixel].r = red;
   leds[Pixel].g = green;
   leds[Pixel].b = blue;
   FastLED.show();
}

void setAll(byte red, byte green, byte blue)
{
  for(int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  FastLED.show();
}

thanks for the replay, can you modify my piece of code? I'm have difficulties to understand your solution, so maybe reading the code will help. Thanks.

I'd go the other way. Leave all the serial reads inside the loop function. Remove the while loop inside the Sparkle function. Store the current mode that was selected in a variable. Then, in loop, call the function based on the current mode.

@Gerben Me too, but the first was the most 'easiest', not the most clean solution.

I tried to modify the code (it compiles)... I removed the exit code and tried to clean up things.

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


text:
Is Fastled.io library suitable for SMD50500 led strip?
I was looking for a ready to use library to control my SMD5050 color led strip, and I stumbled across FASTLED.IO library , but after reading trough their website I didn't find anywhere the support for SMD5050 color LED strip. Does anyone knows another "ready to use" animation library? Are FASTLED.IO suitable anyway?
Thanks

SMD5050 is just a shape of LED. It's a surface mount 5mm x 5mm package. What actual LED strip do you have?

@Majenko actually I forgot..I bought it one year ago...I looked on the strip but there's nothing writed on it...how can I understand it?

Do you have 4 connections at the end: +12V/R/G/B ? Or do you have 3 connections:  +5V/DAT/GND?

@Majenko yep...four connections

Then you can't animate it. You can just set the colour of the strip.

You'd wire it somewhat like this: https://arduino.stackexchange.com/questions/3535/rgb-led-strips-with-arduino

@Majenko I know they are not addressable but I thought to use FASTLED to make just simple color fade animation.. pulsing..buoncing..easing functions and so on..

FastLED is for addressable LEDs.

@Majenko They are wired in the way you showed me

You don't need a library to set the colours - just set the PWM outputs to the levels you want. It's up to you to "animate" it by changing those values.

@Majenko I was thinking there were other library with already made function like those http://easings.net/it

Not that I have ever come across. Arduino LED animation libraries are aimed at animating large numbers of individual LEDs.

No. FastLED is for addressable LEDs (like the WS2812B). Yours aren't addressable. You just need to set the colour you want with the PWM outputs of your Arduino. Changing the PWM values is not hard and you don't need a library to do it for you.

you are right...changing PWM value is not hardthe hard..will be achieving some of this fade functions http://easings.net/it

I am sure you are up to the task of writing the ones you want. If you have a mathematical formula you can easily calculate the colour to use at any one point in time. Otherwise simple CLUTs would be easy to implement.


text:
How do I turn off a 12V 3A RGB LED strip?
I'm trying to understand how to control an RGB LED strip, I set up all the TIP120 (because I could get my hands on an n-channel mosfet), if I power everything in this way I can change colours and everything:

but now I'm facing a dilemma now, whats the correct way to manage to switch my power strip ON/OFF based on an input from a pir sensor? I mean, how can I handle 12V 3A (requested by my led strip), how do I correctly wire my Arduino up in order to make it switch the LED strip ON/OFF?

That's pretty simple: when you turn off all the colours you are actually turning off the entire strip with very minimum leakage current in each of the three FETs.

Oh...really? Is that so simple? Do I need to use some king of Voltage regulator? Is it safe for my Arduino to receive a 12V in(yes) at 3A(I don't know)? The schema provided so will be ok? I don't even need to put 12V into my Arduino..right?

@FabioEnne With the schematic you have provided the 12V doesn't go anywhere near the Arduino.

@Majenko I know...I was just wondering if with this schematic will I be able to switch the LED strip off

@FabioEnne The FETs (or TIP-120s if you must) are just switches. Just like a light switch. Only for dimming you switch the light switch on and off really really fast.

@Majenko so you mean that I just need to give to the Red, Blue and Green pin a zero value or just set them to LOW?

That is correct. 0 is off. All three channels at 0 the entire strip is off.

@Majenko so in this way I should need any sort of voltage regulator right?

@FabioEnne You only need a voltage regulator when you want to change a voltage from a higher one to a lower one for the purposes of powering a device.


text:
Problem using IRremote library
I am using arduino pro micro 5v 16Mhz. I have built a simple IR transmitter circuit as shown.
The code i am using is
https://github.com/z3t0/Arduino-IRremote/blob/master/examples/IRsendDemo/IRsendDemo.ino
Although this worked yesterday, it doesn't seem to work now. I was able to turn on and off my TV yesterday but the led is not even blinking now. I checked led, its working.
After hours of trying to make it work I tried different library.
https://github.com/cyborg5/IRLib2/blob/master/IRLib2/examples/send/send.ino
Surprisingly this seems to work but the code is a bit complicated for receiver.
I want to use the first library. Any help is appreciated. Thank you.

I'm not sure what help anyone can give you here. You had it working, presumably changed nothing, and now it doesn't -- how can we debug that?

It seems the library got the timer pins wrong I changed them and its working now.

How did it ever work?

I used nrf24l01 module in between and maybe it changed timer settings.

The problem was with timer timer settings in library. I checked different timer configurations with different pins and its working now. I found out that timer4 uses pin 13 which is not used in Pro Micro board so I am now using timer 3.


text:
Pressing reset button restarts program only seconds latter
I am wondering why after pressing the reset button on my Arduino, the latest program loaded runs but only after about 5seconds. The same thing happen when I run my arduino from the computer using the Arduino 1.6.9 software.
Is there any way to make this delay shorter?
Thanks,
IF

(1) Might “about 5 seconds” be only a second or two?  That is, did you measure the delay with a timepiece, or just estimate it offhand? (2) If this occurs with only one sketch, please edit your question to include a Minimal, Complete, and Verifiable copy of the sketch, so we can identify the programming error that is causing the problem. (3) If it happens with several different unrelated sketches,  please edit your question to include a list of them.

A few seconds sounds like normal and I don't think you can reduce the time.  If you explain why you want it to be quicker it might be possible for someone to suggest a much quicker alterative.

The bootloader has to run for a few seconds before your sketch does. If you don't want that then delete the bootloader and use a hardware programmer.

The first thing that happens when you apply power to a board or press reset, is the bootloader executes. That waits for a short time to accept a new sketch over the serial port. If nothing arrives it terminates and executes the existing sketch.
On the Uno that delay is only 2 seconds. However on the Leonardo the delay is much longer (around 5-8 seconds) owing to how the serial port is implemented: it has to allow time for the host computer to re-enumerate the USB device after a reset, and that takes a second or two.
If you don't want that delay you will need to remove the bootloader (i.e., ignore it) and program the board through a hardware programmer and the ICSP pins (which will disable the bootloader for you). You lose the convenience of programming through the USB connection though.
Alternatively choose a different board that doesn't have such a delay for the bootloader - one that uses a different programming method.

Having had the same issue , I recently found out that the Leonardo/Micro jumps directly into the user application when it is powered up, either by inserting a USB cable connected to a cellphone charger i.e power only USB , or by connecting external power via the RAW power input.  So, if you need a quick restart after reset, just cut and reconnect the power supply.


text:
ATtiny85 soft-latching, and sensor-waking: Are multiple switches differentiable by pin change interrupt?
I am using a vibration switch with a pin change interrupt on an ATTiny85 to wake the processor and run some code when the vibration switch grounds an input pin. The circuit is battery-powered, so sleep mode is important. I would now like to add another input switch (momentary pushbutton) between an internal pullup on the ATtiny and ground to use as a soft latching switch to accomplish on/mode/off (power-on/case-selection/power-off). I'd like the vibration-wake-sleep code to be one of the cases selectable by the pushbutton. The ATtiny85 has one hardware interrupt (pin2 aka INT0), and the rest are pin change interrupts available on the other I/O pins.
After reading around, my understanding is that the pin change interrupts cannot be separated to run pin-specific code, as they all trigger the same pin change interrupt effect. Is that correct?
To put it another way, do I need to put my pushbutton on the hardware interrupt pin, or can I put it on any old I/O pin and still be able to use the vibration switch on another I/O pin only when I select that mode, without it triggering the same effect as the pushbutton every time there's a vibration? Or is there a better way? I'm trying to minimize the number of components, as this is a space-constrained project. Thanks!

What does the vibration signal look like? Is it a one-shot pulse? If so, what is the minimum width?

The vibe switch physically consists of a helical coil of thin, springy wire that bounces against another piece of wire. So presumably its signal is a big bouncy mess that varies with the force and frequency of the vibration impact.

If you have one dedicated interrupt signal, and enable the shared pin change interupt for only one pin, then you have no ambiguity - the hardware ISR is caused by the dedicated pin, and the shared pin change ISR is caused by the only enabled pin change pin.
Where things get more complicated is if you enable more than one pin to trigger the pin-change interrupt.  In this case, either the ISR or whatever follows in cause from it will need to figure out which pin caused the interrupt.
Unless I'm overlooking it in the data sheet, the ATtiny pin change interrupts don't have a register which latches the causing condition, so you may have to look at the actual pin input register.   The catch is that things like contact bounce might make the causing signal no longer present at the exact instant you check it.  However, contact bounce is typically a more serious problem when releasing a contact than closing it.
Some things you can do:

In the ISR, don't actually do anything, but set an "interrupt happened" flag.  Then in the main program, poll the inputs for a while until you see one actually asserted, and act on that.  You should only need to stay awake for a small fraction of a second before you catch the responsible contacts closed when you are looking.
You could try to use a small capacitor to slow the rate at which the pullup resistor responds to the switch bouncing back open, in the hopes of  making sure that the causing condition is seen when the ISR itself looks.

In either case you will probably want to stay awake and keep the pin change interrupt disabled until the switch has been released, and for maybe a hundred milliseconds thereafter to let release bounces die out.  Then you can re-enable the interrupt and go back to sleep.
Do keep in mind that regardless if the MCU is awake or not, if someone wedges the product into packing material or something which holds the switch closed in opposition to the pullup resistor, then that pullup resistor itself may drain your battery over a few weeks/months.

Ah. Thanks. So I'm reading that as 'yes, use the hardware interrupt for your pooshbutton'

and b) barring that, here are some very interesting techniques that are tantalizingly just beyond your newb level which you will now probably spend countless hours nerding out on. I guess for now I will try to restrict myself to mucking up my beautiful PCB layout to put the button on a different pin. Much appreciated. And good point about the risk of errant button pushing.

Or is there a better way?

Read the data sheet to see if it has individual flags for those pins.
Short of that, read and keep track of the pin states in the use to see which pins may have changed.

Read the manual, you are right.


text:
Referencing Serial output
I'm confused with what I'm reading.
I have Serial communicating with my PC (USB) and SoftwareSerial over RS485 to a remote PC. I don't want to duplicate all of my print statements to be able to send output to either (or both) terminals. What I want to do is have a single set of print statements (think of a list of error messages) and then be able to output a message to either Serial or SSerial depending on which needs it. Does this make sense?

Almost all of those things you do which involve functions like print, println, and write all derive from the Print class.  You could have an array of Print objects and print to whichever you like.
Print* outs[] = {&Serial, &Serial1, &mySoftSerial};

//  Later somewhere in code:

outs[0]->println("This prints to Serial");
outs[1]->println("This prints to Serial1");
outs[2]->println("This prints to mySoftSerial");

for(int i = 0; i < 3; i++){
  outs[i]->println("This prints to all 3.  You could even make this bit a function");
}


text:
NodeMCU NeoPixel
I am attempting to control a single NeoPixel with a NodeMCU, but I'm not having any luck.  Even just loading the default Adafruit NeoPixel library sketch yields unsuccessful results.  I've tested the exact same sketch on a regular Arduino with sucess.  I've got the data line hooked up to D5 on the NodeMCU board and here is my configuration of the Pixel in the sketch.
Adafruit_NeoPixel strip = Adafruit_NeoPixel(1, D5, NEO_GRB + NEO_KHZ800);

Any suggestions??

I had the same problem. It were resolved by initializing the pin as OUTPUT:
  pinMode(PIN, OUTPUT);
  pixels.begin(); // This initializes the NeoPixel library.

As I understand Arduino bootloader does it by itself but bootloader of ESP8266 does not.

The  node mcu is an esp8xxx with 3.3V outputs.
The neopixel is an ws2812 led controller that normally uses 5V logic.
They cannot communicate. This is why it's failing.
Lower the voltage used for the neopixel so that 3.3V is within 70% of the neopixel VIN or use a logic level translator.

Schematic please.

http://imgur.com/a/QTG1a

I had the same issue on a LoLin NodeMCU board while it worked with the Amica NodeMCU board.
When powered via USB, the Amica board provided 5V on the Vin pin, but the LoLin board didn't. I had to use the VU pin instead and it worked.
I did not need a logic shifter. I used the D2 pin with a 220 Ohm resistor for the data.


text:
Arduino Ethernet Shield 2: How can I automatically determine the MAC Address?
I'm using an Arduino Mega.
I know that Ethernet Shield 2's come with a sticker with the MAC Address printed on it. This would imply to me that this address is hardcoded into the shield. Is there any way to recover the MAC without manually entering it in the sketch?
Thanks!

No, the W5500 chip does not have a mac address. You can give it any mac address that you want. The router might not like some mac addresses though.
There are online mac address generators.
The sticker with the mac address is an extra service. It is unique number. But it is just a number on a sticker, it is not related to that specific shield.
Often the mac address DEADBEEFFEED was used. But when two different Arduino boards use the same mac address, the router thinks it is the same device. When there are two devices with the same mac address at the same time connected, that is for sure a way to mess up the router.

It would have been so simple to include a little I2C, SPI or 1-Wire EEPROM on there with the MAC address programmed in at the factory.  The price difference would have been negligible.  Such a shame they never bothered...

Thanks for the info. I was afraid of that. Basically, this prototype will eventually go into large-scale production (Using a proprietary board developed from the Arduino code/circuitry, etc. I end up with) so using a randomly-generated mac seems like a bad way to go. Ah well, I'm sure there's an alternative to the Ethernet shield.

This is an old question, but I wanted to share my code which fixes this.
Basically, the next code generates a "locally managed address" and stores it to EEPROM.
On subsequent starts, it read the address from EEPROM so that you would generally get the same IP address from the DHCP server.
If you do not have EEPROM, you may have another memory that survives programming cycles (SPI Flash, RTC RAM, etc) - you'll need to update the sketch for that.
#include <EEPROM.h>

// If defined, report information about MAC ADDRESS INITIALISATION
#define ENABLE_MAC_INIT_MESSAGES

// Local mac address, initialiser can be removed (when using initMacAddress)
uint8_t mac[6] = {0x00,0x01,0x02,0x03,0x04,0x05};

void initMacAddress() {
  // Rather than having a fixed MAC address for an Arduino sketch,
  // this implements a different, random address which is persistant
  // by storing it to EEPROM (which only works when EEPROM is available).

  // Here the MAC ADDRESS IS LOCATED AT ADDRESS 0 OF THE EEPROM
  for(int i=0;i<6;i++) {
    mac[i]=EEPROM[i];
  }

  // Generating a new MAC address if the address found is not locally
  // Administrated.  This test requires that the 2 lower bits of the first
  // byte are equal to "2" (bits 1 and 0).
  // Normally it is only required that bit 1 is "1", but checking bit 0 for a 0
  // allows to detect an uninitialized EEPROM.
  if((mac[0]&0x03)!=2) { // Is this a locally administered address?
    // No a locally managed address, generate random address and store it.
    #ifdef ENABLE_MAC_INIT_MESSAGES
      Serial.println("GENERATE NEW MAC ADDR");
    #endif
    // make sure random numbers used are not always the same
    randomSeed(analogRead(0));
    for(int i=0;i<6;i++) {
      mac[i]=random(256);
      if(i==0) {mac[0]&=0xFC;mac[0]|=0x2;} // Make locally administered address

      EEPROM.update(i,mac[i]);

      #ifdef ENABLE_MAC_INIT_MESSAGES
        if(mac[i]<10) {Serial.print('0');}  // Print two digets
        Serial.print(mac[i],HEX);Serial.print(":");
      #endif
    }
    #ifdef ENABLE_MAC_INIT_MESSAGES
      Serial.println();
    #endif
  }
}

void setup() {
  initMacAddress();
  /*...*/
}

EDIT: An anonymous use suggested a call to randomSeed(analogRead(0)); to ensure that the generated value is random. This (may) need to be done only once in the program.  It's best done in the 'setup()' as  the analog pin that can actually be used depends on the application - one might also use more complex & random initialisation schemes.


text:
Change timeout of `Serial.parseInt()`?
Serial.parseInt() reads from the serial buffer until it sees a non-numeric character or it's timeout is reached. When I use it, I put a space after the last number to make it return faster. Can I change the timeout so if I forget the number it doesn't take as long?

You can, just call
Serial.setTimeout(millisecondValue);

https://www.arduino.cc/en/Serial/SetTimeout
It defaults to one second, and controls the timeouts for readBytes, readBytesUntil, parseInt and parseFloat.

Don't use Serial.parseInt(). It is very very wrong. The whole idea behind how it operates is completely wrong and teaches bad practices and methods.
Part of your way of speeding it up is half-way to doing it properly.
You require a delimiter to say "this is the end of the number". Relying on time in a system that is inherently asynchronous is just plain daft. You have chosen to add a space. A better choice is to use a proper line ending "\n".
Then you should either read the serial character-by-character and parse it as it arrives until you find the EOL character, or read it character by character into a string (NOT a String, a "string" - a C string - a character array terminated by a NULL character), and then use atoi() etc to convert it to the numerical format you want.
Many of the methods that Arduino provide are not suitable for professional use and should be avoided at all cost lest they teach you the completely wrong way of doing things.

Isn't that just what the Serial.parseInt() function does minus the timeout?

It does one of those methods, yes, plus the timeout. It's the timeout that is evil, and the fact that you have no control over what happens. Better to read the data manually so you a) know what is happening, and b) have control over the entire situation. I have never, and will never, use things like .parseInt().

Fair enough. What if EOL get garbled in transmission somehow? You wait forever?

You wait for the next EOL. But then, if you write your code properly, you won't be "waiting", you'll be "expecting". Written properly serial reading code is non-blocking and your sketch can continue doing other things until the serial data has arrived.

Good point. I will try that.

IIRC the Serial.* methods that have timeouts are based on an assumption that while asyncronous each transmission or 'message' will be contiguous in time, i.e. its written out all at once. This obviously won't work if one wanted to use the serial port like a terminal, ex. a person typing on the other end. AFAIK embedded stuff like this often uses 'bad' practices, but justified by their environment, in that it works under these assumptions. One should be aware of this embedded 'culture' of 'bad' 'code'!


text:
Cannot include .h files back one directory
I am working on a project with multiple arduinos. I want my folder structure to be as follows:
/
  libs/
    someSharedFile.h
  arduino1/
    arduino1.ino
  arduino2/
    arduino2.ino

When I include someSharedFile.h in one of my .ino files like this #include "../libs/someSharedFile.h", I get this error No such file or directory.
However, when I move libs/ to arduino1 and include the shared file like this #include "libs/someSharedFile.h" everything works fine.
I am using IDE 1.6.7 on windows 10.

Arduino IDE copies the files to a temp folder. You can see that when you compile in verbose mode.
As such the lib folder is not available.
You should place you libraries in [your home folder]/arduino/libraries

Thanks for your answer. I was trying to avoid that for git integration. Is there any workaround where the libraries and the main code could be in the same repo?

Not that I know of wit the Arduino IDE.

You could use a symlink that's ignored by git. Why do you need to do this?

I am working in a robotics club at school and I want to make it easy for people to get going without having to install a bunch of libraries first.

I would advice a better IDE for a robotics club. These can handle these situations and have far better version control integration. Off-course I advice my arduino eclipse plugin. http://eclipse.baeyens.it/


text:
Arduino Nano not showing up in /dev
When I plug in my nanoatmega328 to my computer, nothing shows up in /dev as I expect it to. If I plug in my Uno, /dev/ttyACM0 shows up. I have tried several Nanos.
Linux Mint 17.2.

Genuine Nano or cheap Chinese clone?

@Majenko Genuine uno, cheap Chinese nano.

lsusb and dmesg are key points of investigation - you are looking for a USB device and or failure or driver messages after insertion.  Something that is not CDC/ACM would probably be more likely to be /dev/ttyUSB0 or similar, if it recognized with a driver available.

usb-devices is also useful - it can show what driver (if any) is attached to a USB device.

It is not showing up in lsusb. Cannot decipher anything useful from dmesg.

dmesg should be the tool to help you.
Run:
$ dmesg -w

Then hit return a few times (to get some blank lines).
Next plug in your Nano.  Some text should appear on the screen, which will give you a clue as to what is going on.  I don't have a Nano to try with, but a typical working device would look something like:
[29125.599800] usb 9-1.4.1: new full-speed USB device number 13 using ehci-pci
[29125.694742] usb 9-1.4.1: New USB device found, idVendor=04d8, idProduct=0208
[29125.694747] usb 9-1.4.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[29125.694749] usb 9-1.4.1: Product: Lenny
[29125.694751] usb 9-1.4.1: Manufacturer: chipKIT
[29125.694753] usb 9-1.4.1: SerialNumber: CK1660A05353C5
[29125.695213] cdc_acm 9-1.4.1:1.0: This device cannot do calls on its own. It is not a modem.
[29125.695240] cdc_acm 9-1.4.1:1.0: ttyACM0: USB ACM device
[29125.695768] cdc_acm 9-1.4.1:1.2: This device cannot do calls on its own. It is not a modem.
[29125.695791] cdc_acm 9-1.4.1:1.2: ttyACM1: USB ACM device
[29125.697772] input: chipKIT Lenny as /devices/pci0000:00/0000:00:1a.7/usb9/9-1/9-1.4/9-1.4.1/9-1.4.1:1.4/0003:04D8:0208.0004/input/input19
[29125.698394] hid-generic 0003:04D8:0208.0004: input,hidraw2: USB HID v1.11 Mouse [chipKIT Lenny] on usb-0000:00:1a.7-1.4.1/input4

If it doesn't know what the device is it will give you a fraction of the information, and probably tell you it can't attach a driver.
If the device is faulty and not recognisable you will get messages similar to:
[29125.698394] usb 2-2.1: device not accepting address 5, error -71

If you get absolutely nothing displayed then it can't even recognise that anything has been attached to your computer.  Try different USB sockets and different USB cables to see if that helps.
Note: some cheap USB cables used purely for charging small batteries don't have any data wires in them - just power. Using one of these will fail for sure.

Thanks, this clarified the issue for me. The Nano seems to mount by default on /dev/ttyUSB0 whereas the Uno mounts on /dev/ttyACM0, which is what I was used to.

Did you try with lsusb and dmesg?
They should show if the Arduino was detected and what are its parameters (use lsusb -v for more detailed info).
If it is detected but you do not get the corresponding tty device, it might be because of missing/different rules.
You could check out this link and edit the parameters idProduct and idVendor to match what you get from lsusb, in case your rule is not matching.
Then remember to reload the modified rules.
Protip: compare the parameters of your working Uno against the ones from the Nanos and the values set in the rules.

Not showing up in lsusb. Nothing helpful in dmesg

Are you sure that the Nano works? Have you been able to make it do something? In some cases they are shipped blank, without even the bootloader and the only way to make them work is to use an external programmer.

Like Majenko said, if dmesg shows nothing then your cable could be to blame. It could be for power only (no data lines). This happened to me. I wouldn't have even thought of the cable if I did not read it here.
My hardware is also Arduino nano clone (atmega238 + ch340) and the machine runs Ubuntu 15.04. With a good cable the device is recognized like this (dmesg -w):
usb 4-2: new full-speed USB device number 24 using ohci-pci
usb 4-2: New USB device found, idVendor=1a86, idProduct=7523
usb 4-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
usb 4-2: Product: USB2.0-Serial
ch341 4-2:1.0: ch341-uart converter detected
usb 4-2: ch341-uart converter now attached to ttyUSB0

No it was because it was a Chinese clone which don't have serial numbers.


text:
Maintaining pull down on a relay with a shift register
I currently have an Arduino Mega project that uses a relay to switch some high voltage loads. Currently, I use a scheduler library so that every 250ms I check if certain conditions are met and if so I turn off or on the relay. The relay is active when pulled down.
I'm trying to figure out how to transition this project to using a shift register. If the pin needs to be pulled low to be turned on and I want to keep it on, how do I supply a steady "low" signal using a shift register if the register is clocked to only latch every 8 clock cycles (not to mention I only run this code every 250ms). Even if every bit that gets sent by the shift register is low, do I need to no longer use the scheduling library so that every time through the Arduino loop I am sending the low signal so that the low signal can remain constant? With the standard Arduino pin once I set it to low it stays low until I switch it to high. But with a shift register can I keep it low "until I switch it high?"

This is only a problem if you have an unlatched shift-register.

You have misunderstood how shift registers work - and one of the main reasons they exist in the first place.
Shift register ICs have a common 'latch' pin which latches the data present at the input of the cell into the cell, thus updating the output. Some ICs also offer an "output enable", which switches the outputs to a high-impedance state irrespective of the values in the cells - this might not be useful in your case, but the feature exists.
With a serial-to-parallel shift register you can shift in as many bits as you want, at whatever rate you choose, and the outputs will never change until you trigger a rising edge on the LATCH pin.

How a (latching) Shift Register works:
You have eight spaces within the register:
             ___    ___    ___    ___    ___    ___    ___    ___
[DATA_IN]-->|___|--|___|--|___|--|___|--|___|--|___|--|___|--|___|-->[DATA_OUT]
            BIT0                                              BIT7

The 'spaces' are chained together; at one end of the chain is the DATA_IN pin and at the other end is the DATA_OUT pin.
Every time there is a rising edge on the CLOCK pin, data is shifted down the chain from DATA_IN to DATA_OUT, one space at a time. For example, if the state of the 'spaces' is as the left hand column, then upon the rising edge of the CLOCK pin the spaces will change to the values in the right hand column:
 DATA_IN PIN = 1  ->  C  -> ?
BIT0 'SPACE' = 0  ->  L  -> 1
BIT1 'SPACE' = 1  ->  O  -> 0
BIT2 'SPACE' = 1  ->  C  -> 1
BIT3 'SPACE' = 0  ->  K  -> 1
BIT4 'SPACE' = 0  ->  E  -> 0
BIT5 'SPACE' = 1  ->  D  -> 0
BIT6 'SPACE' = 1  ->  G  -> 1
BIT7 'SPACE' = 0  ->  E  -> 1

You will see that BIT(n) changes to the value of BIT(n-1), with BIT0 changing to the value of DATA_IN. The DATA_OUT pin is used to daisy-chain multiple shift registers together. The important thing to note here is that the outputs do not change without a rising edge on the LATCH pin. You can pulse CLOCK as many times as you want, with whatever values on DATA_IN, and the outputs will not change. Ever.
When you finally trigger the LATCH pin, the value in each 'space' is latched into a second row of 'spaces' - these represent the outputs. On a latch trigger, the outputs therefore change to the values of the last eight bits that were shifted into the DATA_IN pin. For example:
OUTPUT = 11001010
                   SHIFT IN "01101111" (starting with RHS first)
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 01101111
                   SHIFT IN "11110000110011001100"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 11110000   i.e. the LAST EIGHT BITS that were shifted in
                   SHIFT IN "10"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 10111100   again the LAST EIGHT BITS that were shifted in

It is generally never the case with a serial-in-parallel-out register that you would ever shift in less that eight bits at a time, so the last example is only there to illustrate the functioning of the IC.

Not all shift registers have latching.

Thank you for your response. Indeed, I do have a misunderstanding. There's one thing I'm still missing. If a relay requires a constant voltage, and the latch triggers every 8 clock cycles. How is a 'HIGH' signal maintained when using the shift register. Another way of putting it: if I have some code that runs on a scheduler every 1 second, and that code shifts all HIGH values into the register and latches it so it pushes a HIGH signal out, will the value drop to LOW between my 1 second intervals when I'm not actively pushing data.. if it does not shift to LOW, why is the HIGH value maintained?

@Inc1982 I've edited the answer, I hope this helps.

Thank you so much for the response. There's one small but important piece of information I'm missing. In my understanding a HIGH signal is say 40ma on an arduino pin, while a LOW signal is 0ma. In-between latches, is the signal kept constant until it is switched again? If so, that would imply that there is some constant power coming from the Arduino that is being fed through the shift register and out the pins. This must be separate from the 8 bits being pushing into the Arduino. Is that why shift registers need a separate power supply?

'High' and 'Low' signals have nothing to do with current; they refer to voltage. There is negligible current flowing between the Arduino and a shift register, at any time. The shift register provides the power to the devices it controls.

Ahh thank you that clarifies it for me. From: http://www.allaboutcircuits.com/textbook/digital/chpt-12/serial-in-parallel-out-shift-register/ "The purpose of the output register is to maintain a constant data output while new data is being shifted into the upper shift register section. This is necessary if the outputs drive relays, valves, motors, solenoids, horns, or buzzers." I didn't realize that after it latches it is able to keep in an output register the voltage differentials on each pin that you were describing.

That is watch 'latching' means.

... relay ... active when pulled down ... shift register ... latch ... Arduino ...

TPIC6C595
shiftOut() and the '595


text:
Can I use the TLC5940 LED Driver if I'm already using other SPI devices on my Arduino mega?
The way I understand SPI is that 3 wires are shared (MOSI, MISO, & SCHK). The slave select is pulled high when you want to write to a specific device. The 3 shared wires can be daisy chained. The TLC5940 LED Driver says that it uses SPI but I don't see any documentation about a slave select. Can I just include this in the standard daisy chaining and assign a new slave select? In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices. I thought that was the whole point of SPI. Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

Can I just include this in the standard daisy chaining and assign a new slave select?

SPI is normally used as a parallel bus and requires MISO to be tri-state (disconnected when not selected).

In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices.

The device does not have a chip select which gives a challenge. No direct wiring is possible but can be solved.

Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

It is possible to connect the TLC5940 but it requires some extra logic. You can for instance block the clock signal when it is not selected. This can be done with a MOSFET or 74HC125 and a pull-low resistor.
Cheers!


text:
Increase IR transmitter directivity and range
I am working on a project to control different devices with arduino and IR LED so I am testing with this circuit:

So, everything is working fine but I want to increase range of my transmitter. For now its barely giving response at 1 meter distance. I want to increase this to at least 5 meters. I tried to increase receiver sensitivity by giving 5V to TSOP, when I do this the range is satisfactory but the directivity is too much its even responding when I point IR LED in opposite direction(inside a room, maybe the radiaton is bouncing off walls - this is not happening with 3.3V). I Know the transmitter range can be increased by increasing the current flowing through LED like this (please correct me if I am wrong):
The problem is with directivity of emitter, I do not want all the devices in my room to turn on when I try to turn on my TV. The devices are placed  up to 1 meter apart and the transmitting range should be at least 5 meters.

Also it would be helpful if someone clarifies which part is actually sensitive (the part which looks like LED or the flat backside part - image below) for TSOP i.e. which part receives the pulses, so that I can cover it with tape (so that it receives signal from only one direction) if nothing else works.

Any help is appreciated, thank you.

Why would all the devices turn on ? Different devices and functions have different 'codes'

I'd start by using a smaller value resistor. You can drive those leds pretty hard, since the are only on for short periods (38000 pulses per second). IR bouncing of walls is normal. Had to prevent this. My TV remote works better if I aim at the ceiling.

I am using same NEC code for all devices, this is only a part of the project the devices actually communicate through WiFi, IR is used to select device. It requires the same code to be used.

@Gerben I am using 330 ohm resistor, I have a couple of 100 ohm ones I'll try that. Can't I just remove the resistor and short the LED and collector of transistor since it is not directly connected to Arduino I/O pin?. I had tested in different rooms and found out that bouncing off walls happens more in rooms with less furniture. Thank you.

Not using a resistor is a bad idea. If you want an even lower value, you could use two 100ohm resistors in parallel. By the way, you really should put a resistor between the Arduino pin and the base of the transistor!!!

Okay I'll add in a resistor between base and I/O pin.

Even if you try to mask the sensor you're still going to get problems with the IR reflecting off objects and maybe even people, I suggest you need to rethink your control/selection mechanism.

you will need discrete IR emitters, aka "blasters". you can find some with small suction cups that seal around the devices IR sensor, ensuring only the correct device receives the code.

Use a red laser instead of IR emitting diode.

Yes thinking of using it

Can i have the source code please Kind regards

more detailed question specification is in this website？ thx ！
https://electronics.stackexchange.com/questions/371867/what-is-the-relationship-between-emitter-intensity-ie-with-the-forward-current-i

The IR sensors are usually build that way, that they get signal from as wide range as possible, also using walls, ceiling etc. to reflect the signal to receiver - the bussiness logic is simple - user want press buttton and have TV reacting - no trying to hit some particular spot on TV wiht invisible light - it is not shooting game, it is meant as remote switch and if it works regardless actual direction, then the best. To select different devices the transmiter sends different codes - every device in room ideally gets the same input, just the TV "knows" it should react say to range 0xFF0000..0xFF00FF and the radio knows it should react to 0xFF1100..0xFF11FF instead (it is more conplicated and the ranges are not continuous and possibly ovelaps, but it is the principle).
So the best way to difference between your devices is using longer numbers and let the device react just to some selected (specific to that device) and ignore all others.
But if you insist on "shooting it directly to head", then the way is putting both the transmitter diode and the receiver to some kind of tubes (like bore of riffle), so the data could be only send to /get from some small cone of space and communication occures only when those cones are aligned. Anyway it would probabelly react on the reflection from the wall on your back (shooting cone opposite way) as then the cone will get way larger by distance (and so hit more receivers) and also from difraction from particles in the wall (so the wall would light to all directions, not just reflect the cone, as mirror would). And there is nearly nothing to prevent this. (Yes, you can cover the wall with some nonreflective black textile or so, but would you do it?)

As for active part of the receiver, the datasheet say the center of sensiteve area is in the centre of the "diode-like" part, with angle around 80 of sensitivity to both sides vercically and horisontally (with the best sensitivity vaguely straight forward) http://html.alldatasheet.com/html-pdf/26589/VISHAY/TSOP1738/1117/6/TSOP1738.html - but basically it can  somehow receive nearly from anywhere on the "diode-like" side.
The back side (flat one) should not be sensitive.

Also you can (and should) use resistor between the pin and transistor base, to limit current from the pin. (transistors have gain like 100 or more, so you need a little current to fully open it).

LEDs are current consumers, not voltage consumers, so you restrict current (not voltage) thru your LED to not burn it and to make it shine more or less. LEDS should use current sources (like providing 20mA, no more or less for normal LED), not voltage sources (which would provide something like 9V, 5V, 3.3V or any other value, no more or less).
But as there are much more easily obtained voltage sources, the resistors are use to limit current thru the LEDs as easy "cheat".
You take the voltage of source (say 9V), substract all known voltages around the path (typically 0.7V for transistors, 1.2V for LEDS and so) and suppose the rest is wasted on the resistor. Knowing maximum alloved current for your LED (typically 20mA for "normal one") you compute value of resistor by dividing voltage (in V) by current (in A) to get resitance (in Ohm).
In your picture: 9V-0.7V-1.2V=7.1V on resistor, 7.1V/0.02A=355 Ohm. You take any resistor equal or larger than that and it would be safe to shine for infinity.
First cheap IR LED I found have typical continuous current 20mA, Absolute Maximum Ratings at Ta=25℃ (room temperature) is current 100mA and  Peak Forward Current (1/10 Duty Cycle, 0.1ms Pulse Width) 1A. But those Absolute values are values, where you probabelly will destroy the LED soon, as any temperatue higher (as in summer) moves them down fast. You should read "Absolute Maximum Ratings Values"  as "values, which can destroy it randomly any moment, if I get near to them" rather than "manufacturer recomed it for extreme usage". (you cannot make perfect laboratory conditions for any device in normal use).
But if you want to make extra power on the risk of destroying the LED, you can set the resistor as low as 7.1V/0.1A = 71 Ohm or even for short pulses 7.1V/1A=7.1 Ohm, but I would bet, that the LED will burn soon anyway. I myself would risk like 80 Ohm in short pulses, but it does not get as much more light as it get in heat. Consult you datasheet and try only on your own risk.

TLDR: I suggest using unique codes by your Arduino sender for diferent receivers, because you cannot reach you goal other way with good certainlity.
Use your receiver to scan all usual remote controllers you have, then select something totally different for your Arduino receivers.

Thank you so much. This cleared many doubts I had. If IR is built like that then is there an alternative that could provide directivity and range like a low powered laser transmitter and receiver which I could use with arduino?

Yes, for example laser transmiter and photoresistor like here: http://www.instructables.com/id/Arduino-Laser-Tripwire/ (or basically any photo-something - photo-diode, photo-transistor, photo-resistor, even normal LED can be used as receiver ...). But you would need to develope some "protocol" if you want more than just switch it on while you are shining there. And you have to cope with daylight too, so put the receiver in some kind of hole/bore to be not so much affected by normal light. And you would still need to go to modulated PWM, as to filter out other light sources (like in IR).

Just google Ardduino laser :) Or arduino light receiver or arduino transmitter - tons of examples everywhere :)


text:
Why is my circuit working only when I touch it?
I have connected digital pin 2 of arduino to the circuit as shown:

The problem is that the LED is not turning on normally its only turning on when I touch anything on collector side of circuit. What seems to be the reason? Seems like grounding problem as its turning off when I don't touch my legs to ground.

Thank you in advance.

if that's an npn, it's (probably) backwards. you also need to common the ground with the MCU

Hint: Use wires intended for breadboards. The battery wires lack pins.

Sounds like you have guessed it: although it's very hard to say from those photos, it doesn't look like you have the circuit grounded.
Connect a ground from the Arduino to the black wire from the battery.

Yes, you are right its working now. Thank you very much :D.

Sorry for the photos, I uploaded this from my phone and I put connections in image descriptions, but they are not visible in the post.


text:
Detecting mutual contact between balls
Is there a simple way to rig two balls in a way that lets you know if they are touching?
For example, here's a bad idea. Put a free-to-move magnet inside of each ball. When the balls get close, the magnets snap together. Use a magnetic sensor within each ball to tell the direction of the magnet. Use an accelerometer to tell the direction of gravity. When the gravity direction differs from the magnet direction, the balls are touching.
I don't need to know the direction of the contact (that would be ideal, but I don't need it). It should work over the whole surface. I would like to have more than two balls and be able to tell which two are touching. I can make the balls however I want.
(Even very basic advice would be quite helpful. I'm not familiar at all with hardware projects or what kinds of sensors are available or how to combine the available pieces into some desired thing. That includes advice like "this is probably too hard".)

If you want to do it with  easy to get  hardware I guess you can do it without an arduino as follows. If the balls are large enough and they are different colour you can use a machine vision C++ library (such as for example openCV can be used for example to track tennis balls direction and the uniquely colored tennis ball and it tracks more than one ball). All you need is a webcam and PC. Though, I dont know if openCV work an a small PC like a raspberry PI.

@qwerty10 That's an interesting idea. I don't think it will work in my particular case, because I intend to be holding the balls and moving around. My body would likely get in the way of the camera's view. It would also be difficult to distinguish between "touching" and "appear to be touching due to perspective".

I still guess your problem can be solved with machine vision becuase machine vision is used to detect if a point or score has been made
in professional televised tennis or soccer matches (or football
as its called outside USA). In those sports its required to detect
if the moving ball (where ever it is in the air) passed over a line
and touched the surface or floor and I guess you would need to be
accurate with that (say 1mm error bound) to decide that. Also there may be players in the way of the camera view of the ball. I dont know if that sports technology uses openCV.

To me your problem sounds like the problem solved by the sports technology (which uses machine vision).But I dont think an arduino can not do something like track a ball to accuracy such as 1 millimetre in 3D space in someones  hand with the person moving around a few metres-this is what you seem to be asking for-but I maybe wrong as Im new to arduino.

How big are the balls? How big is the surface? Can you do anything to the surface? What are the balls made of?

@Gerben The balls would be hand-sized, about as big as a baseball or softball. I'm not sure what you mean by "the surface"; I care about mutual contact between two balls not contact with a surface. I can make the balls out of whatever I want, but I want to be able to hold them without causing false positives.

Option 1
Seems you say you can make the balls out of whatever you want, I would suggest the spheres be made of a metal and then you can either suspend them by wire spot welded or soldered onto the balls. Then what you do is you connect all the balls to inputs of an Arduino ( this is if you are doing this with one). Then connect all inputs to pull-up resistors.
Then to read if a ball is touching a neighbour you start with ball n and set it as an output and use digitalWrite(n,LOW);  and then poll all the other balls as inputs to see which one reads LOW/0V and then record that in an array, you the move onto ball n+1 and scan the rest of the balls. There is also no need to read the previous ball to n+1 as if it did not register a touch, then it won't register with the next ball.
Then at the end you reset everything and start at the beginning again. Using the data how you wish at the end.
Below code is just to show, not tested.
for(int n =0; n < total_N; n++){
      pinMode(n, OUTPUT);

  for(int i = 0; i < total_inputs; i++){
          if(!(digitalRead(n)))// ball is touching
   {

         myArray[i] = 1;// store a point in the list, replace with a way you want
    }
    else myArray[i] = 0;
}
     pinMode(n, INPUT);
}

Option 2 (probably to much to go wrong)
You could use material that will allow IR rays to pass through and make you balls with that. Then in each ball is have a IR transmitter and a IR receiver, making a transceiver basically and then have each ball echo a specific ID and let the other balls pick it up.
To solve the issue that IR travels a good distance you will need to limit the power/voltage/current to the IR transmitter(LED) so that they only work within a certain range.
Option 3
You could place reed switches or hall effect sensors in each ball, with a magnet. Place a niece of metal behind the sensor so that the magnet is drawn to it. The only issue with this is that either the magnet in each ball will not only affect its neighbour but also itself. So they will need to be spaced and also the right strength of magnet.
Option 4
A combination of option 2 and 3 would be to surround a IR receiver setup with a piece of metal disk(like a washer) and also a reed switch or hall effect sensor, and then have a ball with a magnet and a IR transmitter by a magnet, so that when the two are pulled together the transmitter and receiver match up in the same view and are able to tell them that they are connected, you would thus have each ball with a set, one to receive placed on one side and another on the opposite side to transmit.


text:
5 inch TFT LCD for Arduino
I want to use a 5 inch 800x480 TFT display (touch not needed) with an Arduino (mega, uno or due). I'm thinking of buying this display: link (buydisplay.com). How can I connect this ?
I have also seen some pricier screens with serial i2c connection., but I don't understand the difference between this and using a shield?
Do anyone have any advice for displays to order and/or shields for Arduino ? Preferably a solution that I can reproduce by my self later for mass-production by doing be own circuit board.
Thanks in advance!

You need a driver board to run it. SSD1963 based ones are popular and are often included on the screen, especially the 7" ones on eBay.
Arduinos cannot drive a display directly. Small TFT screens often include the driver chip on them in the form of a Chip On Glass (CoG). That can't be done with the larger screens due to the sheer amount of memory needed to store the frame buffer. So an external chip has to be used, or a microcontroller with built in TFT interface.
Note that even with an SSD1963 (or equivalent - see the ones BuyDisplay sell are based on the RA8875) interfacing the Arduino to the TFT screen results will most likely be somewhat disappointing. Especially if you are interfacing using SPI or I2C which will create a bottleneck. Best is to interface with a 16-bit "8080" interface (16 data bits, read, write, chip select, reset and D/C), however that takes a lot of IO pins, and ideally a proper parallel interface to drive it quickly. And you want a lot of RAM for manipulating the data you want to display...

Ok but I can not use it with the raw display and arduino due?

No, that does not have a TFT interface in it. Generally you want a SoC, such as is used on the Raspberry Pi or Beaglebone Black, for that kind of thing.

ok, the problem is that i want to avoid OS based devices and only use micro controllers that i can build by my self with EagleCAD.

So you will need a display with a driver chip - and that means spending more money.

and what about this driver? https://www.adafruit.com/product/1590

okay so basically this kit will work nicely with a Due i guess: http://www.buydisplay.com/default/display-5-inch-tft-arduino-touch-shield-ssd1963-for-mega-due ?

Ideal, yes. And should be well supported by most graphics libraries too.

Ok, one last question: Does it matter if I use a Due or Uno/mega with this as the driver has its own chip and RAM memory that run in parallel ? Thanks again

The Uno will struggle. Also you won't be able to run in 16 bit parallel, only 8 bit parallel, and that will both slow things down and use most of your Uno pins. Better use a Due.


text:
Can I use an IR distance sensor in rain?
I am planning on using 'SHARP IR Distance Sensor - GP2Y0A710K0F' in an outdoor environment. Assuming the casing I design for the sensor is waterproof, can I use this IR sensor without any trouble? If the water is interfering, what can I do to reduce that noise?
The sensor is fixed above the ground and aimed towards the ground like this.

If this is off topic, where can I ask a technical question like this, and not get rejected by people who did not even bother to answer?

According to the data sheet for this device, located at Adafruit's web site, the frequency used is 870nm. If you required specific attenuation figures, that might be useful information.
Another web site suggests that thermal IR camera imaging systems (which use a different frequency IR) are attenuated by rain. Some of the IR energy is lost by absorption and some by reflection. I was hesitant to suggest that as the answer due to the different frequencies involved.
Digikey has a document covering wide use of IR sensing. Listed in the document:
The disadvantages of IR technology are:

Line of sight: transmitters and receivers must be almost directly
aligned
Blocked by common materials: people, walls, plants, and other objects can block transmission
Short range: performance drops off with longer distances
Light and weather sensitive: direct sunlight, rain, fog, dust, and pollution can affect transmission
Speed: data rate transmission is lower than typical wired and RF transmission

Even though data transmission is not your objective, the considerations apply. A wet surface over which your sensor passes will have the signal attenuated and may also be slightly diffracted.
I found no direct reference to the magnitude of the attenuation. If your sensor is protected from water intrusion and the surface is only slightly wet, you may have minimal problems reading the distance. If the rainfall is at the level of a frog-strangler, there could be sufficient water to eliminate useful readings.
Another search resulted in a similar question on the physics stack exhange, which led to a more comprehensive answer:

There is another image on the same page, but both show that at the 870nm frequency, there is lower attenuation than much of the IR spectrum, particularly above 3000nm. The above linked document suggests that the affect of rain (water) is low at near-infrared (970-1940nm) but that's still higher than the device's 870nm figure.
For your objective, shielding the surface from rain (umbrella) or clearing the surface of standing water seems to be the best options. If those are impractical, one would have to experiment to determine how much water flow can be tolerated before the signal is lost or attenuated beyond reception limits.

Thank you very much for this comprehensive answer @fred. I will follow the guide you gave and do some experiments with rain. Never thought that the frequency had a connection with my problem. Thank you very much.

the ir-sensor senses a difference in infrared. the rain will only interfere if its way warmer then the base outside temperature. this is how humans and other mammals trigger infrared sensors on outdoor garden lamps. we emit infrared because our body temp being higher than the temperature of our surroundings.
just a nice quote from this site: https://www.techwalla.com/articles/how-do-ir-sensors-work

All objects emit light according to their temperature--this is called "black body radiation." The hotter the object, the shorter wavelength of light it emits. The Earth emits infrared light at a peak of about nine to 10 micrometers--and so do warm-blooded animals like humans. This light can be used to detect motion or warmth.

Thank you for the response @Jelle. I think you misunderstood how the SHARP IR distance sensor works. It uses it's own IR light source and captures the reflection on a surface. Black body radiation has nothing to do with it.

i see. i was expecting a standard pir sensor


text:
check string for specific characters?
I am just wondering if it is possible to check a string for specific characters.  For example if my string is String mystr = "test"; and I wanted to check for the letter t at the beginning and if it is NOT there do something how would I go about this?
I have read about string.startsWith(string2); however it returns true or false, I want to be able to do "XYZ" if "ABC" isn't satisfied, and it would seem that string.contains isn't a thing.
To paraphrase, I am trying to create an if statement that will evaluate if a string starts with a certain character(s) and will do something if this condition is NOT met.

In C and C++, the ! operator means “not”. E.g. if (!(the condition)) { some_action(); } means “do some action if the condition is not satisfied”.

Yes!  I thought that I might be able to adapt the string.startsWith, however it flagged saying expected unqualified id before '!' token

What did you write to get that error? If you don't show us your code, we won't be able to help.

I messed up and put the ! in the wrong place, sorry to have not caught that.

Have you tried the following?
if(!actualString.startsWith(expectedString)) {
  // do whatever you have to
}

BTW, that is what actually suggested in @EdgarBonet's comment.

That did it, I had the ! in the wrong place.


text:
I swear this worked yesterday!! - mysterious compiler error
I thought I finally had this working yesterday, the code compiled, and executed on the arduino, there were however some small quirks but today I went to fix a small timing issue, but got the following errors instead.  Nothing related to the errors was changed, they just showed up, in fact I went back to the original code which was compiling fine yesterday and it won't compile either.  The errors are directly below this followed by the libraries which appear to be the cause of the errors.  Please help, I just want to get this project finished.
Arduino: 1.6.7 (Mac OS X), TD: 1.28-beta1, Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

In file included from /Users/DMYoung1/Library/Arduino15/packages/arduino/hardware/avr/1.6.13/cores/arduino/Arduino.h:28:0,
from /Users/DMYoung1/Documents/Arduino/libraries/Morse_EnDecoder/MorseEnDecoder.h:7,
from /Users/DMYoung1/Documents/Arduino/libraries/Morse_EnDecoder/MorseEnDecoder.cpp:67:
/Users/DMYoung1/Documents/Arduino/libraries/Morse_EnDecoder/MorseEnDecoder.cpp:75:19: error: variable 'morseTable' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
char morseTable[] PROGMEM =
               ^
exit status 1
Error compiling for "Arduino/Genuino Mega or Mega 2560"

I am attaching my code and the libraries I am using.
Morse EnDecoder.h
#ifndef MorseEnDecoder_H
#define MorseEnDecoder_H

#if (ARDUINO <  100)
#include <WProgram.h>
#else
#include <Arduino.h>
#endif

#define MORSE_AUDIO true
#define MORSE_KEYER false
#define MORSE_ACTIVE_LOW true
#define MORSE_ACTIVE_HIGH false

class morseDecoder
{
public:
morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup);
void decode();
void setspeed(int value);
char read();
boolean available();
int AudioThreshold;
long debounceDelay;     // the debounce time. Keep well below dotTime!!
boolean morseSignalState;
private:
int morseInPin;         // The Morse input pin
int audioSignal;
int morseTablePointer;
int wpm;                // Word-per-minute speed
long dotTime;           // morse dot time length in ms
long dashTime;
long wordSpace;
boolean morseSpace;     // Flag to prevent multiple received spaces
boolean gotLastSig;     // Flag that the last received morse signal is decoded as dot or dash
boolean morseKeyer;
boolean lastKeyerState;
boolean morseAudio;
boolean activeLow;
long markTime;          // timers for mark and space in morse signal
long spaceTime;         // E=MC^2 ;p
long lastDebounceTime;  // the last time the input pin was toggled
long currentTime;       // The current (signed) time
char decodedMorseChar;  // The last decoded Morse character
};

class morseEncoder
{
public:
morseEncoder(int encodePin);
void encode();
void setspeed(int value);
void write(char temp);
boolean available();
int morseSignals;       // nr of morse signals to send in one morse character
char morseSignalString[7];// Morse signal for one character as temporary ASCII string of dots and dashes
private:
char encodeMorseChar;   // ASCII character to encode
boolean sendingMorse;
int wpm;                // Word-per-minute speed
long dotTime;           // morse dot time length in ms
long dashTime;
long wordSpace;
int morseSignalPos;
int sendingMorseSignalNr;
long sendMorseTimer;
long lastDebounceTime;
long currentTime;
protected:
int morseOutPin;
virtual void setup_signal();
virtual void start_signal(bool startOfChar, char signalType);
virtual void stop_signal(bool endOfChar, char signalType);
};

#endif

Here is Morse EnDecoder.cpp
/*          MORSE ENDECODER

- Morse encoder / decoder classes for the Arduino.

Copyright (C) 2010-2012 raron

GNU GPLv3 license:

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Details: http://raronoff.wordpress.com/2010/12/16/morse-endecoder/

#include "MorseEnDecoder.h"

// Morse code binary tree table (dichotomic search table)

// ITU with most punctuation (but without non-english characters - for now)
const int morseTreeLevels = 6; // Minus top level, also the max nr. of morse signals
const int morseTableLength = pow(2,morseTreeLevels+1);
const char morseTable[] PROGMEM =
" ETIANMSURWDKGOHVF*L*PJBXCYZQ!*54*3***2&*+****16=/***(*7***8*90*"
"***********?_****\"**.****@***'**-********;!*)*****,****:*******\0";

morseDecoder::morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup)
{
morseInPin = decodePin;
morseAudio = listenAudio;
activeLow = morsePullup;

if (morseAudio == false)
{
pinMode(morseInPin, INPUT);
if (activeLow) digitalWrite (morseInPin, HIGH);
}

// Some initial values
wpm = 13;
AudioThreshold = 700;
debounceDelay = 20;
dotTime = 1200 / wpm;       // morse dot time length in ms
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;

morseTablePointer = 0;

morseKeyer = LOW;
morseSignalState = LOW;
lastKeyerState = LOW;

gotLastSig = true;
morseSpace = true;
decodedMorseChar = '\0';

lastDebounceTime = 0;
markTime = 0;
spaceTime = 0;
}

void morseDecoder::setspeed(int value)
{
wpm = value;
if (wpm <= 0) wpm = 1;
dotTime = 1200 / wpm;
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;
}

boolean morseDecoder::available()
{
if (decodedMorseChar) return true; else return false;
}

char morseDecoder::read()
{
char temp = decodedMorseChar;
decodedMorseChar = '\0';
return temp;
}

void morseDecoder::decode()
{
currentTime = millis();

// Read Morse signals
if (morseAudio == false)
{
// Read the Morse keyer (digital)
morseKeyer = digitalRead(morseInPin);
if (activeLow) morseKeyer = !morseKeyer;

// If the switch changed, due to noise or pressing:
if (morseKeyer != lastKeyerState) lastDebounceTime = currentTime; // reset timer

// debounce the morse keyer
if ((currentTime - lastDebounceTime) > debounceDelay)
{
  // whatever the reading is at, it's been there for longer
  // than the debounce delay, so take it as the actual current state:
  morseSignalState = morseKeyer;

  // differentiante mark and space times
  if (morseSignalState) markTime = lastDebounceTime;
  else spaceTime = lastDebounceTime;
}
} else {
// Read Morse audio signal
audioSignal = analogRead(morseInPin);
if (audioSignal > AudioThreshold)
{
  // If this is a new morse signal, reset morse signal timer
  if (currentTime - lastDebounceTime > dotTime/2)
  {
    markTime = currentTime;
    morseSignalState = true; // there is currently a Morse signal
  }
  lastDebounceTime = currentTime;
} else {
  // if this is a new pause, reset space time
  if (currentTime - lastDebounceTime > dotTime/2 && morseSignalState == true)
  {
    spaceTime = lastDebounceTime; // not too far off from last received audio
    morseSignalState = false;     // No more signal
   }
 }
}

// Decode morse code
if (!morseSignalState)
{
  if (!gotLastSig)
  {
    if (morseTablePointer < morseTableLength/2-1)
    {
    // if pause for more than half a dot, get what kind of signal pulse (dot/dash) received last
    if (currentTime - spaceTime > dotTime/2)
    {
      // if signal for more than 1/4 dotTime, take it as a morse pulse
      if (spaceTime-markTime > dotTime/4)
      {
        morseTablePointer *= 2;  // go one level down the tree
        // if signal for less than half a dash, take it as a dot
        if (spaceTime-markTime < dashTime/2)
        {
           morseTablePointer++; // point to node for a dot
           gotLastSig = true;
        }
        // else if signal for between half a dash and a dash + one dot (1.33 dashes), take as a dash
        else if (spaceTime-markTime < dashTime + dotTime)
        {
           morseTablePointer += 2; // point to node for a dash
           gotLastSig = true;
        }
      }
    }
  } else { // error if too many pulses in one morse character
    //Serial.println("<ERROR: unrecognized signal!>");
    decodedMorseChar = '#'; // error mark
    gotLastSig = true;
    morseTablePointer = 0;
  }
}
// Write out the character if pause is longer than 2/3 dash time (2 dots) and a character received
if ((currentTime-spaceTime >= (dotTime*2)) && (morseTablePointer > 0))
{
  decodedMorseChar = pgm_read_byte_near(morseTable + morseTablePointer);
  morseTablePointer = 0;
}
// Write a space if pause is longer than 2/3rd wordspace
if (currentTime-spaceTime > (wordSpace*2/3) && morseSpace == false)
{
  decodedMorseChar = ' ';
  morseSpace = true ; // space written-flag
}

} else {
// while there is a signal, reset some flags
gotLastSig = false;
morseSpace = false;
}

// Save the morse keyer state for next round
lastKeyerState = morseKeyer;
}

morseEncoder::morseEncoder(int encodePin)
{
  morseOutPin = encodePin;
  this->setup_signal();

// some initial values
sendingMorse = false;
encodeMorseChar = '\0';

wpm = 13;
dotTime = 1200 / wpm;       // morse dot time length in ms
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;

}

void morseEncoder::setspeed(int value)
{
wpm = value;
if (wpm <= 0) wpm = 1;
dotTime = 1200 / wpm;
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;
}

boolean morseEncoder::available()
{
if (sendingMorse) return false; else return true;
}

void morseEncoder::write(char temp)
{
if (!sendingMorse && temp != '*') encodeMorseChar = temp;
}

void morseEncoder::setup_signal()
{
pinMode(morseOutPin, OUTPUT);
digitalWrite(morseOutPin, LOW);
}

void morseEncoder::start_signal(bool startOfChar, char signalType)
{
digitalWrite(morseOutPin, HIGH);
}

void morseEncoder::stop_signal(bool endOfChar, char signalType)
{
digitalWrite(morseOutPin, LOW);
}

void morseEncoder::encode()
{
currentTime = millis();

if (!sendingMorse && encodeMorseChar)
{
// change to capital letter if not
if (encodeMorseChar > 96) encodeMorseChar -= 32;

// Scan for the character to send in the Morse table
int p;
for (p=0; p<morseTableLength+1; p++) if (pgm_read_byte_near(morseTable + p) == encodeMorseChar) break;

if (p >= morseTableLength) p = 0; // not found, but send a space instead

// Reverse binary tree path tracing
int pNode; // parent node
morseSignals = 0;

// Travel the reverse path from position p to the top of the morse table
if (p > 0)
{
  // build the morse signal (backwards morse signal string from last signal to first)
  pNode = p;
  while (pNode > 0)
  {
    if ( (pNode & 0x0001) == 1)
    {
      // It is a dot
      morseSignalString[morseSignals++] = '.';
    } else {
      // It is a dash
      morseSignalString[morseSignals++] = '-';
    }
    // Find parent node
    pNode = int((pNode-1)/2);
  }
} else { // Top of Morse tree - Add the top space character
  // cheating a little; a wordspace for a "morse signal"
  morseSignalString[morseSignals++] = ' ';
}

morseSignalString[morseSignals] = '\0';

// start sending the the character
sendingMorse = true;
sendingMorseSignalNr = morseSignals; // Sending signal string backwards
sendMorseTimer = currentTime;
if (morseSignalString[0] != ' ') this->start_signal(true, morseSignalString[morseSignals-1]);
}

// Send Morse signals to output
if (sendingMorse)
{
char& currSignalType = morseSignalString[sendingMorseSignalNr-1];
bool endOfChar = sendingMorseSignalNr <= 1;
switch (currSignalType)
{
  case '.': // Send a dot (actually, stop sending a signal after a "dot time")
    if (currentTime - sendMorseTimer >= dotTime)
    {
      this->stop_signal(endOfChar, currSignalType);
      sendMorseTimer = currentTime;
      currSignalType = 'x'; // Mark the signal as sent
    }
    break;
  case '-': // Send a dash (same here, stop sending after a dash worth of time)
    if (currentTime - sendMorseTimer >= dashTime)
    {
      this->stop_signal(endOfChar, currSignalType);
      sendMorseTimer = currentTime;
      currSignalType = 'x'; // Mark the signal as sent
    }
    break;
  case 'x': // To make sure there is a pause between signals
    if (sendingMorseSignalNr > 1)
    {
      // Pause between signals in the same letter
      if (currentTime - sendMorseTimer >= dotTime)
      {
        sendingMorseSignalNr--;
        this->start_signal(false, morseSignalString[sendingMorseSignalNr-1]); // Start sending the next signal
        sendMorseTimer = currentTime;       // reset the timer
      }
    } else {
      // Pause between letters
      if (currentTime - sendMorseTimer >= dashTime)
      {
        sendingMorseSignalNr--;
        sendMorseTimer = currentTime;       // reset the timer
      }
    }
    break;
  case ' ': // Pause between words (minus pause between letters - already sent)
  default:  // Just in case its something else
    if (currentTime - sendMorseTimer > wordSpace - dashTime) sendingMorseSignalNr--;
}
if (sendingMorseSignalNr <= 0 )
{
  // Ready to encode more letters
  sendingMorse = false;
  encodeMorseChar = '\0';
}
}
}

And finally, here is my code!!
#include <avr/pgmspace.h>
#include <MorseEnDecoder.h>
#include <stdio.h>
#include <morse.h>
#define PIN_STATUS  13
#define CPU_RESTART_ADDR (uint32_t *)0xE000ED0C
#define CPU_RESTART_VAL 0x5FA0004
#define CPU_RESTART (*CPU_RESTART_ADDR = CPU_RESTART_VAL);

// Pin mapping
const byte morseInPin = 7;
const byte morseOutPin = 13;
String check = "";
String origin = "SOS";
const int maxItems = 3;
int x;
char myArray[maxItems], curChar;
char nextChar;
int i;
int y;

// Instantiate Morse objects
morseDecoder morseInput(morseInPin, MORSE_KEYER, MORSE_ACTIVE_LOW);
morseEncoder morseOutput(morseOutPin);

// Variables dealing with formatting the output somewhat
// by inserting CR's (carriage returns)
long lastTransmissionTime;
long currentTime;
boolean transmissionEnded = true; // Flag to mark old transmission is finished

// Minimum transmission pause time to insert carriage returns (CR)
// Adjust depending on Morse speed. IE 13 wpm = 646 ms between words (no CR).
const long transmissionPaused   = 1000; // Suitable for 13 wpm?

LEDMorseSender sender(PIN_STATUS);

void setup()
{
Serial.begin(9600);
Serial.println("Morse EnDecoder Geocache");

// Setting Morse speed in wpm - words per minute
// If not set, 13 wpm is default anyway
morseInput.setspeed(5);
morseOutput.setspeed(5);

lastTransmissionTime = (long)millis();

}

void(* resetFunc) (void) = 0; //declare reset function @ address 0

void loop()
{
currentTime = (long)millis();

// Need to call these once per loop
morseInput.decode();
morseOutput.encode();

// RECEIVE MORSE (INPUT)
// If a character is decoded from the input, write it to serial port
if (morseInput.available())
{

char receivedMorse = morseInput.read();
Serial.print(receivedMorse);
// A little error checking
if (receivedMorse == '#') Serial.println("< ERROR:too many morse signals! >");
morseOutput.write('#');
morseOutput.encode();

//Create Array out of receivedMorse Chars

    curChar = 0;
    nextChar = receivedMorse;
    curChar +=nextChar;
    myArray[i] = curChar;
    check.concat(myArray[i]);
    Serial.println(check);

//Check input and respond
if (check == origin)      //GOOD JOB!!  Your reward is as follows
{
Serial.println("check = origin");
Serial.println(check);
sender.setup();
sender.setWPM(5);
sender.setMessage(String("help is coming"));
sender.startSending();
}
else if (check =="S") {}
else if (check == "SO") {}
else if (check == " SOS") {}
else if (check.length() >4)
{
delay(100);
Serial.println("resetting");
delay(500);
resetFunc();  //call reset
delay(100);
}
else {}
}
sender.continueSending();
}

Did you update the Arduino IDE or AVR GCC toolchain? That would explain the compiler error. More recent versions of the compiler will require program memory data structures to be declared "const".

I don't believe that I did, do you happen to know a version number that I could try to revert to?

I went back to 1.6.10, that didn't fix the error, it does not appear that the ide was updated since this has happened.  I am also using IDE 1.6.7 which has been out since december and I have not updated it recently.  I am however updating to 1.6.11 to see if that will fix it and if not, plan to return to 1.6.7 as I have had trouble with the new software in the past.

Apparently you have made multiple copies of MorseEnDecoder.cpp, some of them modified, because the morseTable[] declaration shown in the error message is different than that shown in the code you said is MorseEnDecoder.cpp.  Specifically, line 32 of that code is
const char morseTable[] PROGMEM =

while the error message refers to a line 75 which reads
char morseTable[] PROGMEM =

The solution is to extirpate extraneous copies and restore MorseEnDecoder.cpp to a correct version.

I dowloaded the original code, before I posted this question, to attempt to confirm that this was not the case.  The original code and library would not compile either.  I will look at this again though.

I have downloaded everything again, and replaced my old files.  This did not fix the error.

Search your file system for files named MorseEnDecoder.cpp and see if one of them has the line without const at front.  Eg, on a linux system, grep 'char morseTable' $(locate MorseEnDecoder.cpp)

WOW!!  Well, that fixed it.  I would likely have never found that!!


text:
If a Timer is used, disabling some PWM pins, can I still use those pins for Digital write?
It's my understanding that when a Timer is used on an Arduino (in my case the Arduino Mega), it can disable analog write on some PWM pins, which pins depends on the Timer being used. For instance on the Mega, pins 44,45,46 are controlled by Timer 5.  If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

You can view the connection between the Timer and the pins as programmable. The connection is enabled by, for instance, analogWrite(). The Timer control registers have a setting for both the connection and control logic of the pin (clean, set or toggle on timer value match).
You can use the Timer to generate interrupts without connecting a pin. This is the case with micros() and millis() which get their values from a counter which is updated by an ISR on Timer 0 (overflow). analogWrite() on pin 5 and 6 connects to Timer 0 value match logic.
analogWrite() uses the Timer value match and connects the pins. Enabling only the Timer (as you suggest) will allow you to use the pins with digitalWrite(). You can also use the Timer ISR for overflow. The Timer prescale is set for analogWrite().
Cheers!

When using an timer (other than by PWM) you can choose to enable it's output to a pin (which basically is what PWM does). So you can still use them as a digital pin (if you choose not to).
You could set up an PWM signal and enable timer interrupts afaik. But changing PWM, would also change the timer.
There is a difference in only using Arduino functions, or changing the registers directly.
Try to read the "timers" part of the datasheet and find some tutorials about avr/atmel/atmega register changing or/and setting up timers.


text:
do digital input pins act as a positive or negative
I've gotten contradicting information on the subject.  Some say that digital input pins send out positive voltage, and if it goes to ground (for example) it reads LOW but if the pin is connected to power, it will read HIGH.  On the other hand, some say that the input pin is receiving voltage from either power (+5V) or ground (0V).  which one is it?

Digital pins sink or source current. They don't provide negative voltages. If the pin is set to INPUT then it is high impedance and will not "send out positive voltage".
However if you activate the internal pull-ups, as Ignacio said, then effectively the pin is connected to +5V via (approximately) a 50k resistor.

It's both, depending on whether or not the internal pullup has been enabled (INPUT versus INPUT_PULLUP). The pullup ties the input to the positive supply through a moderately large resistance, meaning that it is possible to source a small amount of current from the input pin.


text:
why does it use A0 to define analog pin 0 in some case and why use 0 directly?
https://www.arduino.cc/en/Tutorial/AnalogInput
https://www.arduino.cc/en/Tutorial/Knob
For first line of both examples(not in comments), it define the same pin, analog pin 0, but they use different values. why and can use A1, A2, etc. to define other analog pins?

The answer is in the source code. Keep in mind that for this answer, I'm assuming you have a standard Arduino Uno. For other Arduino platforms the values are different but the situation is the same.
If you look at the analog pin definitions in hardware/arduino/avr/variants/standard/pins_arduino.h, you'll find these lines:
static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
...

Which tells you that if you call analogRead(A0), it is equivalent to calling analogRead(14). So, really, the question is "How can calling analogRead(0) work?"
The answer to that is in hardware/arduino/avr/cores/arduino/wiring_analog.c. If you wade through the defines, you'll see that at the top of analogRead, there is the following code:
if (pin >= 14) pin -= 14; // allow for channel or pin numbers

The result is that passing either 0 or A0 results in 0 being used in the analogRead code.

You can use 0 to 5 for analogRead of pins A0 to A5. However if you want to do digitalRead or digitalWrite on those pins then you have to use A0 through to A5 in order to avoid confusing them with the digital pins 0 to 5 (on the other side of the board).

can use A1, A2, etc. to define other analog pins?

Yes.