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:
Unable to interface AD7705 (SPI) with Arduino
Code as shown below. I am unable to get the 16-bit data. Can someone help me identify my mistake?
byte spiTransfer(volatile byte data) {
  SPDR = data;
  while (!(SPSR & _BV(SPIF)));
  return SPDR;
}
#define DOUT      (50)
#define DIN       (51)
#define SCLK      (52)
#define CS_AD7705 (53)
#define DRDY (4)

void setup() {
  Serial.begin(9600);
  pinMode(DOUT, OUTPUT);
  pinM ode(DIN, INPUT);
  pinMode(SCLK,OUTPUT);
  pinMode(CS_AD7705,OUTPUT);
  pinMode(DRDY,INPUT);
  SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPOL) | _BV(CPHA) | _BV(SPI2X) | _BV(SPR1) | _BV(SPR0);
  delay(10);
  digitalWrite(CS_AD7705, LOW);
  spiTransfer(00010000); //setup register
  spiTransfer(01100110);
  spiTransfer(00100000); //clock register
  spiTransfer(00001000);
  digitalWrite(CS_AD7705, HIGH);
}

void loop() {
  unsigned int data=0;
  digitalWrite(CS_AD7705,LOW); // enable device
  while(!digitalRead(DRDY));
  data = spiTransfer(00111000);  // select ch1 and setup read 16-bit data register
  data = spiTransfer(0)<<8;
  // Get the most significant 8 bits
  Serial.println("data : "+data);
  data |= spiTransfer(0); // Get the least significant 8 bits
  digitalWrite(CS_AD7705, HIGH); // release device
  delay(1000);
  Serial.println(data, HEX);
}

Why mess around with registers like that? Why not just use the SPI library - that's what it's there for.

I think the main problem is the values you are passing to spiTransfer().  By the way they are written I think you think you are passing binary values, you aren't you are passing decimal values.  So
data = spiTransfer(00111000);  // select ch1 and setup read 16bit data

should be
data = spiTransfer(B00111000);  // select ch1 and setup read 16bit data

The number needs prefixing with a B
Also passing a volatile parameter to this function looks wrong to me, especially when you only pass in constants.

Actually, numbers starting with 0 are octal, not decimal. And you should avoid "B" since they are Arduino-specific macros. Instead you should use the (standard these days) 0b format.

Personally I'd write it in hex, but ... :)

Binary is better when you're working with registers - you can visualise the bits in the register easier.

even though using B as prefix the AD7705 is not taking inputs from potentiometer. can some one help me .i has  left vref(+) and vref(-) open

I've been trying to get one of these working too. I think before you can read the data register, you have to tell the COMMs register your intention to do so.
// Select channel to read:
// write to comm reg selecting channel and
// setting up next op to be a read from data reg
SPI.transfer( DRDY_DONT_CARE | REG_DATA | STDBY_OFF | COMMS_READ | CHAN_AIN1 );
//  Do two 8-bit reads, MSByte first
highByte = SPI.transfer(0xff);
lowByte  = SPI.transfer(0xff);

adcValue0 = highByte << 8;
adcValue0 = adcValue0 | lowByte;

Still, I've had sketchy and intermittent success reading the ADC. The looping code seems to lose sync with the ADC; I've been speculating that reading ASAP following DRDY going True is important.
Have you verified that your SPI interface is working? You can read the 24-bit calibration data, which should match the documented values. Doing so verifies that the SPI reads and writes properly, unless the SPI interface behaves differently for different functions. Are you using genuine Analog Devices silicon, or one of the widely available knock-offs (TM7705, like mine)?

source: Stack Exchange

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

sort: votes


text:
using an ESP8266 shield on my Arduino Uno R3 with an unofficial library
I'm using the following Makefile: https://github.com/sudar/Arduino-Makefile
It works very well and I was able to get my LED to blink.
Now I bought a WiFi Shield which is NOT supported officially by the Arduino WiFi library.
It is the following one I bought: ESP8266 ESP-12E CC3000 UART WIFI Wireless Shield Board Modul für Arduino UNO R3 - you can find this on ebay: http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
What I now am about to do is to include the open source library for the ESP8266 which you can find here: https://github.com/esp8266/Arduino#documentation
Now when I try to upload my sketch it tells me that certain dependencies are not resolved. Like this one here #include <functional> which I was not able to include manually. My main problem here is that the github page of the ESP8266 library isn't providing enough information for me how I can get the working lib to use in my sketch.
I need to know how I can get this library to work in my sketch!

what have you done to interact with your esp through arduino ?

That is not a library for the Arduino. That is a core for programming the ESP8266 directly as if it were an Arduino itself.

Hm that makes me dizzy a bit. So I put that WiFi Shield on my Arduino - how can I use this now? Should I use this makefile: https://github.com/plerup/makeEspArduino - from now on to programm my Arduino because it won't work with my plain Arduino Makefile?

No. You need to find the right library to match the firmware that is on the ESP. If that is the normal aithinker AT firmware then you can just treat it like a normal ESP module. If not then you are on your own. You may be able to flash it with the AT firmware.

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


text:
External 5V Power and USB Serial
I have a Chinese Arduino nano clone, but I don't know if it's possible to connect the Arduino to external (5v) power and have a USB serial connection ongoing. I'm trying to make a PC controlled LED Strip that can also work on its own.
For example: the PC controls the Arduino sets it to a specific mode and I turn off the PC, but the Arduino should still be running even when the PC is turned off.
I'm new to the world of arduinos.
I'm planning to use this to control addressable LED RGB Strips and am planning to use a 4000mA max power supply.

Why don't you try to connect it and see for yourself?

i am afraid that i will fry my pc or arduino

Then you might want to buy genuine parts, or at least parts with a schematic you could analyse for such risks.

@DmitryGrigoryev  "Arduino" is an open source hardware and software system. Ones made by other than holders of the now several trademartks are just as genuine as "originals" if they implement  the core features. Use of the term "genuine parts" in this manner is against the spririt which the whole concept of "open source" seeks to promote.

Having used counterless Arduinos and clones, I can tell you that you can connect both without worrying about any danger. Unless you have a very faulty board, your pc won't be damaged, almost surely neither will the board, as is should select the most powerful source, between your usb or a battery/external PS, while leaving untouched the serial line.

this is the answer i needed thank you very much, but just to be sure have you ever fried something that way?

@TheKayneGame never

If you have solved your problem, please choose one of the answers; so that anyone with a similar problem can read it too

If you are new to something, you should start with reading manual.
Here's what official Wiki page of arduino nano says:
https://www.arduino.cc/en/Main/ArduinoBoardNano

Power:
The Arduino Nano can be powered via the Mini-B USB connection, 6-20V unregulated external power supply (pin 30), or 5V regulated external power supply (pin 27). The power source is automatically selected to the highest voltage source.

So to be sure i won't fry my arduino or my pc when connecting 5v to pin 27 and connect the arduino to my pc at the same time?

For a genuine Arduino Nano you would be fine. For a cheap clone who knows, it depends if they skipped some parts to save money.

Make sure you external power is regulated and connected to the same AC source as you pc. Should be perfectly fine then.
Also refer to this thread for additional points regarding safety:
http://arduino.stackexchange.com/questions/11885/is-supplying-5v-from-both-external-5v-and-usb-harmful?rq=1

The info about 100/150mA USB capability in PC is incorrect. Any normal (not "low-power embedded") USB host must supply 500mA (for USB2.0 ports) and 900mA for USB3.0 ports. In a typical PC this power comes from standby +5VSB rail from system Power Supply. Power rating for this rail is no less than 2A for AT12 compliant PC. Of course it is not advisable to take all this power from one port, due to contact rating limits, and possible polyswitch overcurrent protection of USB ports.
Therefore, if the attached USB device draws total less than 1-1.5A, the design should work fine even if PC is in standby mode (turned off but still connected to AC outlet).
However it is still preferable to use a stand-alone power for this kind of projects. The Arduino board must be designed in a way that, if connected to external higher-voltage source, it would not backdrive any significant current into USB VBUS pin. Usually it gets accomplished by means of one single Schottky diode between VBUS and internal power rail on Arduino board.
You can check if your Arduino drives anything back: power the Arduino with, say, 12V power supply, and check with a Multimeter if VBUS pin on the (unattached) USB connector has any voltage. You should load the VBUS with 10k-15k resistor, and the voltage should be small, 200mV or less, if I remember correctly.
ADDENDUM1: Just checked with Arduino-nano schematics. Yes, there is a "auto selecting" Schottky diode, so there will be no backvoltage on VBUS. However, the Arduino design violates another USB requirement - no signal on any connector pin when VBUS is inactive (low). In the Arduino-nano the VBUS does not control the state of FT232 bridge, so it will always pull-up D+ (USBDP) line as soon as 5V is applied, which is in violation of specs. The side effect of this back-driving is that your PC might not re-connect with the Arduino after waking-up, although it is a rare case these days.

You can connect the Arduino nano to recommended external power supply i.e 5V when it acts as a standalone device with other circuitry. As it is connected to PC it starts drawing power from PC(as PC is acting as a host here) and at the same time serial communication goes on. Now if you want to simultaneously connect the nano to PC or any other host say tablet and external power supply it is recommended that you go for an OTG cable cum power splitter y-cable.
But do not rely on power from PC if you have many sensors or components interfaced to aduino nano as PC is capable of giving max current 100mA in USB 2.0 and approx 150mA in USB 3.0

I was not planning to use PC power alone, and the current draw will be around 3 to 4 Ampère.

authors: женя прунькин

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


text:
9V Vin powered Mega - 3V instead of 5V
I'm experiencing an issue with an Arduino Mega 2560 :
I powered the board through the Vin using a +24 --> 9V voltage regulator. When I power the board and measure the 5V output from the board, the voltage quickly drops from 5 to ~3V within seconds.
However, while powering with USB, the 5V output from the board gives us a clear 4.8V.
I have checked the 9V Voltage regulator (connected to the Vin), and it has a +24V input which remains stable (as should the 9V).
Any thoughts ?

How much current are you drawing from the regulator? In other words, what is connected to the regulator (if any) other than the Mega? Also, what is powered by the Mega?

Much more essential question is what 24V -> 9V voltage regulator. Even 100mA means 1.5Watts turned into the heat on it if it's simple 7809 linear voltage regulator.

And what are the specs, esp. max output current, of the 24v - 9v regulator?

Roberto Lo Giacco > The Arduino board is the only component connected to the 9V regulator. I measured only 2mA from the +9V to the Vin. The mega powers two Leds, 1 TFT (1,8"), and 1 SD card reader.

KIIV > The Voltage regulator is made using a LM7809C. Two capacitors are used both from input to ground and from output to ground (as specified in the spec).
JRobert > The voltage regulator is designed to handle up to 1A.

Well, "designed to handle up to 1A" - yes and no. Yes if you have huge heat-sink on it at this voltage drop. So if you can carry it's safe operating area, it can deliver 1A (with 15Watts of power dissipation P = (24V - 9V) * 1A ).

All right, thank you.
I noticed that after 20" or so, the heatsink becomes very hot (burning when touching), and this is the time when the voltage drops. I think there is some sort of overheating issue (although only 2mA are running through the 9V connector).

Power consumption about 2mA is highly unlikely as ATMega2560's consumption should be about 1mA per 1MHz so at least 16mA and add another for voltage regulator, LCD, LEDs...

So, according to the comments the main problem should be a thermal protection in LM7809C regulator.
The voltage drop between regulator's input and output is about 15 Volts and even with current consumption about 150mA it means 2.25W of power dissipation on it.
For such a big difference between input and output voltage switching regulator is recommended. (Or 9V power supply instead of 24V)
And it is not possible to have 2mA current consumption. I've just measured power consumption of bare Arduino Mega 2560 and it is 81mA through barrel jack input (9V) without anything on it. Not even blinking Led. So if you've measured for example 0.2A it's not 2mA but 200mA

I cannot change the power supply as it is powering another device (24V).
I will have a look at the switching regulators, ty.
However, how can the device not work with ~1% of its maximal current ? Could this be an issue related to the capacitors ? The manual I used gives a circuit at the page 18 : http://docs-europe.electrocomponents.com/webdocs/0e1f/0900766b80e1f8e6.pdf

Use DC-DC converter then. There are loads of them at ebay or so. And it's not possible to have only 2mA consuption not even with bare arduino board.

Thank you KIIV.
It seems like the voltage regulator was the cause of this issue, since providing it a +12V (instead of +24V) has given us a good and steady +9V output (connected to the Arduino Vin). I think this was an overheating problem.
We've bought another DC-DC regulator as adviced to prevent this issue.

@EtienneP. Well, then you can mark it as a solution.

"how can the device not work with ~1% of its maximal current" because your measurement is wrong, and because even with a correct current measurement, the limit being hit is the power one, where the huge voltage drop you are asking it to regulate across is a multiplier.


text:
What's the difference between #define and const int when declaring a pin?
Over the course of my Arduino usage and learning, I've noticed that in some sketches people use the #define command to declare pins, while some others simply use const int for the same.
My question is, what's the difference between the two, and which one should be preferred for use?

I guess that you mean #define instead of #include. The more professional way to declare pins is const int myPin = ... This helps the compiler understand that it is a constant value and storage is not required. This is slightly better than #define as it gives the compile information about the data type.

@MikaelPatel exactly... so basically the int method is better right?

Yes. Please update the title and remove "include". That is something totally different and not related :)

I usually prefer to use enum for integer or character constants rather than either #define or const int.  See accepted answer to  Is it better to use #define or const int for constants?,

"#define" is a preprocessor directive. It defines a lable and a value, that will be positioned in the preprocessed-source-code at the same place of each occurence of the label. No type is defined, so it is a basic and dumb substitution of strings before compilation. It can then lead to errors or misunderstandings during compilation.
"const int xxx" defines a type, and locks the value of that instance. It's safer to use this method. The compiler can check for type errors and throw messages (or break compilation) if you made a mistake.
Example:
#define A 5
int dummy_integer = A

... will be preprocessed as...
int dummy_integer = 5

... and the compiler will read this statement.
However, if I remember good, you can always overwrite a preprocessor directive as follows:
#define A 5
int dummy_integer = A
//some code here
#undef A
#define A "my_string"
std::cout << A

That's not good. By using the "const" modifier, instead, you can't change the value (nor the type) of a variable (and so it's defined "constant").


text:
EEPROM bytes preset to 255 while programming
I'm working on a program with Arduino Uno which involves writing and reading EEPROM. I'm using a basic EEPROM library. My problem is: EEPROM values are preset to 255 whenever I burn my program. And there is nothing in my code which will write 255 in these bytes.
I even tried EEPROM_read example from the EEPROM library and got same result. I used EEPROM_clear code before EEPROM_read to set all values to 0. But when I read those values using EEPROM_read, they are 255.
Please help explain what is happening.

See http://forum.arduino.cc/index.php?topic=106754.0

In flash and eeprom memory an erased value is 255. It's all about how flash memory works. If you want something other than 255 in there you will have to write something other than 255 in there.

I've written other values in EEPROM in my program, and those values are retained through program. But they are not retained when I re-flash the code. The EEPROM memory should be retained through multiple flashes.

Then you need, as @Cano64 has suggested, the EESAVE fuse setting. You can read more about setting fuses here: http://www.ladyada.net/learn/avr/avrdude.html - I don't know the Arduino bootloader well enough to say if you can do it through there or not - you may need a cheap hardware programmer (or another Arduino) to set the fuses through ICSP.

You need to set EESAVE fuse
When the ATmega chip is programmed the memory is erased just before the new code is uploaded. Under normal circumstances the eeprom memory is erased as well as the program memory. The EESAVE fuse can be used to tell the chip not to erase the eeprom. This is useful when you want to upgrade code but keep user settings that are stored in eeprom.
The default value is EESAVE=1, not set and eeprom memory is erased during the chip erase cycle when programming.
This fuse calculator is quite handy.

Yes, the fuse calculator is really handy for knowing fuses, but how do I change these fuses using arduino. I'm working on a project with standalone atmega328.

You need a programmer for it (it can be another arduino), maybe you should make a new question about how to set fuses on arduino.

I know that this is relatively an old topic but I wanted to express my experience here that this answer is the only solution to preserve EEPROM data. Once HIGH.EESAVE is set in your programmer, the EEPROM data will be preserved. My setup was AVRISP MKII and Atmel Studio 7.


text:
Cheapest and easiest Arduino board for 12 bit ADC, thinking of M0
I need an Arduino board for simple ADC, but 10 bits of resolution is sadly not enough. I am going to buy a board with 12 bits of resolution, but really couldnt decide on the exact model. It needs to be easily accessable and wont be used for anything else other then ADC. I have my eye on MO, but cant decide if i should buy the pro or the normal one, or just another Arduino board.
I take the data through USB port and the instrument will also be powered with the same USB cable.
* My only option is to use an Arduino*
I know i can use the Aref pin or do oversampling but i really am not intrested in those options. thanks for your input

Is there a reason for not just using whatever board you already own/use along with an external ADC?

@RobertoLoGiacco  well sadly, thats not an option, since the person who wants that project needs it in that way for some specific reasons

You can use Nucleo boards too. But I'm not sure how about it's with arduino ide support. But mbed is sometimes much better. Just libraries aren't available for specific hardware sometimes.

What speed ADC do you need?

@MichaelVincent it really doesnt matter at all, its really a simple data acquisition, even 2 samples per second is enough.

The problem with ADCs is that to get its full resolution you often need to "help it out" usually with software.  Dig into the specifications of what ever chip you end up with.  Find out the number of significant bits for a given sampling speed.  Usually the longer you allow a ADC to work it's magic the better it performs.  Then, you will likely want to average out as many samples as you can.  This, obviously, is for a signal that doesn't change (much).  Like the charge on a battery. If, on the other hand, you are sampling a fast signal.  Then you need to get a really good ADC to begin with.

How fast is the signal you are trying to digitise moving?  Is it virtually stable?  Regards,

The statement my only option is to use an Arduino is not unambiguous whatsoever.
If you meant "Compatible with Arduino IDE" than the Teensy 3.2, officially priced on the Arduino store at 17.90 EUR + VAT is the cheapest official Arduino board providing a 12 bit ADC.
If you meant "Branded as an Arduino" then the Arduino/Genuino M0 Zero, officially priced at 22.00 42.90 EUR + VAT is the cheapest board providing a 12 bit ADC.
This is the result of a quick search on the Arduino web site, which you could have checked yourself.
In my opinion the cheapest "Arduino based" solution would be an Arduino Pro Mini (officially discontinued) or a barebone ATmega328P along with an external 12 bit ADC. This opens up for many options, just use a parametric search on DigiKey, Octopart or any other website of your choice.
A quick search ended up with MAX1245ACAP priced at 1.30 USD + VAT, probably ending in a BOM cost for the entire solution below 10 USD + VAT, excluding the PCB.
UPDATE: as stated in the comments, the M0 is a cheaper version of the Zero.

i also checked the Arduino website but, what really got me confused was M0 and Zero - one from arduino.cc and other from arduino.org - offers the same ADC resolution but the pricing is quite different. Maybe i should have asked straight away "zero or M0" but doing some research on that didnt really pay off.

What meaning do you assign to the word “ubiquitous”?  Its dictionary meaning is  “Being everywhere at once: omnipresent” or  “Widespread; very prevalent”.

The M0 and Zero both use the same processor. The M0 is probably the cheaper one, as it doesn't have the separate programming and debugging chip that the Zero has. It's a nice feature, but I don't think it's working yet with the Arduino IDE. So they are kind of the same. So just get the cheapest one.

Use a Teensy 3.x. Those have 13 bit ADCs

well, allthough i appriciate the thought, it strictly has to be a arduiona board. and 12 is just enough.

Every time someone comes with a suggesting, another requirement pops up. Please add all your requirements in your question, and stop wasting our time. If it has to be Arduino, just go to the Arduino website. They only have a handful of products. Just check them all to see if they meet your magical list of requirements.

i really would hate to waste anyones time but i thought the first sentence of my question, "I need an Arduino board for simple ADC" should have been enough to make myself clear. Anyways thanks for your time

... But it has to be orange with a plaid silk screen ...

The Teensy is Arduino-compatible. I though that would be enough. Look into the Arduino Zero. I think that is the only option.


text:
Arduino Parse data serially on VB
I am working with Arduino Uno, I have tracker application running on Arduino Uno board. I am sending data in comma separated value. Now I want to view data into Visual Basic. I have code as below. The below code is working with fake values but as soon it live stream data split functions gives out error.
Serial output data looks like this.
Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:1,Local Date:0/0/0,Local Time:5:30:2,tracker_des_angle:0.00,tracker_actual_pos:57.22,Wind Speed :0.00,END
Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:1,Local Date:0/0/0,Local Time:5:30:4,tracker_des_angle:43.00,tracker_actual_pos:69.20,Wind Speed :0.95,END
Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:0,Local Date:0/0/0,Local Time:5:30:6,tracker_des_angle:43.00,tracker_actual_pos:16.34,Wind Speed :1.85,END
Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:0,Local Date:0/0/0,Local Time:5:30:8,tracker_des_angle:43.00,tracker_actual_pos:11.89,Wind Speed :2.77,END

visual basic code:
Option Explicit On

Imports System
Imports System.IO.Ports
Imports System.Text

Public Class Solar_Track
    Dim comPORT As String
    Dim receivedData As String = ""
    Dim strArray() As String
    Dim Data As String
    Dim latitude() As String
    Dim longitude() As String
    Dim Local_date() As String
    Dim Local_Time() As String
    Dim Mode_oper() As String
    Dim Dir_motor() As String
    Dim Act_pos() As String
    Dim Dis_pos() As String
    Dim wind_pos() As String
    Dim start As Boolean
    Dim End_Result As Boolean
    Dim result As Boolean

    Sub Parse_receivedata(ByVal msg As String)

        RichTextBox1.Text &= msg
        Data = msg

        strArray = Split(Data, ",")
        latitude = Split(strArray(1), ":")
        Text_Latitude.Text = latitude(1)

        longitude = Split(strArray(2), ":")
        Text_Longitude.Text = longitude(1)

        Mode_oper = Split(strArray(3), ":")
        Text_Mode.Text = Mode_oper(1)

        Dir_motor = Split(strArray(4), ":")
        Text_MotorDir.Text = Dir_motor(1)

        Local_date = Split(strArray(5), ":")
        Text_LocalDate.Text = Local_date(1)

        Local_Time = Split(strArray(6), ":")
        Label_hour.Text = Local_Time(1)
        Label_min.Text = Local_Time(2)
        Label_Sec.Text = Local_Time(3)

        Dis_pos = Split(strArray(7), ":")
        Text_TrackerDesire.Text = Dis_pos(1)

        Act_pos = Split(strArray(8), ":")
        Text_TrackerActual.Text = Act_pos(1)

        wind_pos = Split(strArray(9), ":")
        Text_Windspeed.Text = wind_pos(1)

    End Sub

    Sub data_parse()
        Data = "Start,Latitude:13.00,longitude:60.00,MODE:1,DIR:1,Local Date:0/0/0,Local Time:5:30:2,tracker_des_angle:0.00,tracker_actual_pos:54.48,Wind Speed :0.00,END"
        strArray = Split(Data, ",")

        latitude = Split(strArray(1), ":")
        Text_Latitude.Text = latitude(1)

        longitude = Split(strArray(2), ":")
        Text_Longitude.Text = longitude(1)

        Mode_oper = Split(strArray(3), ":")
        Text_Mode.Text = Mode_oper(1)

        Dir_motor = Split(strArray(4), ":")
        Text_MotorDir.Text = Dir_motor(1)

        Local_date = Split(strArray(5), ":")
        Text_LocalDate.Text = Local_date(1)

        Local_Time = Split(strArray(6), ":")
        Label_hour.Text = Local_Time(1)
        Label_min.Text = Local_Time(2)
        Label_Sec.Text = Local_Time(3)

        Dis_pos = Split(strArray(7), ":")
        Text_TrackerDesire.Text = Dis_pos(1)

        Act_pos = Split(strArray(8), ":")
        Text_TrackerActual.Text = Act_pos(1)

        wind_pos = Split(strArray(9), ":")
        Text_Windspeed.Text = wind_pos(1)

    End Sub

    Private Sub Solar_Track_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Timer1.Enabled = False
        comPORT = ""
        For Each sp As String In My.Computer.Ports.SerialPortNames
            comPort_ComboBox.Items.Add(sp)
        Next
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comPort_ComboBox.SelectedIndexChanged
        If (comPort_ComboBox.SelectedItem <> "") Then
            comPORT = comPort_ComboBox.SelectedItem
        End If
    End Sub

    Private Sub BtConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connect_BTN.Click
        If (connect_BTN.Text = "Connect") Then
            If (comPORT <> "") Then
                SerialPort1.Close()
                SerialPort1.PortName = comPORT
                SerialPort1.BaudRate = 9600
                SerialPort1.DataBits = 8
                SerialPort1.Parity = Parity.None
                SerialPort1.StopBits = StopBits.One
                SerialPort1.Handshake = Handshake.None
                SerialPort1.Encoding = System.Text.Encoding.Default
                SerialPort1.ReadTimeout = 10000

                SerialPort1.Open()
                connect_BTN.Text = "Dis-connect"
                Timer1.Enabled = True
                Timer_LBL.Text = "Timer: ON"

            Else
                MsgBox("Select a COM port first")
            End If
        Else
            SerialPort1.Close()
            connect_BTN.Text = "Connect"
            Timer1.Enabled = False
            Timer_LBL.Text = "Timer: OFF"
        End If

    End Sub
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        receivedData = ReceiveSerialData()
        ''RichTextBox1.Text &= receivedData
        Parse_receivedata(receivedData)
        receivedData = ""
        '' data_parse()
    End Sub
    Function ReceiveSerialData() As String
        Dim Incoming As String
        Try
            Incoming = SerialPort1.ReadExisting()
            If Incoming Is Nothing Then
                Return "nothing" & vbCrLf
            Else
                Return Incoming
            End If
        Catch ex As TimeoutException
            Return "Error: Serial Port read timed out."
        End Try

    End Function

    Private Sub BtClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtClear.Click
        RichTextBox1.Text = ""
    End Sub

End Class

Posting your question twice doesn't make it more fit for the Arduino community. Flagging it as duplicate AND off-topic.

Looks like you are using a timer to regularly read the data from the serial port... I think you'd be better using the DataReceived() event of the SerialPort class.
The other thing is that you are just reading whatever data is in the buffer (with ReadExisting) if all that is in the buffer is 2 or 3 characters (not a full line) then your Parse_receivedata() will not be able to split it based on ,
You want to keep appending the received data to a StringBuilder (or similar) until you hit a CR/LF and then pass it to the Parse_receivedata() function:
Psuedo code would be something like:
// class scoped variable
rxData = ""

...
// inside the DataReceived() event
rxData += SerialPort1.ReadExisting()
If (rxData.Contains(Environment.Newline)) Then
  lines = rxData.Split(Environment.NewLine)
  toParse = lines[0]
  rxData = lines[1]
  ParseRxData(toParse)
End If


text:
Accelerometer sample code
Just to illustrate my work here, I found a tutorial on how to code an accelerometer, I wanted to understand how does it work, literally get how it works, and not simply using the code without understanding it.
In the beginning of the program,there's a char variable declared as :
char values[10];
then later on the code, there was couple lines of getting the information stored in this variable, I'll give this as as example :
x = ((int)values[1]<<8)|(int)values[0];
we want X to receive values[0] and values[1] , that's what that line does up there.
My question is : can someone explain to me how does that line work, and why can't we simply write it as x = ((int)values[1])|(int)values[0]; ?

char values[10] is actually declaring an array of 10 chars - but none of them are assigned values (presumably the values get set when reading data from the sensor). Those array values are accessed using values[0] ..to.. values[9].  So when it uses (int)values[1] it is referring to the second char in the array (and casting it to an int).

To understand this you have to start thinking in binary.
The | operator is "Perform a binary OR on these two values".
The <<8 is "Shift this value 8 bits to the left".
If you have two 8-bit values, say (in hex) 0x37 and 0x42, and you OR them together you get:
0x37 = 00110111
0x42 = 01000010
--------------- |
0x77 = 01110111

In each column where there is a 1 in either value you get a 1 in the result.
Now if you shift the first number 8 bits to the left, you end up with:
0x3700 = 0011011100000000
0x0042 =         01000010
------------------------- |
0x3742 = 0011011101000010

You do this when a 16-bit value has been split into two 8-bit values and you want to join them back together again into the original 16-bit value.

up in the beginning of the program, there's a char variable declared
  as: char values[10];

This is not a “char variable”, it's an “array of 10 chars”.

((int)values[1]<<8)|(int)values[0]

Majenko's answer perfectly explains the intent of the author of the
tutorial, but that is not necessarily what the code actually does. As
it stands, this piece of code is buggy. Or, to say the least, it has a
serious portability problem: it will probably work fine on ARM-based
boards, but it will fail on AVR-based boards, and on x86.
The reason is that, in C and C++, the type char can be either signed
or unsigned, depending on the platform. On most platforms, including
AVR, it is signed. This implies that, when a char is converted to
int, it undergoes sign extension instead of being just zero
padded. To put it graphically, let's assume the sign bit (most
significant bit) of values[0] is s, then:
values[0]      =         sxxxxxxx
(int)values[0] = sssssssssxxxxxxx

Here I am assuming an AVR (16-bit ints). If the sign bit happens to be
zero, this will work as intended. This is the case in Majenko's example.
But if we replace 0x42 with 0xa2, we will have:
values[1]         =   0x37 =         00110111
(int)values[1]    = 0x0037 = 0000000000110111
(int)values[1]<<8 = 0x3700 = 0011011100000000
values[0]         =   0xa2 =         10100010
(int)values[0]    = 0xffa2 = 1111111110100010

Then, the bitwise OR gives
0x3700 = 0011011100000000
0xffa2 = 1111111110100010
------------------------- |
0xffa2 = 1111111110100010

and the data in values[1] is lost.
Conclusion: values should be declared as an array of unsigned
chars, as this will enforce zero-padding instead of sign extension.
Always use unsigned types when doing bit manipulations. And you probably
should find a better tutorial to learn this kind of stuff.


text:
433M modules w. soldered 34.6cm antenna, first test
I'm doing a first tx/rx on a pair of modules, and some hams have alluded that they 'autoadjust' - since I've soldered halfwave antennas onto the modules, what's the optimal range for first tests? And will I benefit from 1/2 or 1/4 wave radials? I was thinking about 4-6 spokes from a bicycle wheel. Also, what library would be best for RC control of a medium power pump - I'm pretty sure it's going to induce noise. How far away from the pump should I position the rx module? Thanks in advance.

I think the antenna should be slightly shorter as the module already has a very small antenna/coil on the  pcb. Just create a sketch that light an led if it successfully received data. Then keep moving further away till you can just barely receive data.  Then try clipping a (few) millimeters or the antenna and see if you can move further away. PS what specific model do you have?

Good idea, though I will start at ~25m and decrease distance. I trust the deep ham-fu. How much should I decrease it by? And what material would you use to make the antenna (solid core copper wire) completely straight? (and thanks )

@Gerben It's a noname module. They're all pretty similar, will use 5V for tx, and 3V3 for rx module. Tx works ok, will try it at 25m first.

Straight wire antennas are the easiest to make. Just power it by a battery, and start walking. They're all pretty similar, that's not really useful.

An english description here: https://arduinotech.dk/shop/rf-data-modul-433mhz/

I just read 3V3 is the optimal voltage for both tx and rx - bogus?

For the TX, the higher the voltage the greater the output power, and thus range (in most cases).


text:
Need help modelling and coding a feedback scenario

Above illustration is the basic setup for the question. The scenario will be the following:

A potentiometer(providing 0 to 5V) is an analog input to A0. This
  potentiometer voltage is converted to PWM(pin9) which controls a fan M1. Which
  means the human controls directly the M1 fan speed.
This directly speed-controlled M1 fan creates air pressure on a sensor
  Sen1.
On the other hand I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2
  should output the same voltage as Sen1. Which means eventually voltage
  at A1 analog input should be equal to A2. So one can achieve same air pressures at Sen1 and Sen2.

I'm not experienced in PID or other type of controls. I would be glad if someone can help me to relate parameters and code this scenario.

You may find Robotics Stackexchange useful for questions like this.

If you want, I can move this to the Robotics Stack Exchange. Just say if you do.

Well, (very) simply you could slowly increase/decrease the PWM value driving M2 until the voltage at A1 equals that of A2. If you make the time between adjustments long enough you should not get any (significant) oscillations.
However, more likely you want to get to the correct M2 PWM value quickly and for that you need a Proportional, integral, Differential (PID) control algorithm. Explaining this in detail is outside the scope of a S.E. answer, but in summary:
You have a value that signifies the current state of the system - which will be the A2 reading.
You also have a value that states where you want to get to - which will be the A1 reading.
You also have a control value - which will be the PWM value of M2
The Proportial part looks at how far away the A2 reading is from the A1 reading.
The  Integral part looks at how quickly we (the A2 reading) are moving towards (or away from) the desired value (the A1 reading). The Differential part looks at how long we have been away from the desired value.
Each of these (PID) parts (with tuning values that you set) contributes towards determining a new value for PWM at M2 and this iterates around with new values getting the current state closer and closer to the desired value.
There are lots of Arduino PID examples around. I'd suggest you read up on the algorithm itself and have a look at the Arduino.cc samples here.

PID loops are a good way to go for something like this, but, you don't need to implement all three parts.  I have done industrial control using just the P and I.  Start by implementing just the proportional part.
For this, you calculate the error between the input signal (Va0) and the feedback signal (Va1). This is just a subtraction Err = Va0 - Va1.
You now multiply the Err by a constant and add that to Va0 to adjust the PWM.
A bit like this pseudo code:
  k = 0.5;
  Err = Va0 - Va1;
  pwm = Va0 + (Err * k);

Then set the pwm to the new calculated value.
This gives a correction proportional to the error.
Experiment with k.  Start at 1. See how it goes.
Depending on the sensors you may have to apply some gain and/or offset to the Va1 reading in order to make it so that when the motor is at the correct speed, the calculated Va1 reading reads the same as the Va0 input.  For example, say the output range of the sensor is 0V to 2.5V, you will need to multiply by 2 before calculating the Err.
The P part of PID can give acceptable results.  The next stage would be to implement an I part. Do the P and see whether the I is needed.

I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2 should output the same voltage as Sen1.

simple:
  adc_sens1 = readadc(SENS1_PIN); //read adc on sense 1 pin
  adc_sens2 = readadc(SENS2_PIN); //read adc on sense 2 pin
  if (adc_sens2>adc_sens1 + SENS_DELTA) pwm_set(M2_PIN, --dc_ms); //if sens2 value too high, slow down m2's duty cycle -> positive correlatin assumed
  if (adc_sens2<adc_sens1 - SENS_DELTA) pwm_set(M2_PIN, ++dc_ms); //otherwise, increment duty cycle

No error check, no boundary check, ..... but the basic idea is the same.

authors: Вадим Дашкевич


text:
Stepper motor shield compatibilty question
I recently bought Adafruit's motor shield v2 only to find out it can only support upto 12v.
So I'm on the look out for another shield & found this one
Arduino Dual L6470 Stepper Motor Shield
I have an Arduino Mega & the documentation says it is fully compatible with the UNO.
Will there an issue using this shield with a Mega? Or if anyone else can point me at a decent stepper controller?

That is an SPI based device, and it doesn't use the (now considered standard) 6-pin ICSP header for SPI.
Therefore it will only directly work on boards that have the SPI pins available on pins 10-13 of the digital headers.
To use it with other boards you will need to manually route the SPI pins to the right places using wires.

Just so you know, the L6470 is a pretty sophisticated and high-performance driver with lots of options to tweak, but it is a voltage-mode driver that requires some tuning for best results (otherwise, expect to generate some heat). There is a separate ST microelectronics application note, not mentioned in the L6470 datasheet, that describes some tuning guidelines - but it's written for an engineering audience.
There is also a SparkFun version of the L6470 out there.


text:
Communicate with ESP8266 RX/TX
I just managed to get a unofficial Arduino WiFi shield to work. But the ESP is flashed on its own now - providing only information to the USB->TTL converter and therefore the output goes straight to the Serial Monitor of the Arduino IDE.
Since the ESP is flashed and should be running now - I should be able to disconnected the USB->TTL converter and attach the Arduino RX/TX to the ESP TX/RX right?
Then I should receive Serial Data and should be able to process these in my Arduino Sketch right?
So what do I need to do now? Should I start trying a Serial read from the arduino with the baud rate specified by the ESP Flash (11520)? Or do I have to consider something else as well?

Your analysis is indeed correct, you can communicate between Arduino and ESP using the serial protocol.
Electrically speaking you must ensure the RX and TX pins are crossed:
Arduino RX goes into ESP TX
Arduino TX goes into ESP RX
Also, the two devices MUST have a common ground, the GND pins of the Arduino and the ESP8266 must be tied together.
You don't need level shifters because, even if the ESP8266 runs at 3.3V, its IO ports are 5V tolerant.
Also, as you already pointed out, the two devices must set the same speed (aka BAUD rate) in order to comprehend each other.
In case you decide to transmit binary data please also consider the two devices use a different architecture: Arduino is 8bit, ESP8266 is 32bit, meaning they have different word size (the minimum allocation unit size).
I had to face the word size issue when I first tried to exchange a struct between an Arduino and a RaspberryPI (also 32bit)...

Are you sure the input pins are 5V tolerant? They seemed to be but it was yet confirmed by Espressive.

If you aren't using level shifters will the Arduino be able to read the 3.3v signals transmitted by the ESP8266?

The GPIO pins are all 5V tolerant as stated from multiple sources, even if the Expressf datasheet doesn't state it in a clear way and actually provides contraddictory information.
This DOES NOT MEAN you can power an ESP8266 with 5V and ALSO DOES NOT MEAN you can source or sink any significat current at 5V, but you CAN exchange signals at 5V, provided the 5V side is capable to detect a 3.3V HIGH signal, as the Arduino does.

@Matt yes, Arduino operating at 5V is capable to detect a 3.3V HIGH, the threshold voltages are 3V on the high side and 1.5V on the low side.


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

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


text:
Crosspack instead of Arduino IDE, how to include Arduino.h
I quit using the Arduino IDE, instead I am now using Crosspack via the command line on my Mac.
It is working totally fine. I use "make" to compile it, "make flash" to upload it to the Arduino.
This is the Makefile I got right now:
# Name: Makefile
# Author: <insert your name here>
# Copyright: <insert your copyright message here>
# License: <insert your license reference here>

# This is a prototype Makefile. Modify it according to your needs.
# You should at least check the settings for
# DEVICE ....... The AVR device you compile for
# CLOCK ........ Target AVR clock rate in Hertz
# OBJECTS ...... The object files created from your source files. This list is
#                usually the same as the list of source files with suffix ".o".
# PROGRAMMER ... Options to avrdude which define the hardware you use for
#                uploading to the AVR and the interface where this hardware
#                is connected. We recommend that you leave it undefined and
#                add settings like this to your ~/.avrduderc file:
#                   default_programmer = "stk500v2"
#                   default_serial = "avrdoper"
# FUSES ........ Parameters for avrdude to flash the fuses appropriately.

DEVICE     = atmega328p
CLOCK      = 16000000    # 16 MHz for Arduino
PROGRAMMER = #-c stk500v2 -P avrdoper <-- leave this commented since we already specified the default programmer above
FUSES      = -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efuse:w:0x05:m # arduino defaults
OBJECTS    = main.o

# ATMega8 fuse bits used above (fuse bits for other devices are different!):
# Example for 8 MHz internal oscillator
# Fuse high byte:
# 0xd9 = 1 1 0 1   1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000)
#        ^ ^ ^ ^   ^ ^ ^------ BOOTSZ0
#        | | | |   | +-------- BOOTSZ1
#        | | | |   +---------- EESAVE (set to 0 to preserve EEPROM over chip erase)
#        | | | +-------------- CKOPT (clock option, depends on oscillator type)
#        | | +---------------- SPIEN (if set to 1, serial programming is disabled)
#        | +------------------ WDTON (if set to 0, watchdog is always on)
#        +-------------------- RSTDISBL (if set to 0, RESET pin is disabled)
# Fuse low byte:
# 0x24 = 0 0 1 0   0 1 0 0
#        ^ ^ \ /   \--+--/
#        | |  |       +------- CKSEL 3..0 (8M internal RC)
#        | |  +--------------- SUT 1..0 (slowly rising power)
#        | +------------------ BODEN (if 0, brown-out detector is enabled)
#        +-------------------- BODLEVEL (if 0: 4V, if 1: 2.7V)
#
# For computing fuse byte values for other devices and options see
# the fuse bit calculator at http://www.engbedded.com/fusecalc/

# Tune the lines below only if you know what you are doing:

AVRDUDE = avrdude $(PROGRAMMER) -p $(DEVICE)
COMPILE = avr-gcc -Wall -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE)

# symbolic targets:
all:    main.hex

.c.o:
    $(COMPILE) -c $< -o $@

.S.o:
    $(COMPILE) -x assembler-with-cpp -c $< -o $@
# "-x assembler-with-cpp" should not be necessary since this is the default
# file type for the .S (with capital S) extension. However, upper case
# characters are not always preserved on Windows. To ensure WinAVR
# compatibility define the file type manually.

.c.s:
    $(COMPILE) -S $< -o $@

flash:  all
    $(AVRDUDE) -U flash:w:main.hex:i

fuse:
    $(AVRDUDE) $(FUSES)

# Xcode uses the Makefile targets "", "clean" and "install"
install: flash fuse

# if you use a bootloader, change the command below appropriately:
load: all
    bootloadHID main.hex

clean:
    rm -f main.hex main.elf $(OBJECTS)

# file targets:
main.elf: $(OBJECTS)
    $(COMPILE) -o main.elf $(OBJECTS)

main.hex: main.elf
    rm -f main.hex
    avr-objcopy -j .text -j .data -O ihex main.elf main.hex
    avr-size --format=avr --mcu=$(DEVICE) main.elf
# If you have an EEPROM section, you must also create a hex file for the
# EEPROM and add it to the "flash" target.

# Targets for code debugging and analysis:
disasm: main.elf
    avr-objdump -d main.elf

cpp:
    $(COMPILE) -E main.c

I cannot just include "Arduino.h", but I need (want) to use it anyway.
My question is how I would go about doing that? I know where Arduino.h is located, but I cannot just copy that file to the project folder because it needs other files too.
If more info is needed, please let me know.

You need to compile all the core .c, .cpp and .S files into .o files (optionally archiving them into a .a file) then link them with your main program. Your main program will then become a sketch where you use setup() and loop() instead of main() since the main.cpp file in the core has main() in it. Of course you need to include Arduino.h in your source files as well or nothing will work.
The same goes for libraries. You need to compile and link the source code with your code as well as including the header file(s) in your code (and providing the paths to them with -I... directives).

First of all; thank you for your answer. I don't know if you mean exactly the same as I do. Let me explain a little bit: I have a Crosspack project with a main.c(pp) file. In this file I want to build a project. What I want to achieve is that I can do #include "Arduino.h" at the top of the file. If this is the same as you wrote, could you maybe explain a little bit how to do this, or at least point me in the right direction? I don't know how to do this since I have no experience with linking / compilers. Thanks again.

Arduino.h doesn't need to be in you make file.  It needs to be the first line of your source files (your main.c or main.cpp files).
#include in a make file will be treated as a comment, because # means comment.

@JeroenJK Yes, that is what I mean. Using Makefiles can be a bit of a black art. You will need to create targets for .cpp.o and .S.o which call the correct compilation commands for those file types. Then you add all the .o files to your OBJECTS variable. Alternatively create a libcore.a target which uses the archiver avr-ar to create a libcore.a archive which you then link with your main.o with: -L. -lcore. Note that calling your file main.c (which compiles into main.o) is a bad idea since the core contains main.cpp which compiles into main.o as well. Conflict city...

@Matt Ah no, I mean #include at the top of the main.c file. ;) Sorry if that was not clear. @Majenko I will look into how to do what you wrote. I hope I will find out by Googling and trial and error. If not, I'll let you know. And if it succeeds I will of course accept your answer.

@JeroenJK - This is confusing.  Do you mean "How do I include Arduino.h in main.c?"  OR do you mean "My make file can't find Arduino.h, how do I tell it where to find it?"  The exact argument depends on the compiler but it is usually -I, or some compilers accept the content of the INCLUDE environment variaible.

@Matt What I want to achieve is that I can use the Arduino library (Arduino.h). It would be perfect if I could just add #include "Arduino.h" or #include "/Path/To/Arduino.h" to main.c(pp), but unfortunately that doesn't just work because Arduino.h has other imports and those imports got other imports. And if I add #include "/Path/To/Arduino.h", I get this error when running make: In file included from main.c:3:0: /Path/To/Arduino.h:249:26: fatal error: pins_arduino.h: No such file or directory  #include "pins_arduino.h"

@JeroenJK - Cool - Since its gcc use -I (upper case 9th letter of the alphabet not numeric) i.e. COMPILE = avr-gcc -Wall -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE) -I "Path/To" -I "Path/To/Some/Other" -I "Some/Where/Else/Entirely"   Does that make sense?  You should also look at Majenko's stuff too, because it looks like even when you get the includes working you will still have issues. :(

You should look at either existing makefile solutions or the arduino-builder system.

I followed your instructions @Matt, but then I had problems with a not found Arduino_pins.h. While I was searching for a solution I found PlatformIO (http://platformio.org/) which I use instead now. Thanks for thinking with me and helping me, but said IDE is going to serve me just fine.


text:
Cheap ATtiny programmer on Debian
I've recently purchased a no-brand 1€ ATtiny programmer off eBay, and with the ridiculous price obviously came no documentation nor support from the seller.

At first I thought that using it with the Arduino IDE would have been as simple as plugging and programming, but no default lib worked. My hopes definitely crumbled when I realized the device wasn't even being picked up by Debian, showing instead this in the logs:
kernel.info: [ 2758.501968] usb 6-3: new low-speed USB device number 2 using ohci-pci
kernel.err: [ 2758.641798] usb 6-3: device descriptor read/64, error -62
kernel.err: [ 2758.885515] usb 6-3: device descriptor read/64, error -62
kernel.info: [ 2759.125231] usb 6-3: new low-speed USB device number 3 using ohci-pci
kernel.err: [ 2759.265065] usb 6-3: device descriptor read/64, error -62
kernel.err: [ 2759.508779] usb 6-3: device descriptor read/64, error -62
kernel.info: [ 2759.748500] usb 6-3: new low-speed USB device number 4 using ohci-pci
kernel.err: [ 2760.156027] usb 6-3: device not accepting address 4, error -62
kernel.info: [ 2760.291871] usb 6-3: new low-speed USB device number 5 using ohci-pci
kernel.err: [ 2760.699382] usb 6-3: device not accepting address 5, error -62
kernel.err: [ 2760.699421] usb usb6-port3: unable to enumerate USB device

and with lsusb outputting this:
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 003: ID 07d1:3c0a WiFi Dongle
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 002: ID 045e:0745 Mouse/Keyboard BT Dongle
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

Reading up on the subject seemed to confirm that it was something I shouldn't have bought, and the closest I've got to a better understanding was with this question (link) which I can't comment.
So building up on the answer there, can anyone please explain a bit more in detail what for and where micronucleus would be needed?
Alternatively, is it possible to go with something as easy as installing the drivers and plugging it into the Arduino IDE?

I'm in the same boat, or will be soon when the bits arrive from China.   The 1€ price tag is hard to resist!

I got a couple of Chinese USBASP programmers from eBay at 2.78 € each, with free shipping. They work great for programming ATtinies, and they are supported by avrdude (the programming tool used by the Arduino IDE). But you have to connect 6 wires...

It would be handy if you specified which specific item you bought. Most likely it's just the ATTiny breakout board that has the ISP-header brought out, and has a micro usb port, that is only used for power. I'd get a UsbASP programmer. They work perfectly for me.

If the board has a real ISP header, that would actually be a nice addition to the usbasp. No need to use the board's USB connector though, as the chip will be powered by the usbasp through the ISP.

This is unanswerable without a picture of the other side of the board.  Without that, and with no documentation, there's little reason to believe there is any IC on this capable of functioning as a USB device.  The provided failure message are merely a result of having a pullup resistor on a USB data line, without necessarily meaning any USB interface engine connected.  As this is in unanswerable form it should be closed

Looking at this item on ebay I am really confused as to how this product was meant to be used. As far as I can see there is no other MCU onboard. Couldn't find anyone actually using these on google either...

As this is in unanswerable form it should be closed - yes, Chris, but that's what comments are for. Teasing out more information about the question. You could have merely asked for a photo of the other side of the board.

Micronucleus is a bootloader - in the same way that Optiboot is a bootloader used on the Uno. It provides the USB connection to program the chip.
Without it you can't do anything at all with that, since the USB port just plugs direct into the ATTiny chip. With no software on the chip the USB port doesn't do anything.  It's kind of a catch-22 situation - you need software on the chip in order to put software on the chip.
In essence Micronucleus turns the ATTiny into a kind of Mini Leonardo.
You need to first put Micronucleus on the chip (which you can do with an Arduino as an ICSP programmer) and then once that is installed you should be able to start using that little board with the chip to program it.
Since you're on a decent operating system there's no need for "drivers".

Crystal clear, thank you! So basically the socket on the board is not meant for the "end-product" MCU, but rather for the programming MCU... If that's the case, that sucks. Would some other board (Sparkfun's i.e.) instead provide a direct usb2tiny interface? EDIT: I will of course make do with what I have now, but the whole point was to remove all the wiring from the process and in this very moment I simply shrunk the Mega I was formerly using to program the tinys...

You want a board that has a built-in hardware programmer. It will have a second MCU on the board to do the programming. If there is no second MCU on the board then all you have is a fancy socket like this one.

It isn't clear to me what you need to do- both for specific chip and your programming needs.
You can easily program an ATTiny with just an arduino and a breadboard.  A breakout board and a socket are fun, you could also build or buy a permanent shield for this.
With that breakout board (you could just use a breadboard, too) and an Arduino, you can program your ATTiny from the ArduinoIDE or from avrdude (if for example you have just a .hex file from an Instructable.  You will find that the Arduino IDE doesn't support uploading .hex files directly, but since the IDE calls on avrdude for all the actual work- you can invoke avrdude from the command line to upload your .hex file to the chip).
If you mention which ATTiny you need to program, I've missed it.
Overall process is:
From the Arduino IDE, add these core libraries from: Tools/ Boards/ Boards manager
github.com/damellis/attiny
This will get you:
ATtiny 25 (8 pin)
ATtiny 45 (8 pin)
ATtiny 85 (8 pin)
ATtiny 24 (14 pin)
ATtiny 44 (14 pin)
ATtiny 84 (14 pin)

Add:
github.com/MCUdude/MicroCore  (this will need manual install, instructions are provided)
and
sourceforge.net/projects/ard-core13/files/latest/download  (I forget if this can be added from the IDE or needs manual install).
if you need ATtiny13 support.  Each has some advantages the other does not.
You will want to use IDE 1.6.x.
Wire up your breakout board (or breadboard) to your Arduino appropriately for the ATTiny you are using.  For example, according to the wiring diagram here for the ATTiny85:
highlowtech.org/?p=1695
And from there you should be able to program your ATTiny so that it can run independently from your Arduino.
If you need to upload a .hex file to your ATTiny check the examples here:
arduinodiy.wordpress.com/2012/09/11/programming-hex-code-on-an-attiny85-with-the-arduino/
You can do that by using the Arduino as an ISP and then uploading the .hex file to the ATTiny using AVRdude.  You'll have to tweak the avrdude command line params a little specific to your situation.
I've just done programming of ATTiny13 using an Arduino Uno, a breadboard, and 6 jumper wires just fine.  Both uploading sketches I made in the Arduino IDE as well as using compiled .hex files that were part of an Instructables.com project I was building worked fine.
If you need to upload a program to a board and then use that board to mass-produce many identically programmed ATTiny without using an Arduino, adafruit as a solution, as does shop.myavr.com.  I can't justify the expense but they look really neat.  Using the Arduino as ISP for this of course works as well.
htlinux has a shield for Arduino's that is really inexpensive and comes with sockets for many Atmel pinouts:
www.htlinux.com/product/attiny-isp-shield/
I ordered one and it isn't here yet, it took a month to get the shipping notice, but it looks like a convenient all-in-one solution.  It still needs an Arduino to act as programmer.  It would meet your requirement of "removing all wiring" if you are find with a shield.
You could easily build your own shield with a proto board, too.
http://www.instructables.com/id/ATtiny-Programming-Shield-for-Arduino-1/?ALLSTEPS
I hope this helps!  I spent a while figuring out all this stuff, hopefully having many items in one answers helps the next person looking to program ATTiny with Arduino.  I'm working from OS X, it should be even easier from Windows or Linux.

Thanks for all the detailed info, I'm sure they will come in handy to many, but I'm actually past that point. I can successfully program tinys (45/85) with the setup you described. With the board as from topic I was instead hoping to remove all the extras and have a single socket 'plug and program' solution for this.

Sounds good.  So you want a stand-alone programmer?
As Majenko indicates, you can build one or just buy one.  I think you are looking for something like: learn.adafruit.com/mass-avr-isp-programmer

Judging by the picture it's just a board.
If it is anything like this link on eBay (the first hit for "attiny programmer board") then this is the description:

Development board supporting chip:ATtiny13A / ATtiny25 / ATtiny45 / ATtiny85 etc

It supports the named chips, it doesn't have them on it.
I presume you are supposed to do a few things with it:

Purchase an ATtiny85 (or similar) chip
Install it on the board
Solder in an ICSP header onto the 8 pins on the right
Program the Micronucleus bootloader using a suitable other piece of hardware (like a ICSP programmer)
Then use the board as a ATtiny development board.

It's not responding because there is no chip there (unless you can see one on the other side). That's why it's cheap. You are buying a board, not a microcontroller on a board.
This other link on eBay for a slightly different board (for the same price) shows that the other side does not have a processor on it.


text:
How to read Ultrasonic sensor value to use and drive servo motors
I would like to know how i can use my ultrasonic value in an if else statement, so i can use the value that the servo motors stop running and go in another direction when the ultrasonic sensor gets close to an object.
/*
  Digital pin 2 is connected to a switch
  Digital pin 3 is connected to a switch
  Digital pin 7 is connected to the echo port of the ultrasonic sensor
  Digital pin 8 is connected to the trig port of the ultrasonic sensor
  Digital pin 9 is connected to a servo
  Digital pin 10 is connected to a servo
  Digital pin 13 is connected to a LED

 */

#include <Servo.h> // include a special file that is needed for servo motors, do this only once

Servo motor1; // create a servo object for each motor
Servo motor2;

int echo = 7; //declare echo from ultrasonic sensor
unsigned long duration;
void setup() {
  // initialize the LED pin as an output:
  pinMode(13, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(2, INPUT);
    // switch 2 initialize
    pinMode(3, INPUT);
  // initialize the servo on pin 9
  motor1.attach(9);
  // motor 2 initialize
  motor2.attach(10);
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
    //echo pin of ultrasonic sensor
    pinMode(echo, INPUT);
    //trig pin of ultrasonic sensor
    pinMode(8, OUTPUT);

}

void loop() {
      // the trigger pin sends a pulse
       digitalWrite(8, LOW);
       delayMicroseconds(2);
       digitalWrite(8, HIGH);
       delayMicroseconds(10);
       digitalWrite(8, LOW);
       duration=pulseIn(echo, HIGH);
      // the echo pin measures how long it took for that pulse to come back
       Serial.println(duration);
      // delay in between reads for stability
       delay(50);
       duration=pulseIn(echo, HIGH);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if(duration <=400) {
    // turn LED on:
    digitalWrite(13, HIGH);
    // turn the motors off for 2 seconds
    motor1.write(90);
    motor2.write(90);
    delay(2000);
    //turn motor 1 on for 2 seconds to make a turn
    motor1.write(180);
    delay(2000);
  } else {
    digitalWrite(13, LOW);
    //motors run when vehicle is not near objects
    motor1.write(0);
    motor2.write(180);
  }
}

So what is the problem so far? Does the code not work? Please be more specific.

The sensor shows me all the values in the console but i dont know how i can use those values in an if else statement so that my servo motors would stop and turn around when the sensor gets close to an object. The code works when i use a switch in the if else, but now i want to use the ultrasonic sensor to be the switch in stopping the servo motors.

First, I would make sure I have continuous servo motors that can rotate 360 degrees. Your servos will just rotate to the degree you entered if they are not continuous. Additionally, it would be more helpful if you named your pins. For example:
int echo = 7;
void setup(){
    pinMode(echo, INPUT);
}

This will help us read the code better.
I also see that you have "pulseIn" in your if statement. You must save the value to a variable with the data type of unsigned long.
//before the setup
unsigned long duration;

//keep your setup as it is

void loop(){
   digitalWrite(8, LOW);
   delayMicroseconds(2);
   digitalWrite(8, HIGH);
   delayMicroseconds(10);
   digitalWrite(8, LOW);

   duration=pulseIn(echo, HIGH);

   if(duration<=400){//check for the value
       // turn LED on:
        digitalWrite(13, HIGH);
        // turn the motors off for 2 seconds
        motor1.write(90);
        motor2.write(90);
        delay(2000);
        //turn motor 1 on for 2 seconds to make a turn
        motor1.write(180);
        delay(2000);
   }else{
        digitalWrite(13, LOW);
        //motors run when vehicle is not near objects
         motor1.write(0);
         motor2.write(180);
       }
   }

Overall: check your servos and save the value of pulseIn to a variable. You might also want to convert to centimeters by dividing duration by 58.2.

the led goes on now when i put my hand in front of the sensor and off when i get my hand away, but the motors do not continue running. When before they would just go on forever

@S.Mateijsen What power source are you using? So the LED goes off, motor 1 stops and motor 2 is already stopped? And they just stay at rest?

im using 4 AA batteries and my laptop as power, the led stays on untill i remove my hand(thats also whats supposed to happen so the led works) the motors just rotate a bit around and then stop at there angles

turned out my batteries where almost empty :< But now the motors both go on at the start. after a couple seconds the led goes on and he makes a turn. but he keeps making turns now and doesnt go right ahead anymore so he keeps looping the if duration <=100 statement and doesnt come to the else part.

First check your batteries. Maybe they are dead. It happened to me yesterday. A servo was working and then in the middle it always shut off. Can you confirm that they are continuous servos? Post a picture of them or a link where you got them. The phrase "at their angles" confuses me. Do the servos stop at 0 and 180 degrees? If yes, then they are not continuous.

If you are using your computer for power, the chances are that your computer is in the way of the sensor. It might always read low values and trigger the if statement. Try using a 9V battery to power the arduino and out the robot on the floor in an open space without obstructing the sensor.

It would also be helpful for you to post the updated draft of the code you are using now.

The servos are continuous servos they keep running now(problem was the batteries) I also tried to put it in on open area where nothing would be in front of the sensor but it keeps looping the "stopping and making a circle part" instead of going straight ahead. and i updated the main post with my current code.

Try reading the Serial Monitor and seeing if the duration values actually change. You might have a defective sensor. Also, does the LED turn off in a wide area or no?

The sensor puts the values out like every 2 seconds in the console with a value of 7000 so it shouldnt be doing the <=100 statement at all. The LED also stays on in an open area.

What if you put your hand in front of the sensor? Still 7000? Also do Serial.println(duration) not Serial.println(pulseIn(7)). The second option will cause the duration to become 0 after printing because the signal will have already been collecting and pulseIn will return 0 the second time.

i updated the main post again, the sensor gives me the values now and when i put my hand infront of it it becomes like 200 and when i dont the values is around 17000.

That is not what I meant with Serial. First save pulseIn to duration. Only then print it out and then do the if statement. If you called pulseIn twice, the second time will give you a 0 and the first time will give you the right value.

Cheers man! that was the problem it works perfectly now :D


text:
RF24 - Split data in payloads at sender and then rebuild on receiving end
I'm trying to send some data using nRF24L01+ transceivers, but I need to use 8 byte payloads for reliability. The data I'm sending is much bigger than that, so I need to split it into 8 byte packets and then reassembly on the receiving end. I wrote the following code to test it, but to no success.

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
RF24 radio(9,10);
const byte pipes[][7] = { "master", "slaves" };
#define PayLoad 8

void setup() {
  Serial.begin(9600);
  while(!Serial){}
  radio.begin();
  radio.setRetries(15,15);
  radio.setPayloadSize(PayLoad);
  radio.setPALevel(RF24_PA_LOW);
  radio.setDataRate(RF24_1MBPS);
  radio.setCRCLength(RF24_CRC_16);
  delay(100);
  radio.openWritingPipe(pipes[0]);
  radio.openReadingPipe(1,pipes[1]);
  radio.startListening();
  radio.printDetails(); //RF Debug
  delay(1000);
  //sendRF("Payload splitting test. 1234567890");
}

void loop() {
  if (radio.available()){
    fromRF();
  }
  if (Serial.available()){
    String dataIn = Serial.readString();
    sendRF(dataIn);
  }
}

void fromRF(){
  byte numPkgs;
  radio.read(&numPkgs,1);
  Serial.println(numPkgs);
  char rcvBuffer[numPkgs*PayLoad];
  for (byte pkg=1; pkg<=numPkgs; pkg++){
    char payloadBuff[PayLoad];
    radio.read(&payloadBuff,PayLoad);
    for (int charpos=0; charpos<PayLoad; charpos++){
      rcvBuffer[((pkg-1)*PayLoad)+charpos] = payloadBuff[charpos];
    }
    if (pkg < numPkgs){
      int timeout = 0;
      while(!radio.available() && timeout<100){
        timeout++;
        delay(1);
      }
      if (timeout >= 100){
        Serial.println("Package timed out.");
        return;
      }
    }
  }
  String msgRcvd(rcvBuffer);
  Serial.println(msgRcvd);
}

void sendRF(String msg){
  byte msgLen = msg.length();
  Serial.println(msg);
  Serial.println(msgLen);
  char msgBuff[msgLen];
  msg.toCharArray(msgBuff,msgLen);
  radio.stopListening();
  byte numIters = msgLen/PayLoad;
  if (msgLen%PayLoad > 0)
    numIters++;
  radio.write(&numIters, 1);
  Serial.println(numIters);
  char payloadBuff[PayLoad];
  for (byte iter = 1; iter <= numIters; iter++){
    for (byte i=0; i<=PayLoad; i++){
      payloadBuff[i] = (char)0;
    }
    byte initchar = (iter-1)*PayLoad;
    byte lastchar = (iter*PayLoad)-1;
    if (lastchar > msgLen)
      lastchar = msgLen;
    byte counter = 0;
    for (byte nextchar = initchar; nextchar <= lastchar; nextchar++){
      payloadBuff[counter] = msgBuff[nextchar];
      counter++;
    }
    radio.write(&payloadBuff, PayLoad);
    Serial.println(payloadBuff);
    delay(50);
  }
  radio.startListening();
  delay(100);
}

This code is intended to work for both master and slave, except that writing and reading pipes change places.
My splitting is working fine (as shown by the serial monitor), but it looks like I'm not able to receive it well. Any help would be greatly appreciated!!
EDIT:
I've got it working! (kind of). It still lacks managing lost packages, but it's working quite fine.
void fromRF(){
  byte numPkgs;
  radio.read(&numPkgs,1);
  //Serial.println(numPkgs);
  String rcvdStr = "";
  for (byte pkg=1; pkg<=numPkgs; pkg++){
    char rcvBuffer[PayLoad+1];
    delay(100);
    radio.read(&rcvBuffer,PayLoad);
    rcvBuffer[PayLoad] = '\0';
    String strBuffer(rcvBuffer);
    rcvdStr += strBuffer;
  }
  Serial.println(rcvdStr);
  //sendRF(rcvdStr);
}

void sendRF(String msg){
  byte msgLen = msg.length();
  Serial.println(msg);
  //Serial.println(msgLen);
  char msgBuff[msgLen];
  msg.toCharArray(msgBuff,msgLen);
  radio.stopListening();
  byte numIters = msgLen/PayLoad;
  if (msgLen%PayLoad > 0)
    numIters++;
  radio.write(&numIters, 1);
  Serial.println(numIters);
  char payloadBuff[PayLoad];
  for (byte iter = 1; iter <= numIters; iter++){
    for (byte i=0; i<=PayLoad; i++){
      payloadBuff[i] = (char)0;
    }
    byte initchar = (iter-1)*PayLoad;
    byte lastchar = (iter*PayLoad)-1;
    if (lastchar > msgLen)
      lastchar = msgLen;
    byte counter = 0;
    for (byte nextchar = initchar; nextchar <= lastchar; nextchar++){
      payloadBuff[counter] = msgBuff[nextchar];
      counter++;
    }
    radio.write(&payloadBuff, PayLoad);
    Serial.println(payloadBuff);
    delay(50);
  }
  radio.startListening();
  delay(100);
}

Gotta give a look at RF24Mesh.

What do you mean by not able to receive it "well"?

I'm not that into C but in the case of char rcvBuffer[numPkgs*PayLoad];, I'm not entirely sure that you can create an array with a dynamic size. Also, you method relies on never missing a single packet, and not turning on the receiver in the middle of a transmission of packets.

It would be maybe a good idea to use an existing solution like RF24Mesh that does it for you?

@Majenko It was not receiving the complete payload, only the first byte. It's fixed now, but I'd like to make improvements. I haven't found anything related, so I guess this could be helpful for others.

@Gerben Actually at the moment of creating the array, numPkgs*PayLoad acts as a constant. Anyway, I'm doing it differently now. And nope, still no lost package management. :S

@Avamander Gotta give it a try. ;)

@Gerben You only need to provide a constant as an array size when the array is global (or maybe static). When it's local it gets allocated on the stack dynamically and the size can be given at runtime, not compile time. Only when it needs to be allocated in the .bss or .data sections does the compiler need to know the size beforehand.

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


text:
Advanced ADC setup on Due (SAM3X8E) to increase precision
I want to make some precise measurements with Arduino Due. Although I'm using very good external voltage reference (LTC6655) measured data is still jumping around, especially significant when I'm trying to measure low voltages (0.1-0.05V). Can I improve ADC accuracy by changing it's settings?
The default Arduino Due ADC settings are:
// Initialize Analog Controller
pmc_enable_periph_clk(ID_ADC);
adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1);
adc_configure_trigger(ADC, ADC_TRIG_SW, 0); // Disable hardware trigger.
adc_disable_interrupt(ADC, 0xFFFFFFFF); // Disable all ADC interrupts.
adc_disable_all_channel(ADC);

So, with adc_init we can configure frequency and startup time. And with adc_configure_timing we configure tracking time, settling time and transfer time. But how to select those values? Does increasing of that times improves precision?
Useful links:
Datasheet - ADC description starts on page 1317.
Atmel Software Framework - see adc.h and adc.c.

What are you measuring? Is it possible that it's intrinsically variable (jumping around)?

@Squats, I'm measuring battery voltage.

How much your measurement fluctuate? 0.1V? 0.01V?

@LookAlterno, It's an old question and I don't remember exactly. Something about 10-20%.

Generally speaking the input BandWidth of the analog signal is a major cause of noise in a ADC circuit as well as improper ground and reference generation and layout techniques.  Be very careful that ALL of the analog paths do not have any digital current return paths. Remember that at 12 bit for a 1.25V reference an LSB is ~300uV. I have not ever measured the SNR of the SAM ADC but I doubt that it is the specified ~60db (i.e. 10bit) unless absolute care is taken during the layout/routing.
Recommend:
1) Limit input BW to the correct channel ground. (well below Nyquist BW if possible to avoid alliasing)
2) Oversample if possible.
3) Insure low digital I/O of peripherals during sample period.

Default resolution is 10b because of backward compatibility, so you can start with setting analogReadResolution(12); as stated on Arduino analogReadResolution Refference page.
If it's still not enough you can use GAIN setting for used ADC channel. For single ended input GAIN can be set up to 4. But it means you can mesaure voltages up to 1/4 of Uref

I think increasing the resolution will not improve actual precision. It just will add more trashy bits which has nothing common with real measured value. I decided to use external ADC.

@kelin - the degree to which increasing resolution increases precision depends a lot on how clean the analog circuit design is, of the board and the source, and even on how much "is going on" digitally at the time of reading - sophisticated designs often shut a lot of the chip down while taking sensitive readings.  Also, even "noisy" bits can yield precision if evaluated statistically, for example putting many readings into a filter.

measured data is still jumping around

it will always jump around -> that's why adc modules are such a great random number generators (using its lsb). jumping around 8 - 9 lsb isn't that rare. anything beyond that should be investigated.
a few things to watch for:

use a good reference;

allow sufficient time;
pay attention to layout;
make sure that the source impedance isn't too great;
put a signal conditioning circuit on the input. a 1k/.1uf filter can do wonders;
pick the right oscillator for the adc module - see some c8051f350 code for example;
write the right code;
oversampling.

Thanks for broad answer, but my question is about ADC setup on SAM3X8E.

I've found http://sim.okawa-denshi.jp/en/CRlowkeisan.htm to be useful for designing a low pass filter but make sure you're not sampling more frequently than the design of the filter.