text:
powering the arduino uno
I need to power an arduino uno with a battery but for a very long period of time. And I read a lot of thing about this. Some say do not use a 9V battery with a regulator some other say that it is the best way. SO I am really confused and I need to know what's the best solution for this (taking into consideration the fact that I need my board to last a week at least, if it is possible?)
Thanks!

The Arduino Uno is not really designed for that. Simply keeping the power indicator LED, regulators and extra circuits on for a week will require in the order of 1500-2000 mAh (10*24*7=1680mAh). That is without any application at all on the MCU.
Now it is possible to modify the board and reduce this extra power requirements to less than 1 mA and as low as 0.1 mA. Or even better buy a Pro Mini clone and cut the wiring to the LED and regulator, and power with a 3.7 V/1500mAh battery directly.
Here is a great reference on the subject.
Cheers!

As I've said this below too. Pro Mini 3.3V is already really stripped of unnecessary components and really the best for battery powered things.

I didn't quite understand why it's 10247. What does the 10 represent?

No problem! 10 mA x 24 hours x 7 days. 10 mA is lower boundary of power consumption for all the extra circuits on the Uno board. It is actually higher but this is an easy way to get a rough estimate.

You will definitely not get a week out of a 9V cell - they have very small capacities (and are expensive relative to other types of cell).
Your Uno already has a regulator in it and this regulator wastes a certain amount of energy converting between different voltages. I'm certainly no expert, but from what I've gleaned over the last month or so of owning an Uno, powering it from batteries can be tricky if you want to do it for long periods of time.
It's probably worth trying a 12v sealed lead acid battery - these have capacities measured in Amp Hours, rather than milli-amp hours like most other types of cell. The built-in voltage regulator in the Uno is good up to 20V, just be sure to connect to the barrel jack on the board.
Of course, without knowing more about what you're actually trying to power along with the Uno, it's difficult to make proper recommendations.
I would also suggest looking at building your system with a naked MCU and a voltage regulator tailored to your application. That way you can throw away a lot of the stuff that uses power on the board that you don't need. (Start with a Breadboarduino and take stuff out from there!)

Instead a higher capacity battery. I think using a Pro Mini 3.3V would be a better idea.

Three main things to do to decrease the Uno's power consumption:

Remove the power LED (you can Google for instructions if you're not sure how to do it)
Bypass the voltage regulator by providing ~5V of power to the 5V pin. You can arrange three sets of AA batteries in series to get about 4.5V which should be fine except that the crystal may run at a different speed (and you may get incorrect results from the millis() function for example). Obviously if that is unacceptable then you will need to provide a constant 5V voltage either by using the Arduino's regulator (which is quite inefficient) or buying a more efficient third-party regulator. The voltage provided by the batteries will vary somewhat, and over time the batteries will start putting out less voltage and eventually your Arduino may start to behave erratically or not at all. If reliability is of high importance then this may not be acceptable to you.
Use sleep modes to the greatest extent possible (see http://playground.arduino.cc/Learning/ArduinoSleepCode). If your Arduino only needs to wake up for a few seconds every hour, you can make a few batteries go a very long way. Note that if you're using a regulator, it will still draw significant power even while the Arduino is sleeping.

Bonus tip: buy a micro instead, or build your own board. (Avamander suggests a Pro Mini 3.3V in the comments below, he's probably right, I don't know much about that board)

Pro Mini 3.3V is the best idea for battery powered things.


text:
Arduino Mega 2560 ADC sampling instant and other timings
Hello Everyone (I might be making some mistake in asking this "question", bear with me as I am new to these sites... I honestly think this is the best way to frame my inquiry because it's rather elaborate)
I'd like some help in understanding the "timings" of Arduino MEGA 2560's ADC module, especially with respect to the command analogRead.
I read ATmega2560 microcontroller Datasheet
Let's assume, for now, that our conversions are normal ones ( the other type being a "first" conversion, which takes 25 ADC clock cycles instead of 13, due to the time required for the initialization of analog components )
From what I understood, on a normal single conversion, the sample and hold happens after 1.5 ADC clock cycles from the start of the conversion.
Let's say that I set the prescaler to 32 with the following commands:
const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0);
const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

ADCSRA &= ~PS_128;  // remove bits set by Arduino library
ADCSRA |= PS_32;  // set our own prescaler to 32

hence 16MHz / 32 = 500 kHz should be the new ADC clock frequency
( or 2 microseconds ADC clock period )
since a normal single conversion takes 13 ADC cycles, the entire conversion should take about 26 microseconds
If I'm not mistaken, (2 microseconds * 1,5)  = 3 microseconds after the ADC conversion starts, my analog pin value is set on hold, right?
I measured the elapsed time using the micros() function and, like I'd expect,
I found out that there's a little overhead introduced with analogRead function
because it takes about 28 \ 32 \ 36 microseconds (these are empirical measures).
analyzing the code in wiring_analog.c
( which is located in the folder [...]/arduino/hardware/arduino/cores/arduino/ )
the actual conversion seems to happen at line 77
// start the conversion
sbi(ADCSRA, ADSC);

does that mean that this is the instant from which the actual ADC conversion start, and so 1.5 ADC clock cycles from here, my analog pin value is set on hold?
how can I know how much time passed before that sbi function call is issued?
I saw that a single instruction on arduino won't take more than 4 microseconds (but micros() function has that resolution so I don't exactly know!)
Now, considering the so called "first" conversion, which take 25 ADC clock cycles
does this conversion happen just the first time I call analogRead since I powered on Arduino?
or does it happen even after some time , because the ADC module gets powered off? (of course, I consider the case when Arduino remains powered on all the time)
Judging by the timings I measured it seems like that the former is the one really happening, even if I don't use ADC for some time, but can anyone confirm?

does that mean that this is the instant from which the actual ADC
  conversion start, and so 1.5 ADC clock cycles from here, my analog pin
  value is set on hold?

Yes. After between 3μs and 5μs. This is because conversion start at the following rising edge of the ADC clock cycle. This rising edge might have just happened, which means you need to wait 31 (main) clock cycles.

how can I know how much time passed before that sbi function call is
  issued?

You could copy the original code and create your own analogRead2 function that measures the time before setting ADSC.

I saw that a single instruction on arduino won't take more than 4
  microseconds (but micros() function has that resolution so I don't
  exactly know!)

A single instruction will take 1 or 2 clock cycles (if I remember correctly). So at 16Mhz that will mean 62.5ns (nano seconds) per clock cycle. Not 4ms

Now, considering the so called "first" conversion, which take 25 ADC
  clock cycles
does this conversion happen just the first time I call analogRead
  since I powered on Arduino? or does it happen even after some time ,
  because the ADC module gets powered off? (of course, I consider the
  case when Arduino remains powered on all the time)
Judging by the timings I measured it seems like that the former is the
  one really happening, even if I don't use ADC for some time, but can
  anyone confirm?

This first conversion is after the ADEN bit changes from 0 to 1. If you don't unset this bit, all further conversions will take the shorter time.
PS on the first conversion, the sample-and-hold takes place after the extra 12 ADC clock cycles, so between cycle 12 and 13.5.
PPS this info is actually based on the ATMega328, but should be pretty similar in the 2560.

First of all, thx Gerben.
"Yes. After between 3ms and 5ms. [...]"
Just to be crystal clear: you meant microseconds, right? I'm asking because I work with that magnitude: I need to read within 40 microseconds
"A single instruction will take [...] 62.5ns per clock cycle."
if it gets translated into one machine instruction, yes, but like you suggested, I can create my copy of AnalogRead and get the info I need;
Nice advice, thanks! :D
the first sbi() call took about 52 microsecs, the next ones took nearly 24 microsecs.

Yes, sorry. I meant μs.

source: Stack Exchange

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

sort: votes


text:
SPI MOSI receive error
I have a master and a slave (both are arduino UNO) connected through SPI connected. I want to transmit a character to the slave and receive true or false to the master. The transmission is working perfectly. If I send '2', slave is receiving '2'. When I try to transmit an integer from slave to master, the master is always receiving some arbitrary number like 128 or 255.
Master Code:
void setup() {
  Serial.begin(9600);
  Serial.println("Master");
  digitalWrite(SS,HIGH);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop() {
  digitalWrite(SS,LOW);  //  Slave select to low
  received1 = SPI.transfer(test);  // test is a variable which is '2'. The data received by master is stored in received1 variable which is char.
  Serial.println(received1);
  digitalWrite(SS,HIGH);
}

Slave code:
void setup() {
  Serial.begin(9600);
  Serial.println("Slave");
  pinMode(MISO,OUTPUT);
  SPCR |= _BV(SPE);
  process = false;
  SPI.attachInterrupt();
}
ISR(SPI_STC_vect){
  received = SPDR;  // the data received by slave is slored in **received** variable(the variable is char type)
  Serial.println(received);
  process = true;
}
void loop() {
  if(process){
    SPDR = jj;  // Updating SPDR to send data from slave. jj is char type
    process = false;
  }
}

The most important part, declaration of variable process, is not here. Is it volatile? Also do you realize that SPDR on slave must be set before the master starts transmission?

Sorry for not mentioning about process. It's a boolean variable which will be true when something is received by slave.

I have found a solution for this problem in a blog.
Link: http://www.gammon.com.au/forum/?id=10892
I modified my master code and got my desired result.
Master code:
byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (2000);
  return a;
} // end of transferAndWait

void loop() {
  digitalWrite(SS,LOW);
  transferAndWait (10);
  received1 = transferAndWait (11);
  digitalWrite(SS,HIGH);
  Serial.println(received1);
}

The response will be "collected" next time through the loop. That's why we need to keep a dummy transferAndWait() function first and then the result of that transfer will be stored in received1 variable.

Please accept your own answer if it solved your problem, otherwise Stack Exchange throws it up from time to time as an unsolved question.

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


text:
is it possible to program an arduino with usb/ttl adapter
i want to upload sketch into arduino uno using usb/ttl adapter.i tried searching for it, but found about programming arduino using another. can anyone help me.

This may be obvious to you, but may not be to us.  What are you connecting to each end of the USB to TTL adapter cable?

I'm trying to understand your question, why can't you just program it by plugging a USB lead between a PC and the board.  Are you doing something special?

The Arduino onboard USB to serial is connected to D0 (Rx) and D1 (Tx).
And without a USB connected to the Arduino you can use a USB/TTL adapter connected to D0 and D1 like this;
Arduino  - USB/TTL
Tx       - Rx
Rx       - Tx

And to get the Arduino inte "programming" mode:

Automatic way, if the USB/TTL have CTS, connect it to Arduinos reset pin.
Manual way, press the reset button when the Arduino IDE starts to upload the code.

The Uno is normally programmed by its on-board USB adapter.
The Pro Mini does not have an on-board adapter, and is normally programmed with an external USB/serial adapter. This should also be possible with Uno.


text:
Button not working - Arduino Due project (MiniEngine v2)
I am building Arduino Due based project called MiniEngine v2 (an open-source motion control software for timelapse photography).
The project is not very active anymore but there are still all the documentation at github. Project owner had webshop where he sold MiniEngine shields for arduino but they are not available anymore. There was gerber files available at project github page so I orderer PCB's form seeed.com.
Project's Github page is at:
https://github.com/airiclenz/miniEngine2
Everything seems to work ok but one of the buttons is not working. There is only 2 buttons and one rotary encoder.
I think the reason why the button is not working is that the output voltage for button from 74HC14N (hex smith trigger) is too low (I am not very good at electronic so I might be totally wrong.
I tried to measure values with voltage meter and here is the result what I got for those two buttons:
Here are the values in written format ( I took measurement from SN74HC14N )

btn_2 (pin9 input, pin8 output)
btn_1 (pin11 input, pin10 output)

SETTINGS BUTTON (btn_2) -> this one works fine

1) button up  - metering from input pin 11 => 3.26
2) button down -metering from input pin 11 => 0
3) button up - metering from output pin 10 => 0.6
4) button down - metering from output pin 10 => 2.38

START/BACK BUTTON (btn_1) -> this one does not work

1) button up  - metering from input pin 9 => 3.26
2) button down - metering from input pin 9 => 0
3) button up - metering from output pin 8 => 1.43
4) button down - metering from output pin 8 => 1.53

Here is how the buttons are initialized:
    void input_init() {

  // set pin modes
  pinMode(PIN_ROTARY_PRESS, INPUT);
  pinMode(PIN_KEY_1, INPUT);
  pinMode(PIN_KEY_2, INPUT);

  // attach interrupts for the keys
  attachInterrupt(PIN_ROTARY_PRESS, input_interrupt_keyRotary_press,  RISING);
  attachInterrupt(PIN_KEY_1,        input_interrupt_key1,             RISING);
  attachInterrupt(PIN_KEY_2,        input_interrupt_key2_press,       RISING);

  // attach interrupts to both encoder pins for every state change
  attachInterrupt(PIN_ROTARY_A,     input_interrupt_rotary,           CHANGE);
  attachInterrupt(PIN_ROTARY_B,     input_interrupt_rotary,           CHANGE);

  // set the initial rotary values & configurations
  rotary.setPosition(0);
  rotary.setKeyMode(true);
  rotary_old_pos = 0;
}

And here is function for btn_1 press that is never called (except once in powering the shield/arduino due)
void input_interrupt_key1() {

  if ((key_1_time + DEF_INPUT_DEBOUNCE) < millis()) {

    key_1_time = millis();
    setBit(input_status, BIT_2);

  }
}

I can only use 2 links in posts (I do not have 10 reputation) so you can find the code for inputs at Github (link above). (folder MiniEngine2/Software/miniEngine2/mE2_input.ino)
All code files are at Sotfware at folder: MiniEngine2/Software/miniEngine2
I have put Serial.println command in code and nothing is printed when btn_1 is pressed. When I plug power on then the btn_1 is triggered once...
Here is link to the the schematic for that shield ( it is quite big so that's why I did not embed the photo):
Schematic for shield is at Github folder : Hardware/miniE shield v2 revB BED board - schematic.pdf
Here is also link to the video where you can see how I took the measurements:
https://youtu.be/wFR7P65qMGA
Please ask if I need to provide more information...

First thing to try - power the board without the arduino connected and verify that you see the same results. That would eliminate the possibility or an arduino or software related issue. My best guess is a soldering issue on the output pin or the connector to the arduino. A digital output pin that's stuck halfway between high and low normally means either a design fault or a short somewhere.

I forgot to mention that I soldered two similar shields and both have the same problem. So I do not believe that it is soldering issue (but of course it still might be it). Now I try without arduino connected...

It was the Arduino Due issue. Arduino digital pin 43 was faulty or something. I managed to change 43 to 53 and now the button works...

You should accept this answer as the solution so that the question no longer shows up as open.


text:
Particle Electron to RS232 Serial gibberish
I've spent all day trying to monitor serial console output of a router. I'm using an "ebay" MAX3232 RS232 to TTL converter connecting only GND, TX and RX to the Electron. Trying to simply monitor the console output during bootup - all I get is gibberish.
Even connected to computer's COM1 port and was unable to echo back and forth. All I get is 0 or weird symbols. (this was tried with more code than below)
Here's my most basic code. I'm about ready to give up. Any ideas?
#include "Particle.h"

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600); // tried with 2400/even 1200 really should be 9600
  Serial.println("Starting up Serial");
  Serial1.println("Starting up Serial1");
}

void loop() {
 while(Serial1.available()>0)
 {
   Serial.write(Serial1.read());
 }
 delay(50);
}

Did you check the power supply voltage on the MAX3232 pins (V+ pin 2 and V- pin 6)? What are the values of the two flying caps (across pins 1-3 and pins 4-5)? And, if you suspect that you were sold a counterfeit part, Maxim customer service would like to know. (Disclaimer: I am a Maxim applications engineer.)

I suspect you have the wrong master serial clock rate.

Loopback test the MAX3232 transceiver by itself (independent of the microcontroller). Connect the loopback on the RS232 side (T1OUT driving R1IN), and then drive logic low on T1IN, expect the RS232 loopback should go to about +5.5V and expect the R1OUT should go logic low. Then drive logic high on T1IN, expect the RS232 loopback should go to about -5.5V and expect R1OUT should go logic high. MAX3232 datasheet

Will definitely try that and get back. Thanks

I didn't see any comments to check other baud rates. How did you determine it should be 9600 baud? What Arduino board are you using? I've not played with the mega board but the examples I saw did not use Serial.begin(). They were all Serial1.begin, Serial2.begin... depending on which serial port you want to use.

If the OP has correctly stated that only three connections to the MAX3232 have been made, power to the device is missing.
Code tested with an RS232 transmitting device (Maxbotix 7092) with Sparkfun MAX3232 breakout and Particle Photon. Serial monitor correctly displays continuous range reading.

You do not need any hardware between the Particle and the router. Both the router and the Particle work at 3.3V logic levels.

Connect the GND of the router the GND of the Particle
Connect the TX of the router to the RX1 of the Particle
Connect the RX of the router to the TX1 of the Particle

You only need the MAX3232 if you want to connect direct to your computer's RS232 port:

Connect the GND of the MAX3232 to the GND of the computer and the GND of the router
Connect the TX of the computer to RIN of the MAX3232
Connect the RX of the computer to DOUT of the MAX3232
Connect the TX of the router to the DIN of the MAX3232
Connect the RX of the router to the ROUT of the MAX3232
Connect the VCC of the MAX3232 to +3.3V from the router.

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


text:
Is it right to connect Serial module directly?
I find a strange thing that the led is on when power is off. And it's the problem of my serial module. Arduino may get power from my serial module. My serial module use max2322. I don't if it will harm my arduino or has influence to my program.
Is it needed to add a resistance?

you have an Arduino ??? powered from ??? and you connected a serial module ??? to rx/tx, ground and ???

@Juraj Arduino no power。I just connect tx rx and gnd to serial module. And my module is connected to pc by usb

Maybe the serial module has a serial cable attached to it which gives a voltage.
I think it can hurt, since you have two voltage sources, one from the Arduino and one from the Serial cable. Not using the power wire from the serial cable should fix the problem.
A resistor will not help because you still have two power sources in case you have both voltage from the Arduino (adapter/USB) and serial.


text:
How to compare two string?
I meet a terrible problem. I can't compare two string!
My job is simple, every 1ms use SoftwareSerial read_card(2, 3);to check if i read a id card.And don't read a card twice.Here are my code:
bool CardReader::check()
{
    String str= read_card.readString();
    if (str.length() == 0 ) return false;
    //Log("card:%s", str);
    Serial.println("card_id");
    Serial.println(str);
    Serial.println(card);
    Serial.print("cmp:"); Serial.println(str == card);
    if (str.length() == card.length())
    {
        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();
        for (int i = 0; i < card.length(); i++)
            if (p1[i] != p2[i])
                break;
        return false;
    }
    card = str;
    return true;
}

Let's see output:
card_id
 Rq
 僐R
cmp:1

The hex are:
00 01 52 71 02
00 83 52 52 00

Why the two string is equal?
Bugs are fixed.If string begin with '\0',== can't work and = can't work either.
bool CardReader::check()
{
    String str = read_card.readString();
    if (str.length() == 0) return false;
    if (str.length() == card.length())
    {
        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)card.c_str();
        for (int i=0; i < card.length(); i++)
        {
            Log("%d:%d", p1[i],p2[i]);
            if (p1[i] != p2[i])
                goto find_card;
        }
        return false;
    }
find_card:
    for(int i=0;i<5;i++)
        card[i]=str[i];
    return true;
}

Because both strings are empty. In fact, calling the method c_str() will give a an array, which has at its first position ([0]) the null terminator (0x00 or '\0'). What follows the 0x00, is just rubbish.
In fact, check the card length, it will be 0.
(btw, there are some bugs in the code too. It always return false if the string have the same length, and it will always return true otherwise. EDIT: following the Nick Gammon's answer I also noticed that you get the pointer of the same string :). I corrected also this).
I think the code should be rewritten to:
if (str.length() == card.length())
{
    uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)card.c_str();
    for (int i = 0; i < card.length(); i++)
        if (p1[i] != p2[i])
            return false;
}
else
    return false;
return true;

EDIT:
I add there what I wrote in the comments, for future reference, and explained in details.
The problem lies on the String class, which on one hand, it allows adding '\0' characters, through the method concat(char*), but on the other, it uses the strcmp (and other C standard functions) to perform compare between strings. This leads to unpredictable results. Maybe this is a bug in the String class.
In particular, SoftwareSerial extends Stream. Stream::readString() (which is used in the program to get str), is implemented as follows:
String Stream::readString()
{
  String ret;
  int c = timedRead();
  while (c >= 0)
  {
    ret += (char)c;
    c = timedRead();
  }
  return ret;
}

The line ret += (char)c; uses operator +=, which is implemented in WString.h as:
String & operator += (char c)           {concat(c); return (*this);}

Note that readString() also allows adding any non negative value of c, including 0, i.e. '\0' - see while (c >= 0) in its code above
In turn, concat(char c) is implemented in WString.cpp as:
unsigned char String::concat(char c)
{
    char buf[2];
    buf[0] = c;
    buf[1] = 0;
    return concat(buf, 1);
}

And concat(const char *cstr, unsigned int length) is implemented as:
unsigned char String::concat(const char *cstr, unsigned int length)
{
    unsigned int newlen = len + length;
    if (!cstr) return 0;
    if (length == 0) return 1;
    if (!reserve(newlen)) return 0;
    strcpy(buffer + len, cstr);
    len = newlen;
    return 1;
}

In the above method, length (instead of strlen) is used to determine the length of the string to add, and the new length is calculated using it:
newlen = len + length;

That's the bug: you can add a '\0' char to the string, and this will also result in an increased length of the string. They should have checked if length <= strlen(cstr), before performing this concat operation.
Now, if you call the method String::equals or use the operator == (it is the same, as it is defined in WString.h as     unsigned char operator == (const String &rhs) const {return equals(rhs);}), you call this code:
unsigned char String::equals(const String &s2) const
{
    return (len == s2.len && compareTo(s2) == 0);
}

Which, in turn, calls:
int String::compareTo(const String &s) const
{
    if (!buffer || !s.buffer) {
        if (s.buffer && s.len > 0) return 0 - *(unsigned char *)s.buffer;
        if (buffer && len > 0) return *(unsigned char *)buffer;
        return 0;
    }
    return strcmp(buffer, s.buffer);
}

And strcmp ends its compare operation if it first encounters a null operator (or when a compare mismatch occurs).
Therefore in your case, readString() added a null character to the "ret" String at first, and then some other characters. This created a String which begins with '\0'. Such string is equal to any other string beginning with a '\0', regardless what follows '\0'. But if you call length(), you'll get "len" (which String::concat() does not correctly calculate, and it will be non 0), as you can find in WString.h:
inline unsigned int length(void) const {return len;}

Disclaimer: future versions of WString.h and WString.cpp could have fixed this bug.

I had a think of the problem of '\0'.So how to get the real length of string?

No, length is right.It returns 5 when str begin with '\0'.And it should return true when str!=card because I find a new card.So I don't think there are bugs about condition.@next-hack.In addition,I found some strange things.Is it relative to memory?I have used 65%.

That's strange indeed, as in fact your first check for str.length() should make your function returning false immediately. Can you update your question writing also the code of read_card.readString() ?
Strange things could happen also due to misused pointers or buffer overflows...

.read_card isSoftwareSerial.And I already print str and card.

Ok, I got it. SoftwareSerial extends Stream. Stream::readString() simply adds characters, regardless their value, i.e. it concats also '\0' (i think it's a bug, they just check for >=0 instead of >0. Then String::concat(char c) also allows adding \0 chars, see WString.cpp. This lead to a malformed String, which can actually start with a \0, which is a null terminator. String class uses conventional C string functions (such as strcmp for operator == and for compareTo() method), therefore having a String with a \0 char will generate unpredicted results...

Thank you.I have solved it.But it's hard to create a dynamic length string.

More strange thing is that the operator= of string would alloc the right length memory, but wouldn't assign every value.

it's simple. The operator = creates a new string, whose length is determined calling oldString.length(), which just return the miscalulated "len" value (see my answer). However, it copies oldstring into newstring, using strcpy, which ends prematurely as the first null terminator is reached. ( http://www.cplusplus.com/reference/cstring/strcpy/ ). The remaining chars remain uninitialized ("random" value).

Why the two string is equal?

        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();

Both p1 and p2 point to the same string so of course they will always compare equal.

Do you mean:
if (str == card)
   // do something

Sorry, I write the compare function because  str == card didn't work.

Try strcmp()
See if  it works.

it wont even compile, str and card are String objects, while strcmp() works with char*.

Not a bad idea to use c-style strings this time maybe?

@dannyf maybe include instructions how to use char * instead of String?


text:
Arduino IDE on Linux - directory not found
I have Ubuntu 14.04 installed on a chromebook through crouton. I'm trying to install the Arduino IDE. I figured out that I needed the 64-bit version of the IDE and downloaded it. Then, I started following the instructions given - I found the downloaded file, which was named arduino-1.8.0-linux64.tar.xz, opened it (this opened a new window in a program called Xarchiver, which listed the subfolders and files), and saw the install.sh file. When I right-clicked, there was no option to run it from the terminal, so I went back to the terminal and did cd Downloads and then tried to cd into the downloaded file. However, it said that there was no such directory. I listed the files in Downloads, and the downloaded file came up, listed in red.
How can I run the install.sh file? What am I doing wrong? Any help would be appreciated.

You need to extract the archive file first.
$ cd ~/Downloads
$ tar -Jxvf arduino-1.8.0-linux64.tar.xz


text:
Which timer does Arduino Nano use for each PWM pin?
I'm unable to find which Timer controls each PWM pin (3, 5, 6, 9, 10 and 11) in an Arduino Nano Board (ATmega328).
Any guesses?
Thanks in advance,
Eduardo

This is a good pinmapping picture of the Nano : www.pighixxx.com/test/portfolio-items/nano/
A timer has sometimes two outputs, A and B. The pins with OC0A and OC0B are timer outputs of Timer0. OC1A and OC1B are Timer1, OC2 and OC2B are Timer2.
Everything is also in the datasheet of the ATmega328P, but that picture is a lot easier.


text:
MPU9250 - Calibration Not Saved with RTIMULib EEPROM Issues
I'm using the MPU9250 and the RTIMULib to perform sensor fusion, however, when I run ArduinoMagCal, and save the calibration, and follow that with running the main ArduinoIMU it claims the calibration file is not saved, and there is no data to use. I'm trying to determine why this is - I have tried the other MPU9250 libraries without luck, as this one is working on my setup (Arduino Micro -> eventually NodeMCU).
Repo : https://github.com/maxouille/RTIMULib-Arduino
ArduinoMagCal
////////////////////////////////////////////////////////////////////////////
//
//  This file is part of RTIMULib-Arduino
//
//  Copyright (c) 2014-2015, richards-tech
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
//  Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
//  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <Wire.h>
#include "I2Cdev.h"
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "CalLib.h"
#include <EEPROM.h>

RTIMU *imu;                                           // the IMU object
RTIMUSettings settings;                               // the settings object
CALLIB_DATA calData;                                  // the calibration data

//  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

#define  SERIAL_PORT_SPEED  115200

void setup()
{
  calLibRead(0, &calData);                           // pick up existing mag data if there

  calData.magValid = false;
  for (int i = 0; i < 3; i++) {
    calData.magMin[i] = 10000000;                    // init mag cal data
    calData.magMax[i] = -10000000;
  }

  Serial.begin(SERIAL_PORT_SPEED);
  Serial.println("ArduinoMagCal starting");
  Serial.println("Enter s to save current data to EEPROM");
  Wire.begin();

  imu = RTIMU::createIMU(&settings);                 // create the imu object
  imu->IMUInit();
  imu->setCalibrationMode(true);                     // make sure we get raw data
  Serial.print("ArduinoIMU calibrating device "); Serial.println(imu->IMUName());
}

void loop()
{
  boolean changed;
  RTVector3 mag;

  if (imu->IMURead()) {                                 // get the latest data
    changed = false;
    mag = imu->getCompass();
    for (int i = 0; i < 3; i++) {
      if (mag.data(i) < calData.magMin[i]) {
        calData.magMin[i] = mag.data(i);
        changed = true;
      }
      if (mag.data(i) > calData.magMax[i]) {
        calData.magMax[i] = mag.data(i);
        changed = true;
      }
    }

    if (changed) {
      Serial.println("-------");
      Serial.print("minX: "); Serial.print(calData.magMin[0]);
      Serial.print(" maxX: "); Serial.print(calData.magMax[0]); Serial.println();
      Serial.print("minY: "); Serial.print(calData.magMin[1]);
      Serial.print(" maxY: "); Serial.print(calData.magMax[1]); Serial.println();
      Serial.print("minZ: "); Serial.print(calData.magMin[2]);
      Serial.print(" maxZ: "); Serial.print(calData.magMax[2]); Serial.println();
    }
  }

  if (Serial.available()) {
    if (Serial.read() == 's') {                  // save the data
      calData.magValid = true;
      calLibWrite(0, &calData);
      Serial.print("Mag cal data saved for device "); Serial.println(imu->IMUName());
    }
  }
}

ArduinoIMU
////////////////////////////////////////////////////////////////////////////
//
//  This file is part of RTIMULib-Arduino
//
//  Copyright (c) 2014-2015, richards-tech
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
//  Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
//  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <Wire.h>
#include "I2Cdev.h"
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "RTFusionRTQF.h"
#include "CalLib.h"
#include <EEPROM.h>

RTIMU *imu;                                           // the IMU object
RTFusionRTQF fusion;                                  // the fusion object
RTIMUSettings settings;                               // the settings object

//  DISPLAY_INTERVAL sets the rate at which results are displayed

#define DISPLAY_INTERVAL  300                         // interval between pose displays

//  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

#define  SERIAL_PORT_SPEED  115200

unsigned long lastDisplay;
unsigned long lastRate;
int sampleCount;

void setup()
{
    int errcode;

    Serial.begin(SERIAL_PORT_SPEED);
    Wire.begin();
    imu = RTIMU::createIMU(&settings);                        // create the imu object

    Serial.print("ArduinoIMU starting using device "); Serial.println(imu->IMUName());
    if ((errcode = imu->IMUInit()) < 0) {
        Serial.print("Failed to init IMU: "); Serial.println(errcode);
    }

    if (imu->getCalibrationValid())
        Serial.println("Using compass calibration");
    else
        Serial.println("No valid compass calibration data");

    lastDisplay = lastRate = millis();
    sampleCount = 0;

    // Slerp power controls the fusion and can be between 0 and 1
    // 0 means that only gyros are used, 1 means that only accels/compass are used
    // In-between gives the fusion mix.

    fusion.setSlerpPower(1);

    // use of sensors in the fusion algorithm can be controlled here
    // change any of these to false to disable that sensor

    fusion.setGyroEnable(false);
    fusion.setAccelEnable(true);
    fusion.setCompassEnable(true);
}

void loop()
{
    unsigned long now = millis();
    unsigned long delta;
    int loopCount = 1;

    while (imu->IMURead()) {                                // get the latest data if ready yet
        // this flushes remaining data in case we are falling behind
        if (++loopCount >= 10)
            continue;
        fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
        sampleCount++;
        if ((delta = now - lastRate) >= 1000) {
            Serial.print("Sample rate: "); Serial.print(sampleCount);
            if (imu->IMUGyroBiasValid())
                Serial.println(", gyro bias valid");
            else
                Serial.println(", calculating gyro bias");

            sampleCount = 0;
            lastRate = now;
        }
        if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
            lastDisplay = now;
//          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());                // gyro data
//          RTMath::display("Accel:", (RTVector3&)imu->getAccel());              // accel data
            //RTMath::display("Mag:", (RTVector3&)imu->getCompass());              // compass data
            RTMath::displayRollPitchYaw("Pose:", (RTVector3&)fusion.getFusionPose()); // fused output
           Serial.println();
        }
    }
}

Lastly in the repo, you will see a CalLib folder with the CalLib.cpp program inside, wondering if it is saving to the EEPROM incorrectly?
////////////////////////////////////////////////////////////////////////////
//
//  This file is part of RTIMULib-Arduino
//
//  Copyright (c) 2014-2015, richards-tech
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
//  Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
//  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "CalLib.h"
#ifdef __SAM3X8E__

// Due version

#include "DueFlash.h"

DueFlash flash;

void calLibErase(byte device)
{
    uint32_t data = 0;

    flash.write(CALLIB_START + sizeof(CALLIB_DATA) * device, &data, 1); // just destroy the valid byte
}

void calLibWrite(byte device, CALLIB_DATA *calData)
{
    calData->validL = CALLIB_DATA_VALID_LOW;
    calData->validH = CALLIB_DATA_VALID_HIGH;

    flash.write(CALLIB_START + sizeof(CALLIB_DATA) * device, (uint32_t *)calData, sizeof(CALLIB_DATA) / 4);
}

boolean calLibRead(byte device, CALLIB_DATA *calData)
{
    memcpy(calData, CALLIB_START + sizeof(CALLIB_DATA) * device, sizeof(CALLIB_DATA));
    return calData->valid == CALLIB_DATA_VALID;
}

#else

// AVR version

#include <EEPROM.h>

void calLibErase(byte device)
{
    EEPROM.write(sizeof(CALLIB_DATA) * device, 0); // just destroy the valid byte
    //EEPROM.commit();
}

void calLibWrite(byte device, CALLIB_DATA *calData)
{
  byte *ptr = (byte *)calData;
  byte length = sizeof(CALLIB_DATA);
  int eeprom = sizeof(CALLIB_DATA) * device;

  calData->validL = CALLIB_DATA_VALID_LOW;
  calData->validH = CALLIB_DATA_VALID_HIGH;

  for (byte i = 0; i < length; i++) {
    EEPROM.write(eeprom + i, *ptr++);
    //EEPROM.commit();
  }
}

boolean calLibRead(byte device, CALLIB_DATA *calData)
{
  byte *ptr = (byte *)calData;
  byte length = sizeof(CALLIB_DATA);
  int eeprom = sizeof(CALLIB_DATA) * device;

  calData->magValid = false;

  if ((EEPROM.read(eeprom) != CALLIB_DATA_VALID_LOW) ||
      (EEPROM.read(eeprom + 1) != CALLIB_DATA_VALID_HIGH)) {
    return false;                                  // invalid data
  }

  for (byte i = 0; i < length; i++)
    *ptr++ = EEPROM.read(eeprom + i);
  return true;
}
#endif

I'm not sure if you're flashing your device, but anytime you flash an Arduino the EEPROM is cleared. This might be the issue.

There was a compilation error which was preventing me from seeing that the data was indeed being saved to EEPROM, as far as I know there are no more issues. Just be mindful if you want to test it to add this in your calibration file after the save line:
  if (imu->getCalibrationValid())
      Serial.println("Using compass calibration");
  else
      Serial.println("No valid compass calibration data");

authors: Юрий Демидов


text:
Scale Magnometer to Servo
I'm trying to determine what is the best way to scale a magnometer to a servo, I am using the BNO055 from Bosch I get a heading say 50 degrees, and I want to be able to input 45 degrees and have the servo motor move accordingly. I am using a 180 degree motor. I would like to be able to input 45 degrees, and then the motor if 50 degrees was 95, would decrease in value step by step until the magnometer read 45; I'm having difficulty creating the logic to do this.
Bosch output is between 0 and 360; so I could end up with servo 0 is 120; and servo 180 is 300. Meaning the values are 300 - 360, 0 - 120 making the full 180, so I am not sure how I could use something like map in arduino to solve this issue.

Okay, lets say the output of your BNO055 is called x and the value for your servo is y. We need to translate x to y and you are correct to use the map() function. But what you are forgetting is that you do not need to map all the values of x to all the values of y. You can split it up.
In your example the values of the BNO055 relate to the servo as follows:
x   | y
0   | 0
120 | 0
300 | 180
360 | 180

The servo only rotates from 0 degrees to 180 degrees between the BNO055 sensor values of 120 and 300. So you only need to map those values, while all values below should result in 0 and all values above should result in 180 degrees for the servo.
This translates into the following code:
//x is the output of BNO055 sensor
if(x < 120){
  servo.write(0);
}
if(x > 300){
  servo.write(180);
}
if(x > 120 && x < 300){
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}

Another way of coding this is:
if(x < 120){
  servo.write(0);
}
else if(x > 300){
  servo.write(180);
}
else{
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}

It's hard to tell from the question, but I got the impression the OP wanted 300-360 to map to 0-60 and 0-120 to 60-180, which means wrapping the values first to be -60 to +120.

Now I'm confused, haha. Regardless what OP's desired data is, I hope this code shows him he is able to specify ranges of map() instead of just mapping everything.

@Len is correct to clarify the sensor reads 0 to 360; and for the example we have 300 to 360 and then 0 to 120 because the sensor wraps around - so my plan was to set the servo to 0 get the min reading which was 300 and 180 is 120 so then I need to map for those values so I'm guessing that means I would map like 0 to 60 for 300 to 360 and 60 to 180 for 0 to 120; does that make sense for map function?

Yes, you can reverse map values. Say you need to map 0, 100 to 10,0 you just reverse the last two variables of map() as follows map(x, 0, 100, 10, 0);
Also, about the servo. You don't need to manually change the position of the servo. Servo's are made to rotate to a specific location and know at what position they are, even if they just got power.

You need to remember that you are working with a circle. You have degrees 0 to 360, but only if counting clockwise. If you work anticlockwise you also have degrees 0 to -360.
So your angles of interest are, clockwise from 0, 0-120, and anti-clockwise from 0, 0 to -60
To make things easier on you you need to create a range that is wrapped around so that anything in the "left" half of the circle is counted as anticlockwise from 0 and anything in the "right" half of the circle is counted clockwise from 0.
So values 0-180 are 0-180, but values of 180 to 360 are -128 to 0.  Then your entire range spreads from -180 to +180 instead of 0-360 (if that makes sense).
It's simple enough:
if (angle > 180) angle = 0 - (360 - angle);

So if angle is 300 you get:
0 - (360 - 300) = 0 - 60 = -60

If angle is 330 you get:
0 - (360 - 330) = 0 - 30 = -30

Now you can map the new values using the map function @Len has detailed above:
servo = map(angle, -60, 120, 0, 180);

It is also possible to combine it all into one line should you wish, using the C "inline if" format:
servo = map((angle > 180 ? (0 - (360 - angle)) : angle), -60, 120, 0, 180);

But that is kind of cryptic :)

Excellent this solution I believe will solve it - unfortunately during the test of this solution I ended up burning out the servo motor itself :P So now I'll have to try again sometime next week, will keep this updated.


text:
Determine Object Heading
Is there a sensor I could use which would let me know which direction an object is heading/facing? i.e. I have a servo that can rotate 0 to 180 degrees, and I have another sensor on a block. When I turn the block 45 degrees, I want the servo to also turn 45 degrees - I thought I could do this with a compass, but the varying magnetic fields make it impossible. Gyro/acc maybe? Except I don't know how to use that to solve this problem.
So in other words we need to know the block was rotated 45 degrees using a sensor on the block, which tells the servo to rotate 45 degrees.

You can lookup "sensor fusion" (which is a complicated matter) and "MPU6050", which is a cheap board with some hardware support and plenty of examples for it - perhaps it might be what you need.

Great thanks, I think that might work I have used that sensor before for an indoor positioning system / IMU setup -- one question though is there a way to have two separate MPU6050 synchronize orientations? That was the reason for my compass system - both knew which way was north irregardless of when they were turned on so I could use that as a calibration point.

Lookup Magnetometer sensor.

You could use the accelerometer to "synchronize orientation" because gravity always points down, but that will only work if the two sensors rotate on an axis that does not line up with gravity (e.g. they don't rotate around an axis pointed up). Similarly, a magnetometer won't work if the table rotates around the north vector.

Use a gyro, it will give you the angle. Gyros are difficult to find spare, so you should buy an IMU like MPU6050 that contains also an accelerometer.

authors: บันฑิตา อินทร์สุวรรณ์


text:
Strange RPM Readings on Teensy 3.2
While trying to read RPM from a computer fan using the 4-wire protocol, I am getting strange readings. +12 and GND from the fan are connected to a power supply, and the tachometer to the PIN-0 or a Teensy 3.2.
I wrote code to read the tachometer pulse using the internal pull-up and interrupts. The strange thing happening is that the number of recorded revolutions is increasing as I manually slow the fan using my fingers.
Here is the code :
#include <avr/io.h>
#include <avr/interrupt.h>
#include <elapsedMillis.h>

const int fanPulse = 0;
volatile long half_revolutions;
elapsedMillis timeElapsed;

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

  pinMode(fanPulse, INPUT_PULLUP);
  attachInterrupt(fanPulse, rpm_fun, FALLING);

  half_revolutions = 0;
  // analogWriteFrequency(20, 25000); // Teensy 3.0 pin 3 also changes to 375 kHz
}

void rpm_fun() {
  half_revolutions++;
}

void loop() {
  if (timeElapsed < 1000)
    return;

  Serial.printf("%d revolutions in %d miliseconds\n", half_revolutions / 2, (unsigned long)timeElapsed);

  timeElapsed = 0;
  half_revolutions = 0;
}

Here is the strange output :
0 revolutions in 1000 miliseconds  // Start
0 revolutions in 1000 miliseconds
82 revolutions in 1000 miliseconds
394 revolutions in 1000 miliseconds  // "normal" reading
412 revolutions in 1000 miliseconds
576 revolutions in 1000 miliseconds
456 revolutions in 1000 miliseconds
554 revolutions in 1000 miliseconds
585 revolutions in 1000 miliseconds
799 revolutions in 1000 miliseconds  // Slowing the fan
712 revolutions in 1000 miliseconds
691 revolutions in 1000 miliseconds
683 revolutions in 1000 miliseconds
625 revolutions in 1000 miliseconds
531 revolutions in 1000 miliseconds
239 revolutions in 1000 miliseconds
0 revolutions in 1000 miliseconds
0 revolutions in 1000 miliseconds  // End

I must have misread what you have written.  Why do you think these readings are strange?  I would expect that as you slow the fan the number of revolutions per second goes down and that's what the results seem to say.

Did you connect the ground of the Teensy to the ground of the fan?

Matt, I get around ~450 rpm in normal conditions and around ~650 rpm when slowing down.
@Majenko, No I didn't, I was thinking this might be the issue too. My Teensy is powered through USB and the Fan to an external power adapter, is it safe to connect the two ground?
Andy, the 0 rev cycles are the moment where I manually switched off the external power adapter with a switch.

You have to have the grounds connected, otherwise you are just measuring noise.

@Majenko, make that an official response and you'll get a resolving answer! Thanks to all.

Without the ground of the teensy connected to the ground of the fan all you will be measuring is noise. Ground is required to complete the circuit between the teensy and the fan.


text:
Can I use a PIR sensor to turn on an arduino?
I'd like to use a PIR sensor (HC-SR501) to control the power to an Arduino Uno. Note that I'm not talking about using a PIR sensor as input to the Arduino and sensing the output pin from the PIR, I'm talking about using the output pin from the PIR to turn the Arduino itself on and off.
Hooking it up directly doesn't seem to work as I'm guessing the PIR doesn't handle that much current output. Would I use a transistor of some kind to do this?
My reason for wanting to do this is simple, power preservation. The PIR uses so little current when it doesn't sense anything that I thought it would be nice for something like a mailbox sensor that doesn't need to run that often. Thanks.

Most serious designs would do this by suspending the processor rather than depowering it, though the whole board needs to designed with that in mind, something an off-the-shelf Arduino is not.  If you actually want to depower it, and the Arduino needs to communicate with anything having a common ground with the control circuit, you may find high-side "USB power switch" like the RT9701B simplest for controlling the supply, even if it is not USB.

Did anyone find a solution to this? I have a servo to power with the Arduino. Maybe the PIR sensor can turn on a second power supply before turning on the Arduino and running the servo? Long shot but who knows.

Yes you can.
It all depends on how you are turning the power on.  You sensor needs to flip a 'switch' rather than actually power the Arduino directly.  (I'm sure you know that but just in case).
So you need a normally open relay in between you power source and you Arduino.  Normally open because you don't want it powered unless you 'turn it on'.  Your relay might be able to be switched by your PIR sensor's data output, but if you need more current then you are going to have to use a transistor and draw more power from the power source.
You have the PIR sensor, so now find the relay capable of carrying the maximum current you need for the Arduino.

Ok that's kinda what I figured and I did try a relay before, but not with a transistor between it and the PIR. I guess the PIR can't drive the relay directly.  Thanks.

I'd suggest using a transistor, instead of a relay. Relays are more expensive, and  waste power energizing the coil inside them.

Thanks. Do you happen to know what transistor type I should use for this? I tried using a PNP 2N3906 as recomended at http://www.rason.org/Projects/transwit/transwit.htm, but it didn't provide enough current, only a trickle. I could see the LED lights on the Uno slightly light up, but not quite full power.

Well, I got a 2N2222 NPN transistor to do the job, but I'm not sure if this is the correct solution. When I use this to turn on an Arduino Uno that plays a melody, the power leds on the arduino flicker with each note played. However a multimeter across the circuit only shows it drawing 54mA at most.

A bipolar NPN transistor like a 2N2222 is a relatively poor choice for this, and as a low-side switch creates some substantial complications if the Arduino is connected to anything.


text:
esp8266 deep sleep timer slightly inaccurate?
I'm making a door open timer using a hall sensor and have a wemos d1 mini that uses a deep sleep to sleep for 1 minute after checking the hall sensor state and printing the value on the serial port. I'm using the Arduino IDE to monitor the serial output and have the Show timestamp option enabled so that I could time how long the device is running after it resets.  However, I'm getting output like this:
08:03:26.286 -> ^H⸮ȸ$RKx⸮⸮x⸮I⸮⸮696
08:04:25.454 -> HEA⸮⸮⸮d⸮⸮⸮⸮⸮⸮⸮696
08:05:24.681 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮696
08:06:23.915 -> ⸮DP⸮V⸮l⸮X⸮X⸮H⸮⸮694
08:07:23.178 -> ⸮A⸮K`E⸮M⸮⸮xxE⸮696
08:08:22.406 -> ⸮HlX⸮K⸮I|⸮⸮xE⸮693
08:09:21.703 -> ⸮⸮NI⸮ hlE⸮0⸮⸮E⸮694
08:10:20.978 -> 8H⸮JcD⸮M⸮⸮xxE⸮695
08:11:20.306 -> ⸮⸮NI⸮AhlE⸮ Op⸮⸮696
08:12:19.573 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮539
08:13:18.897 -> ⸮⸮OI⸮AhlE⸮⸮O⸮⸮538
08:14:18.196 -> HEA⸮⸮⸮d⸮⸮⸮⸮I⸮⸮539
08:15:17.561 -> ⸮dG⸮⸮⸮hLJ⸮@h⸮⸮(⸮539

The garbage output isn't what I'm asking about, it's the timestamps being created by the arduino ide. Since I sleep for 60,000,000 microseconds, I would assume that the second value of the minute would be slightly more each time. But as shown above, it becomes slightly less every time, as if it takes less than a minute. So what I'm wondering is if the sleep timer on these devices is not accurate enough to count on this or something else I should be considering like an inaccuracy in the IDE?  I only wanted to measure the uptime so that I could consider it for battery drain considerations, I don't really need a millisecond accurate timer for the functionality of the device.

How to use an external RTC to wake the ESP8266: https://arduino.stackexchange.com/a/91504/78174

A (now 3 year old) GitHub thread suggests using an external RTC if time tracking is of importance.  It also points at a dead NodeMCU document link.  That document appears to have moved.  This document describes the lengths taken to provide a better account for time passage during sleep.  Which, apparently, includes guessing at the sleeping chip's temperature:

Time keeping on the ESP8266 is technically quite challenging. Despite
being named RTC, the RTC is not really a Real Time Clock in the normal
sense of the word. While it does keep a counter ticking while the
module is sleeping, the accuracy with which it does so is highly
dependent on the temperature of the chip. Said temperature changes
significantly between when the chip is running and when it is
sleeping, meaning that any calibration performed while the chip is
active becomes useless mere moments after the chip has gone to sleep.
As such, calibration values need to be deduced across sleep cycles in
order to enable accurate time keeping. This is one of the things this
module does.

Update:
A recent Arduino stack exchange answer goes into detail using a DS3231 Real Time Clock.

Yes a RTC can be very inaccurate. Some RTCs will let you synchronise them.

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


text:
Cannot upload to Leonardo after update to macOS Catalina
I'm not sure this is the right site, but I've spent several hours trying to figure out why I suddenly cannot upload to my Leonardo (actually, a "Pro Micro" with a 32u4) after upgrading to macOS Catalina.
Initially I thought the board was just dead, but I can program it without issues from a Windows machine. I also worked just fine with it a few days ago, before the update to Catalina. Now I'm getting this output:
Arduino: 1.8.10 (Mac OS X), Board: "Arduino Leonardo"

Sketch uses 10226 bytes (35%) of program storage space. Maximum is 28672 bytes.
Global variables use 1000 bytes (39%) of dynamic memory, leaving 1560 bytes for local variables. Maximum is 2560 bytes.

avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_drain(): read error: Device not configured
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type = �
Software Version = .�; Hardware Version = �.�
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader
avrdude: ser_close(): can't reset attributes for device: Device not configured
the selected serial port avrdude: ser_close(): can't reset attributes for device: Device not configured
does not exist or your board is not connected

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

My Mega2560 as well as Due work just fine. I even tried re-burning the bootloader into the Pro Micro using the Mega, which worked fine but didn't solve the issue.
I also tried getting into the bootloader mode, by tapping the reset (actually, using a wire to pull RST to GND) button twice. It changes the error to
Found programmer: Id = ">>> SPI"; type = SSoftware Version = >.>;
Hardware Version = >.
avrdude: error: buffered memory access not supported.
Maybe it isn't a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
Double check connections and try again, or use -F to override this check.

The bootloader trick is not required on Windows, it just works.

In case people are arriving here from search engines, there is an open issue on the Arduino GitHub tracker: https://github.com/arduino/Arduino/issues/9290


text:
Specific noise while using arduino ADC in free running mode
To make an oscilloscope in matlab environment, for data acquisition on arduino side, when inbuilt analogRead() is used, it's working fine, but with very low sampling rate, that aliasing is clearly observed. That too, non-uniform sampling. Thus listing out the drawbacks:

Very slow data rate, even if, sent with 115200 baudrate,
Aliasing
Non-uniform sampling

Thus, to overcome above, ADC in free running mode was used, with 16 as prescaling factor, thus 76.9KHz sampling rate (counting each ADC as 13 clock cycles). Thus, data is uniformly sampled now. Also it is quite fast, because of sampling, and is observed. The only problem now exists is, output has a specific noise. The data being sampled is 50Hz sinusoidal current waveform by current sensor ACS712. It overlays instantaneous current waveform over a bias of 2.5V. Thus, when signal is not present, a constant voltage of 2.5V is observed, thus, 512, because of mapping to 255 range.. 127. But in the case of free running mode, along with 127, 191, 63 only are observed. And it can also be seen that nearly 127 = 63*2, and 191 = 63*3. And when current waveform exists, it's highly distorted, but perceptible that it's not the previous signal of just 127, 191, 63. In the below plot, current is passed since 33.5sec.

I am unable to understand this, structured noise. What may be the reason ? I have once read, last two MSB bits get noisy at this sampling rate, but then how would 127, jump to 191. Why is 63 getting added, subtracted at each instant ?
I understand the reason for non-uniform sampling now is because of Serial.print(), whose interrupts are obstructing the ADC interrupts, but don't understand the reason behind the noise observed.
Following is the code uploaded in arduino. Serial data is read from matlab by fread() function.
long t1=0,ts1=0,ts2=0;
int aval=0, val=0;

void setup() {

 TIMSK0 = 0x00;           // disable timer (causes anoying interrupts)
 DIDR0 = 0x3F;            // digital inputs disabled
 ADMUX = 0x40;            // measuring on ADC0, right adjust, AREF reference
 ADCSRA = 0xAC;           // AD-converter on, interrupt enabled, prescaler = 16
 ADCSRB = 0x00;           // AD channels MUX on, free running mode
 bitWrite(ADCSRA, 6, 1);  // Start the conversion by setting bit 6 (=ADSC) in ADCSRA
 sei();
 Serial.begin(115200);
 t1=millis();
 }

ISR(ADC_vect)
{
 aval = ADCL;
 aval += ADCH << 8;
}

void loop() {
val = map(aval, 0, 1023, 0, 255);
Serial.write(val);
delay(10);
}

I wonder how are the functions like millis() and delay(10) working as you've disabled it's interrupt.

Also, if you want 8-bit data, have the ADC left-adjust the result, don't enable it's interrupt, and Serial.write(ADCH);.

You might want to define aval as volatile.

@KIIV, even though TIMER0 is disabled, millis() was still working fine, but it's not the important problem now. I'll enable it, when I use millis() from now. Thank you, for making me aware of it.

@Edgar Bonet, I have used interrupt to handle ADCL, ADCH registers properly, instead of facing a situation of reading them while they are being written (for I thought, ADC writes into these registers the instant they are obtained at 13th clock cycle). I lean't now, that it was my misconception. It was given in datasheet, "When ADCL is read, the ADC Data Register is not updated until ADCH is read, when right adjusted". I'll try it now. Thank you.

If you use an ISR to retrieve the ADC result, you will need to protect the read of the variable. An interrupt may occur when reading aval in the loop(), as this is a 16-bit value and the read requires several instructions. This may give corrupt values.
void loop() {
  noInterrupts();
    val = aval;
  interrupts();
  val = map(val, 0, 1023, 0, 255);
  Serial.write(val);
  delay(10);
}

Cheers!

You're right, but running an ISR every 16 CPU cycles is a bad idea to start with.

Yes, especially if there is a delay(10) in loop().

but running an ISR every 16 CPU cycles is a bad idea to start with. It is a bad idea to put a slow transmission inside of an isr, not to mention issues from re-entrance of serial.print().

It is very unclear what you are trying to achieve here. You are clocking
the ADC at its maximum frequency, which has it take one reading every
13 µs, and yet you are delaying for 10 ms after sending one
reading through the serial port. So basically your Matlab program is
getting one reading out of every 769 you take.
If you want fast data acquisition with a consistent sampling frequency,
you basically have two options:

clock the ADC as fast as you dare, buffer the data in RAM and, when
the buffer is full, send it to the host computer
set a high baud rate and take the data as fast as the UART can send
it.

The first option allows for faster sampling rates, but only as short
bursts, as limited by the available RAM. Given what you have already
written I assume you want continuous acquisition, and thus the second
option. I also assume you are using an Arduino Uno or similar.
At 115.2 kb/s (actually 117.647 kb/s given the rounding), every bit sent
takes 136 CPU cycles, or 8.5 µs. One byte takes 10 bits
(start bit + 8 data bits + stop bit), i.e. 85 µs.
This means there is no point in clocking your ADC that fast: you can set
the prescaler to 64 and each reading will take 52 µs.
What I would do here is configure the ADC to be triggered by
Timer 1, and have that timer deliver the trigger signal every
1360 CPU cycles exactly. Then,
ISR(ADC_vect)
{
    Serial.write(ADCH);
}

assuming of course you have set the left-adjust mode (ADLAR bit in
ADMUX).
With the ADC and the UART working at the very same frequency, you keep
the UART busy without ever filling the output buffer. If your ADC runs
faster than the UART, the buffer will fill out and your timings will get
nasty. On the other hand, if you are really confident in your timings,
you could skip the Serial managing of that buffer and just do
UDR0 = ADCH in the ADC ISR.

What Serial communication baudrate would 1360 CPU cycles related to, for ADC and Serial to be in sync ?

@WupadrastaSantosh: Assuming a 16 MHz clock (like in the Uno), if you Serial.begin(115200);, the UART will take exactly 1360 CPU cycles per byte.

Not sure what "structured noise" you are referring to but some advices.

Check the datasheet to see adc timing requirement. When not enough time is given, acc results are highly correlated serially.
In the acc isr, make sure that atomicity is preserved.
Isr has its overhead so make sure that it is consistent with your acc speed setting.
If you are using only the msb. You can configure the acc to be left alighened, saving you lots of time and headache.

What I meant by structured noise is that the output which has to be at 127, is reaching to either 191 (1.5127) and 63 (0.5127). Isn't this very exact form of pulses... Like it's pdf has just three values, where as the actual one is 127.

For serially correlated results, check your reference, supply decoupling, input signal conditioning, and acc clock setting, to name a few.

authors: สุภัณศักดิ์ พาสกุล


text:
Input audio from jack to Arduino, and output by
I've never used Arduino but I know a few of its utilities.
I want to input audio from a Jack cable (analog) and be able to send it via Bluetooth, or Wi-Fi, or USB to an Android Phone and being able to print the values (from 0 to 1).
I'm looking for tutorials but I just find the way to make the input but not the output.
Which one would you recommend me of Bluetooth, Wi-Fi and USB?
Thanks.

Yes but maybe I'm using MIDI, then I wouldn't have problems on sampling

Maybe I would like to know the compontents to be used and I will learn on my own :)

The simplest solution: it really depends. There are a couple of things to consider:

Bluetooth would probably be the least professional to impliment. The easiest way to do this is with an app. You can impliment it into your application with this:

Let your own Android application receive data from Arduino by listening to the "primavera.arduino.intent.action.DATA_RECEIVED" intent. This intent will contain the "primavera.arduino.intent.extra.DATA" byte array with the received data. Call getByteArrayExtra("primavera.arduino.intent.extra.DATA") to retrieve the data. Send data to Arduino from your application by broadcasting an intent with action "primavera.arduino.intent.action.SEND_DATA". Add the data to be sent as byte array extra "primavera.arduino.intent.extra.DATA".

Still, that's pretty unprofessional IMHO. There are probably other ways to do this, but Arduino Uno Communicator is the easiest by far that I've seen. The main advantage of Bluetooth is it works without a router and it's very cheap (as far as wireless). I can't remember if it's the HC4 or HC5 chip that is commonly available, but [one of those] can be picked up for around $6. Just connect via serial and issue AT commands.
WiFi would be the most professional. First of all, people hear Wifi and they think Ohh! Shiny! I'm going to buy it! That's just what I've observed in the past, but it may not always be true. WiFi can be done with the TL-WR703N router. This blog post outlines how you can even connect it directly to the Arduino. You can also use an ethernet shield (or equivalence, I've seen breakout ethernet boards built for ~$5). Either way, it's a great way to add 5V WiFi to your Arduino. The only disadvantage is cost and it only works if you're near a WiFi router. If those aren't disadvantages, go ahead with WiFi; it's a great product.
USB is only useful if you want:

Speed
Stability
Portability (i.e. no WiFi Router)

Speed can be eliminated as a need if you only send data every 300 ms or so, depending on what you're doing. For WiFi, it might be best to only go to a webpage when an even occurs (i.e. button pushed on Arduino). Bluetooth and WiFi are stable enough if you're over short distances (and you couldn't go a long way with wires, anyway), and there's not too much interference (don't try at a football game with 50K cell phones... granted, they will be on different bands if using cell service, but Bluetooth may be on).
As far as portability, for the price of an OTG cable for your phone, you'd be better off buying a Bluetooth module for a dollar extra.

Suggestion: go with WiFi unless you need the portability. Consider figuring out WPS so your users can connect to WiFi with a push of a button. I don't know if the TL-WR703N has support for WPS, via serial or not.
Forgot to mention: I don't know everything about your app, but WiFi might have too much latency/overhead for near-instant response. As far as wireless, Bluetooth would have much lower latency AFAIK. (As you can tell, there's no perfect solution here :-))

Exactly I was interested in latency rates ;).
Sorry for not reveal my project, it's kinda game with "music" (not guitar hero, please :D)
Thank you very much, ;)


text:
I'm getting NaN for readings on my DHT22 sensor when using 3v3 pin, but not 5v pin
I have a DHT22 temperature sensor and DS1302 RTC module connected to the 3v3 pins on an Arduino Nano. Both the sensor and the RTC module are rated to work on either 3.3V or 5V, but the recommendation is 3.3V.  For some reason though, when I connect the sensor and RTC to 3.3V power on the Nano, the sensor just returns NaN even though the RTC module works.  When I change the sensor to use 5V and leave the RTC on 3.3V, I get a proper temp and humidity value on the DHT22.  What is wrong?
Turns out the solder joint for the 3v3 pin on the nano was not properly done. I figured this out after I swapped out the nano for another nano and it worked. Resoldering the 3v3 pin fixed the problem.

Sometimes the problem is simply that you didn't properly solder the headers onto the Arduino. You should check to make sure that your solder joints are all good.


text:
MCP7940 RTC Library
I am looking to implement a Microchip MCP7940 real time clock into my sensor data logging circuit that I have based on the Uno. Would the most logical solution be to attempt at changing an existing library to work with this clock (ie RTClib), or to begin from scratch and do the configuration directly in my program?

Have you compared the MCP7940 to another RTC chip for which a working library exists? You'll need the datasheets. The more alike they are, the easier it will be to modify one's library for the other. At the higher levels - the interface functions - there shouldn't be too much difference; you'll need methods to set the clock, read the clock, and maybe 'hack' the clock (start it running in sync with some reference signal after you've pre-set the time). But the devil, as they say, is in the details. If the chips differ much, one library won't help much with the the low-level details of the other.

Looking at the datasheet, it is very very similar to the DS1307. I wouldn't be surprised if the DS1307 library would work for the MCP7940 without modifications. So definitely use an existing library as a starting point.

@JRobert The pinouts of the DS1307 and MCP7940 are identical. The major difference between the two is that the MCP7940 has an alarm output (which is the reason I'm using it over the DS1307). I'd assumed it would be fairly simple to modify a library to work with it. Now it just becomes a question of how long that will take with my limited programming knowledge/experience.

Then you're far better off starting with a working library. You'd always have a known-good state to revert to when you need to. That beats the heck out of every line of code being experimental! You don't say much about your programming experience, but if the library is moderately well documented, you should at least be able to identify what part of the library needs modifying and what needs to happen there. Then, if you need it, it would be relatively easy for someone to guide you from there to working code.

@JRobert My programming experience is assembly on PIC controllers, and directly with the Arduino. I know enough about programming to know that the libraries are constructed using something more in depth than what is being used in the IDE.

Did you ever get your library working?

Yes, I used the RTClib by jeelabs, and added instructions to set and check the alarm function.

In case anyone comes looking for an answer to this question, here is my solution:
I started with the excellent library by jeelabs (link: https://github.com/jcw/rtclib)
To create my new library, I changed a few of the register addresses, and added the few functions that I wanted it to do (set alarm, create an ordinal date, manually adjust the time with user input)
I posted my code to a Git project: https://github.com/crako1t/MCP7940-library-for-logger.git


text:
What is causing my Uno to wake up?
NOTE: this code was working perfectly fine in another program.
I have a simple piece of code that puts the Arduino to sleep. When it is finished and intergrated into my project, it will only wake the processor up when an alarm from an external RTC triggers one of the hardware interrupts.
#include <avr/sleep.h>
#include <avr/power.h>

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

void loop(){
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);        //deep sleep mode
    Serial.println("Device is going to sleep...");
    sleep_enable();        //put device to sleep

    sleep_disable();        //Device restarts here on wake
    Serial.println("Device is awake...");
    delay(1000);        //to slow down serial output
}

In theory, the program should shut down the processor indefinitely because there is nothing available to wake it up.
However, the device continues waking itself up immediately after shutting down.
I have tried attaching the interrupts hoping it was some kind of anomalous watch-dog function. I have tried tying the interrupt pins to +5V and also (in a separate attempt) to GND. Nothing has helped.
What is causing the processor (and/or program) to constantly wake itself up?

sleep_enable() allows the MCU to sleep, but it does not cause it to sleep. Call sleep_cpu() after enabling.

I can't believe I overlooked that, it works perfectly.


text:
Arduino Ethernet Shield: May I connect it to a PC connected to the internet via wifi?
I have an Arduino Ethernet shield.
May I connect it to a machine that´s connected wirelessly to the internet in order to get the arduino into the internet?
Or do I need to connect it only to a router?

Assuming an Ethernet port on the PC, the Ethernet shield can be connected to it using an Ethernet crossover cable:

(source: Wikipedia)
Many recent PC network interfaces have automatic cross-over (Auto MDI-X), with which even a regular (straight) Ethernet patch cable will work.
This merely addresses the physical Ethernet connectivity.
For actually routing IP packets between the Arduino and the rest of the Internet, some software router or software bridge is required to run on the PC. Several open source routing products exist, especially for Linux and FreeBSD, but that is outside the scope of this StackExchange.
Finally, the Ethernet shield does not need a router, it an as well be hooked up to an Ethernet switch or hub.

Note: on Windows you can select both the WiFi adapter and the ethernet adapter and click "bridge connections."


text:
Help with struct variable
I made a struct like this:
typedef struct {
  int color[3];
  int positions[4];
  char init[20];
  void (*fn)();
} buttons;

and a variable like this:
button test[1] =
{
  {{0,0,0},{0,0,100,100},"getSomething",setSomething}
}

In loop() I call test[i].color, test[i].position normally.
Problems start when I want to execute a function.
I made two attemps, one with string and one with a function statement. With the string I have no problems using a strcmp() but it's not what I want.
I need to know how I can store 2 different functions in the struct and how I can execute.
Thanks in advance!

Could you post what you've tried, please, and in what way it didn't work?

Jot answers is what I needed!

What mark was saying is if you post more code people may be able to understand what you are trying to say better and help you faster.
I thought you wanted to store two function pointer in the one struct by what your text says.

The typedef is no longer needed, using the 'struct' with a name declares the type.
// Arduino Uno

struct buttons
{
  int color[3];
  int positions[4];
  char init[20];
  void (*fn)();
};

// Declare the functions here, or use prototyping
void func1();
void func2();

buttons test[] =
{
  { {0,0,0},    {0,0,100,100}, "getSomething",  func1 },
  { {40,40,40}, {50,50,10,10}, "somethingElse", func2 },
};

void setup()
{
  Serial.begin(9600);
  Serial.println("Calling the functions:");

  test[0].fn();
  test[1].fn();
}

void loop()
{
}

void func1()
{
  Serial.println("func1");
}

void func2()
{
  Serial.println("func2");
}

Not needed because what? Because it is C++?


text:
USB D+ D- to Arduino Mega RX TX
Is it possible to directly communicate USB D+ D- to Arduino Mega serial port TX RX?

Actually it is possible with some passive components to get close enough to the USB spec to usually be able to bit-bang the lowest speed version in software.  I believe on the ATmega328 you can do this with fairly arbitrary GPIOs, presumably you can on a mega as well.

Despite the answer to the contrary it IS possible to access USB directly from digital I/O pins. As TX & RX are also standard digtal I/O pins they could be used for this purpose BUT you need dedicated bootloader code to do this and it has inferior performance if a USB to serial converter is available. The eg ADAFruit Arduino Trinket uses this system.

No, D+/- are high frequency USB signals. TX/RX is 5V UART protocol, i.e. compeletely different. But you can e.g. use AT90USB128x processor to avoid 16u2 bridge. The prosessor is not so mighty as 2560 but it's cheaper and simplifies design.

Thanks. I knew it but I was thinking may be arduino mega has an option to go through the 2560 UART. I thought it would be the serial port 0 as it is the port for PC serial monitor.

The Arduino Leonardo has a ATMega32u4 witch also supports USB directly. An entire board might be easier than just a raw chip.

Well, I have few couple of Arduino Mega, so, I don't really need to have a Leonardo I think. :)


text:
NRF24L01+ scanning and connecting to wifi hotspots or creating one
I've seen this video so I think I can connect it through my wifi router to any device. How can I scan for and discover wifi hotspots and then connect to it? Or is there a way to create wifi hotspot of it's own?

It does seem possible, check out this thread on Arduino forums, where cpixip worked directly with the NRF24 SPI interface to accomplish that.
Here is the code he published, in case the link won't be available:
#include <SPI.h>

// Poor Man's Wireless 2.4GHz Scanner
//
// uses an nRF24L01p connected to an Arduino
//
// Cables are:
//     SS       -> 10
//     MOSI     -> 11
//     MISO     -> 12
//     SCK      -> 13
//
// and CE       ->  9
//
// created March 2011 by Rolf Henkel
//

#define CE  9

// Array to hold Channel data
#define CHANNELS  64
int channel[CHANNELS];

// greyscale mapping
int  line;
char grey[] = " .:-=+*aRW";

// nRF24L01P registers we need
#define _NRF24_CONFIG      0x00
#define _NRF24_EN_AA       0x01
#define _NRF24_RF_CH       0x05
#define _NRF24_RF_SETUP    0x06
#define _NRF24_RPD         0x09

// get the value of a nRF24L01p register
byte getRegister(byte r)
{
 byte c;

 PORTB &=~_BV(2);
 c = SPI.transfer(r&0x1F);
 c = SPI.transfer(0);
 PORTB |= _BV(2);

 return(c);
}

// set the value of a nRF24L01p register
void setRegister(byte r, byte v)
{
 PORTB &=~_BV(2);
 SPI.transfer((r&0x1F)|0x20);
 SPI.transfer(v);
 PORTB |= _BV(2);
}

// power up the nRF24L01p chip
void powerUp(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x02);
 delayMicroseconds(130);
}

// switch nRF24L01p off
void powerDown(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)&~0x02);
}

// enable RX
void enable(void)
{
   PORTB |= _BV(1);
}

// disable RX
void disable(void)
{
   PORTB &=~_BV(1);
}

// setup RX-Mode of nRF24L01p
void setRX(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x01);
 enable();
 // this is slightly shorter than
 // the recommended delay of 130 usec
 // - but it works for me and speeds things up a little...
 delayMicroseconds(100);
}

// scanning all channels in the 2.4GHz band
void scanChannels(void)
{
 disable();
 for( int j=0 ; j<200  ; j++)
 {
   for( int i=0 ; i<CHANNELS ; i++)
   {
     // select a new channel
     setRegister(_NRF24_RF_CH,(128*i)/CHANNELS);

     // switch on RX
     setRX();

     // wait enough for RX-things to settle
     delayMicroseconds(40);

     // this is actually the point where the RPD-flag
     // is set, when CE goes low
     disable();

     // read out RPD flag; set to 1 if
     // received power > -64dBm
     if( getRegister(_NRF24_RPD)>0 )   channel[i]++;
   }
 }
}

// outputs channel data as a simple grey map
void outputChannels(void)
{
 int norm = 0;

 // find the maximal count in channel array
 for( int i=0 ; i<CHANNELS ; i++)
   if( channel[i]>norm ) norm = channel[i];

 // now output the data
 Serial.print('|');
 for( int i=0 ; i<CHANNELS ; i++)
 {
   int pos;

   // calculate grey value position
   if( norm!=0 ) pos = (channel[i]*10)/norm;
   else          pos = 0;

   // boost low values
   if( pos==0 && channel[i]>0 ) pos++;

   // clamp large values
   if( pos>9 ) pos = 9;

   // print it out
   Serial.print(grey[pos]);
   channel[i] = 0;
 }

 // indicate overall power
 Serial.print("| ");
 Serial.println(norm);
}

// give a visual reference between WLAN-channels and displayed data
void printChannels(void)
{
 // output approximate positions of WLAN-channels
 Serial.println(">      1 2  3 4  5  6 7 8  9 10 11 12 13  14                     <");
}

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

 Serial.println("Starting Poor Man's Wireless 2.4GHz Scanner ...");
 Serial.println();

 // Channel Layout
 // 0         1         2         3         4         5         6
 // 0123456789012345678901234567890123456789012345678901234567890123
 //       1 2  3 4  5  6 7 8  9 10 11 12 13  14                     |
 //
 Serial.println("Channel Layout");
 printChannels();

 // Setup SPI
 SPI.begin();
 SPI.setDataMode(SPI_MODE0);
 SPI.setClockDivider(SPI_CLOCK_DIV2);
 SPI.setBitOrder(MSBFIRST);

 // Activate Chip Enable
 pinMode(CE,OUTPUT);
 disable();

 // now start receiver
 powerUp();

 // switch off Shockburst
 setRegister(_NRF24_EN_AA,0x0);

 // make sure RF-section is set properly
 // - just write default value...
 setRegister(_NRF24_RF_SETUP,0x0F);

 // reset line counter
 line = 0;
}

void loop()
{
 // do the scan
 scanChannels();

 // output the result
 outputChannels();

 // output WLAN-channel reference every 12th line
 if( line++>12 )
 {
   printChannels();
   line = 0;
 }
}

The pinout seems to match the NRF24 library pinout.
Please note that it seems this project does not implement the WiFi stack, but only check a high enough signal ( > -64dBm) for a given channel.
In order to create a WiFi hotspot, implementing the 802.11 stack is inevitable, and it seems like the Arduino core chip (atmega328) is not suitable for implementing it using software and bit-banging, so a dedicated hardware will be necessary.

I'm using Arduino Mega which has ATmega2560 chip. Do you think wifi stack can be implemented on this? Can you also provide me some tutorial or other helpful links about wifi stack please? I am new to wifi stack thing.

You can read more about 802.11 in wikipedia: http://en.wikipedia.org/wiki/IEEE_802.11 . It seems that a microcontroller running around 16MHz won't do the job. Also, implementing the network stack by yourself is not recommend for beginners. Nevertheless, there is also a nice gateway solution, check out this thread: http://forum.arduino.cc/index.php?topic=187274.0

if I use this ESP8266 module, do you think I can work without implementing any wifi stack?

Looks like this module should work, check out this instructable: http://www.instructables.com/id/ESP8266-Wifi-Temperature-Logger/

Anybody, please check this question of mine. (link) I edited this question now, since no one is answering it, I thought I would post it here.

I believe nRF2401 is low level tx/rx chip working in 2.4GHz band. But it's not WiFi module. To use it as WiFi you probably need implement WiFi stack. I think guy in video set up channel and counting receved data only.

It's all right if i can only send and receive data, all i need is i can search, discover and connect with the nrf module using any wifi enabled device.

The issue is more fundamental than implementing a wifi stack - the nRF24L01 radio does not have the bandwidth and modulation types needed to support wifi.


text:
Arduino 433Mhz weather sensor receiver
I want to monitor the temperatur around the house and outside. I want to save the data to mysql and then create some kind of webapplication that displlays the data. It is pretty easy to find temperature sensors that transmitts over 433Mhz, and I have thought about Telldus tellstick to receive data and store them. This receiver costs about 30 - 40 $ and 10 - 20 $ for each sensor.
But since I just learned that Arduino can be used for everything, I would love to hear more about it.
Can someone please give me an introduction to what I would need to make this solution? The arduino should basicly receive data from 433 Mhz sensors and store it to MySQL.
What woulds be the challanges when doing something like this?

Where is the MySQL server running? A local computer connected over ... or a remote server, or do you wan't an Arduino capable of running MySQL?

I have MySql on NAS on my local network, but I also have an windows pc that's always on that can run MySql

You could use an Arduino with an ethernet shield to store the data to a MySQL server on the local network. See this blog post for an introduction to a library.
The tellstick is designed to be plugged into a USB host, so it doesn't make much sense in combination with an Arduino. You can get a USB host module but it's an expensive solution and you are using way more hardware than necessary.
Instead you could get 433 MHz receivers dirt cheap on ebay, but I'm afraid they only work on one channel, and there are a bunch of channels in the 433 MHz spectrum. So they might not work with the sensors you are talking about.
Another option would be to use eg. Arduino Pro Mini's in combination with a 433 MHz transmitter, powered by a battery. You could get the temperature reading from the internal sensor, or use an external one. The internal sensor takes quite a bit of calibration work to give a precise reading though.
You can get Pro Mini clones on ebay for a few dollars. You would have to dive into sleep modes and such, if you don't want't the batteries eaten away in a short time. To program it, you'll need an FTDI cable, or another Arduino programmed as an ArduinoISP (In System Programmer).
As an alternative to the Pro Mini board you could use a plain AVR chip, but it will be more work.

Okey so the best way to make the temperature sensor is to buy a pro mini and add external sensor, battery and 433mhz sender? Can this be made to work with the tellstick receiver? And can I mount any sensor on this pro mini? Like humidity, barometer, light, volume etc?

The microcontroller on the Pro Mini is the same as on the Uno. You can hook it up to all sorts of sensors. I don't know if it will work with the Tellstick. It might, but you would have to implement a protocol supported by Tellstick yourself. I'm not sure if the cheap 433 MHz modules run on the same frequency (433.92 MHz) as the Tellstick though.


text:
How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation?
I am working on Fall Detection in humans. A system that would raise alarm when a person falls. For this I plan to use acceleration to see if it is a fall and orientation change to reduce false positives. I was trying to get angle of orientation using gyroscope,accelerometer and magnetometer. According to what I have googled I shouldn't use gyroscope alone as when we integrate to get angle the result is not accurate and I should use sensor fusion and filter using kalman filter or complementary filter. I can't use accelerometer  as during a fall the acceleration won't be only from gravity. I am a newbie so I don't know how to proceed. Correct me if I have understood anything wrong till now.

The magnetometer will be very difficult to use because you have no idea what the local magnetic field will look like around the user.
The gyroscope can help you keep track of angular orientation data during accelerations, but unless you know exactly how this is going to be attached to the human it will not help because you cannot orient the relative angles to the subject. A person can fall with or without rotating in the air as well, so I don't see it helping much anyway.
Kalman filters are great, but overkill; you are not doing inertial navigation over long distances, so don't bother. Simple averaging will suffice.
The accelerometer should be able to detect falls by itself. The only way it will ever "Zero out" is in freefall, and if that zeroing is long enough and then followed by a very hard acceleration against the direction of gravity (the crash) you can call it a fall. Unless the person has some kind of engine to produce thrust, or is going so fast air resistance is a factor, there will be no accelerations in the air. Simplely calibrating of the threshold for being in freefall, the time necessary to call it a fall, and the necessary strength of the following crash should be able to detect falls or jumps with almost no false positives.
For instance if you want to track short falls where the object is never fully off the ground, a large dip in acceleration data will still be seen, so just set the "zero" threshold high.

Such system, some even has airbag, has been around in university/research/papers for many years.  Presumably, falling means a marked change in 'data values'. One can easily log some data (accel and gyro) by falling on bed and plot the values.
May you find some inspiration in followings
http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0CEMQFjAC&url=http%3A%2F%2Fcourses.daiict.ac.in%2Fmod%2Fresource%2Fview.php%3Fid%3D2430%26redirect%3D1&ei=Ls_WU5-cOob_8QW3v4KoCA&usg=AFQjCNEDUyJKTNYFCi71rX13RMlxoHL8kg&bvm=bv.71778758,d.dGc
https://www.google.com/search?q=human+fall+detection+system&safe=off&tbm=vid&source=lnms&sa=X&ei=ps3WU6jGMYyE8gWxo4LYCA&ved=0CAoQ_AUoAw&biw=1577&bih=800&dpr=1#q=elderly+fall+detection+airbag&safe=off
Hope it helps


text:
Input a signal from a sensor to an Arduino Due
I'm working with Arduino Due and I have a sensor that outputs a square signal with voltages in the range of 0-5V.
In the Due specs there is a warning that says:
"Warning: Unlike other Arduino boards, the Arduino Due board runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Providing higher voltages, like 5V to an I/O pin could damage the board."
Is it possible to connect it to the board?
Thanks.

See http://arduino.stackexchange.com/posts/418/edit - you need a logic-level voltage converter (e.g.), unidirectional in this case.

This is a tough one. If it was digital IO sensor, a simple level shifter would suffice. However, since it's analog, you have limited options.
The cheapest route (and the easiest) would be to use a voltage divider. They only take two resistors, and they divide linearly. That means 1/2 of 5V would be divided into 1/2 of 3.3V. You can then  use the full range of the Due (be careful not to use 0-1023, as it has a 12 bit ADC: it'll give you weird numbers).
More on voltage dividers. Even more on voltage dividers.
To build one:

From Sparkfun (link at bottom)

That's four different ways to build one. R1 would be 1700 ohms and R2 would be 3300 ohms. Vin would be from the sensor and Vout would be to the Due.