text:
Multiple If statements
I am using following code for my arduino project in which i have to control a dc motor using arduino uno via text messages.
my question is that i have used multiple number of 'If' statements and only one else statement at the last, i compiled this code and gives no error, is it ok to use multiple If statements one after another without using else after each if?
#include <LiquidCrystal595.h>
#include <GSM.h>

GSM gsmAccess;
GSM_SMS sms;
char sendernumber[20];
int Enable_m=11;
int Control_2=12;
int Control_7=10;
LiquidCrystal595 lcd(7,8,9);
void setup()
{
   Serial.begin(9600);
   pinMode(Enable_m,OUTPUT);
   pinMode(Control_2,OUTPUT);
   pinMode(Control_7,OUTPUT);

   digitalWrite(Enable_m,LOW);
   digitalWrite(Control_2,LOW);
   digitalWrite(Control_7,LOW);

   lcd.begin(16,2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Hello");
   lcd.setCursor(0,1);
   lcd.print("Everyone");
   delay(2000);

   while (!Serial)
      Serial.println("SMS Messages Receiver");
   boolean notConnected = true;
   while(notConnected)
   {
      if(gsmAccess.begin("0000")==GSM_READY)
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   Serial.println("GSM initialized");
   Serial.println("Waiting for messages");
}

void loop() {
   // put your main code here, to run repeatedly:
   char c;
   int val=0;
   val=digitalRead(Enable_m);
   if (val==LOW){
      digitalWrite(Enable_m,HIGH);
   }
   if (sms.available())
   {
      Serial.println("Message received from:");
      sms.remoteNumber(sendernumber, 20);
      Serial.println(sendernumber);

      if(sms.peek()=='#')
      {
         Serial.println("Discarded SMS");
         sms.flush();
      }
      while(c=sms.read())
         if(c=='motoroff'){
            analogWrite(Enable_m, 0);
            digitalWrite(Control_2,LOW);
            digitalWrite(Control_7,LOW);

         }
      if(c=='motoronclockwise'){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='motoronanticlockwise'){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,HIGH);
         digitalWrite(Control_7,LOW);
      }
      if(c=='speedhalf'){
         analogWrite(Enable_m, 128);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='speedquarter'){
         analogWrite(Enable_m, 65);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='speed75'){
         analogWrite(Enable_m, 192);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else{
         digitalWrite(Enable_m,HIGH);
         Serial.print(c);
      }
      Serial.println("\nEND OF MESSAGE");
      sms.flush();
      Serial.println("MESSAGE DELETED");
   }

}

A 'list' of if statements should be implemented as a switch/case statement; this is used where a single variable has many possibilities, and allows a 'default' case which does what you think your final else statement does. However, as Majenko says, you can't directly compare strings as your are doing.

@CharlieHanson so i can replace the if's with labels and set the value of the variable equal to the incoming message?

#include <LiquidCrystal.h>
#include <GSM.h>

GSM gsmAccess;
GSM_SMS sms;
char sendernumber[20];
int Enable_m=11;
int Control_2=12;
int Control_7=10;
LiquidCrystal lcd(7,8,9,8,1,2,3,4,5,6);

void setup()
{
   Serial.begin(9600);
   pinMode(Enable_m,OUTPUT);
   pinMode(Control_2,OUTPUT);
   pinMode(Control_7,OUTPUT);

   digitalWrite(Enable_m,LOW);
   digitalWrite(Control_2,LOW);
   digitalWrite(Control_7,LOW);

   lcd.begin(16,2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Hello");
   lcd.setCursor(0,1);
   lcd.print("Everyone");
   delay(2000);

   while (!Serial)
      Serial.println("SMS Messages Receiver");
   boolean notConnected = true;
   while(notConnected)
   {
      if(gsmAccess.begin("0000")==GSM_READY)
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   Serial.println("GSM initialized");
   Serial.println("Waiting for messages");
}

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

   // I chose 160 since that is max size for sms
   char message [160];
   // this fills message with null characters
   memset( message, '\0', sizeof(char)*160 );

   int val=0;
   val=digitalRead(Enable_m);
   if (val==LOW){
      digitalWrite(Enable_m,HIGH);
   }
   if (sms.available())
   {
      Serial.println("Message received from:");
      sms.remoteNumber(sendernumber, 20);
      Serial.println(sendernumber);

      // you used single qoutes properly here
      // single qoutes denote a char which is a single character
      if(sms.peek()=='#')
      {
         Serial.println("Discarded SMS");
         sms.flush();
      }

      // this will add the characters to messages[]
      for(int i = 0; message[i] = sms.read(); i++){}

      // I changed this to double qoutes since you need double
      // qoutes to denote a string literal
      if(strcmp(message, "motoroff") == 0){
         analogWrite(Enable_m, 0);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,LOW);
      }
      else if(strcmp(message, "motoronclockwise") == 0){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else if(strcmp(message, "motoronanticlockwise") == 0){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,HIGH);
         digitalWrite(Control_7,LOW);
      }
      else if(strcmp(message, "speedhalf") == 0){
         analogWrite(Enable_m, 128);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else if(strcmp(message, "speedquarter") == 0){
         analogWrite(Enable_m, 65);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else if(strcmp(message, "speed75") == 0){
         analogWrite(Enable_m, 192);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      // This else will only be executed if the previous if and else if statements are false
      else{
         digitalWrite(Enable_m,HIGH);
         Serial.print(message);
      }
      Serial.println("\nEND OF MESSAGE");
      sms.flush();
      Serial.println("MESSAGE DELETED");
   }

}

So I've made some edits to your code. For example this code 'motoronanticlockwise' isn't correct. Single quotes are used for char data types and double quotes are used for string literals. You should use double quotes since there are multiple characters "motoronanticlockwise". Also as Majenko said you would have to use strcmp() in order to compare c-strings
c-strings are char arrays that have a null terminator '\0'. Also strcmp() returns 0 if the two strings are equal.
Your last else statement will only executed if the previous if statement is false. It seems like you only want it to execute if all of the previous if statement are false. To do this you make the first if statement and then make a chain of if else statements followed by a single else statement. You can have a single if statement with no else or if else statements however, if you want else or if else statements then you need to have an if statement. I've made the necessarily edits to your code already.
Lastly, this part of the program is the biggest problem while(c=sms.read()) This is because sms.read() returns a char so you can only read the sms message one character at a time. To do this properly you should make a character array and store the values returned by sms.read() in it. This can be done like this
char message [160]; // I chose 160 since that is max size for sms
memset( message, '\0', sizeof(char)*160 ); // this fills message with null characters
// this will add the characters to messages[]
for(int i = 0; message[i] = sms.read(); i++){}

I am using a for loop to iterate through message[].
Try the above and get back to me if there are any problems with it.

I apologize for late reply, and thank you for your time to answer the question. I'll check the code on hardware and let you know. Again thanks for you help, I really appreciate that.

sketch_oct16a.ino: In function 'void loop()':
sketch_oct16a:81: error: 'messages' was not declared in this scope
sketch_oct16a:114: error: 'messsage' was not declared in this scope
what does this mean? i verified and this error came up

I screwed up, those are just typos. I edited the code in my answer.

Yeah i thought so, its OK now verified. cheers

Two things:

The else will only be subject to the last if being false, the rest of the if statements are completely separate and can affect the else in no way whatsoever.  To chain them you need if (...) { blah blah } else if (...) { blah blah } etc.
You cannot compare characters and strings like that (and in fact they're not even strings, they're lots of characters squeezed into a single character through the use of the wrong kind of quotes).

So basically no, your whole program there is completely wrong and won't do what you think it will and you need to completely re-thing how it works.
Some tips:

Use strcmp() to compare strings.
If reading strings from serial store them in character arrays not a single character.

You might find this useful:

http://hacking.majenko.co.uk/reading-serial-on-the-arduino
http://hacking.majenko.co.uk/the-evils-of-arduino-strings

So you are saying that i should create an array of strings and then using 'strcmp()' to compare them. Then how would i assign each string a seperate function?

No, I am saying each string should be an array of characters. Google for tutorials on "C strings".

then i have to define each array like i have at the beginning and just refer to it in the conditional statement?

Ask google to show you. It's better at it than me trying to teach you the basics in comments. There's literally a bazillion examples and tutorials out there. Go and read them.

i was going through that link it and its quite useful. thanks.

If you intend each if statement to be executed, regardless of the whether the prior one(s) did, then yes, they do not require else clauses.
If you mean to try each condition until you find one that is true, and execute that one and only that one, then the second and subsequent ifs need to be else ifs. The final one may be just an else, if you want a catch-all clause; or an else if if it is possible that none of the clauses might need to be run.
Update: To execute at most one clause, you need to use if, some else ifs, and maybe a final else.
If you're trying to match strings, you can use an array of strings or use literal strings as you've tried to do. Strings have to be enclosed in double-quotes (") however, not the single quotes you've used. And the variable char c; you tried to use to hold the SMS message is really only one character. You'll need to make it an array of characters such as char c[140+1];,  the size of the longest SMS message + one more for a  zero-character string-terminator. C doesn't directly compare strings as simple variables so == and != won't work here. You'll need to compare them with strcmp().

from all the conditions only one has to be true. so when the string is matched it should execute only that condition and wait for the next message to arrive.


text:
How do you write to a free location on an external EEPROM?
I want to log GPS positions to an external EEPROM over I2C.
For example:
Latitude: 51.0000
Longitude: 4.0000
If I remove the decimal place then each of these addresses would consume up to two bytes each.
My question is: How can I log each new set of GPS data to a new memory address on the EEPROM each time?
Bearing in mind that the Arduino might be switched off between entries.

The trick you are looking to implement here is the ability to look through the EEPROM and say "This is the last place I wrote to - I will write to the next place now."
There's two ways of doing it, the easy way and the right way.
The easy way is to maintain a single address in the EEPROM that says where you wrote to last.  If you are trying to implement some form of wear levelling to extend the life of your EEPROM then this would basically negate it, since that one cell in the EEPROM will wear out before the rest of it and become useless.  So it's really not a good idea although it may sound like it at first.
The right way to do it is to store more information in the EEPROM every time.  Not only do you need to store the data, but also some kind of identifying sequence number.
Say you have 4 bytes of data to write each time.  Add a fifth byte to it.  That fifth byte increases by one each time you write.  Before you write you scan through the EEPROM looking at every fifth byte looking for the "end" of the sequence.
For instance, you may end up with (xx is your data bytes) in hexadecimal:
00: 00 xx xx xx xx
05: 01 xx xx xx xx
0A: 02 xx xx xx xx
0F: 03 xx xx xx xx
14: FF FF FF FF FF

You see that at address 0x14 the nice sequence of numbers breaks.  Therefore your next write must be at that point.  Now, if you then loop through the EEPROM many times after a while, you may end up with something that looks like this:
00: FE xx xx xx xx
05: FF xx xx xx xx
0A: 00 xx xx xx xx
0F: 01 xx xx xx xx
14: 58 xx xx xx xx

You can see a clear sequence here of 0xFE 0xFF 0x01 where they increase by 1 each time (0xFF + 1 = 0x00) so you can see that you have looped through your sequence numbers. You don't care though because it's still just plus one.  Only when you get the jump from 0x01 to 0x58 does the sequence break, so you know where the last write would have been.
There are only a couple of small gotchas here:

You can only use 5*n cells in the EEPROM since the last 5-byte packet of data may not fit within the last bit of EEPROM (say it's a 1024 byte EEPROM you would have room for 204.8 packets - so 204 packets and 4 bytes left over).
You must ensure that you don't end up with exactly 256 packets fitting in the EEPROM before you loop the address - otherwise the sequence won't "break" so you will never know where the last write was after the first loop.

You can divide EEPROM space into entries and provide each entry with a single "used" bit. You could use a separate byte to store it, or reuse a bit from a byte which is not completely used by your data.
Suppose you start with EEPROM willed with zeroes, and you decide that the first byte of each entry holds the "used" bit in the LSb. When you log coordinates the first time, you'll have:
 /---"used"
01 51 00 00 04 00 00
00 00 00 00 00 00 00
 \---"free"
...
00 00 00 00 00 00 00

(of course, you don't have to store GPS coordinates as BCD, it's just an illustration).
Note that as you add entries, it's trivial to keep track of the last one: just check the entries in sequence until you find a "free" one and go back one step. Also note that the first entry is always "used".
This will go on until all your entries are "used":
01 51 00 00 04 00 00
01 52 00 00 05 00 00
...
01 53 00 00 06 00 00

At this point (when you have to write new data but there are no "free" entries), you start writing from the first entry again, inverting the value of the "used" bit:
 /---"used"
00 54 00 00 07 00 00
01 02 00 00 05 00 00
 \---"free"
...
01 53 00 00 06 00 00

(remember that the first entry is always "used"? Thanks to this, it's possible to simply swap the values representing "used" and "free" entries without actually erasing anything).
To sum up, the algorithm is:

read the "used" bit from the first entry
scan entries until the value of the "used" bit changes, or until you reach the end.
to read the last logged data, use the last "used" entry
to write new data, use the first "free" entry. If there are no "free" entries, start from the beginning, inverting the "used" bit.

This seems like the best answer here.  "Dirty" might not be the best word for the currently valid data, though.

@endolith Thanks, I replaced "dirty" with "used" and "clean" with "free".

You could assign the first byte(s) of the EEPROM as the address of the next free location in which to store GPS coordinates, and update it before the Arduino sleeps. At wake-up, retrieve the address.
You could keep the pointer in RAM, too; RAM keeps its contents across a sleep. But using EEPROM would even let you power off the Arduino, and still pick up where you left off after the power-up reset. (Of course, other parts of your program would have to be restart-tolerant as well; I'm just looking at the coordinate storage here).
As an aside, two bytes isn't sufficient to store a GPS coordinate to four decimals unless their range is limited such that you can scale them into [0 - 65535].

Using the same bytes and writing into the same location often will render those bytes soon broken. They have a limited write amount.

The question asks specifically about EEPROM (E2) and many of the answers point out or attempt to address E2's main limitation: limited # of write operations. Not mentioned is E2's slow speed. Its is best suited for storing infrequently modified data such as-built- or setup parameters such device calibration data and features of a device's external operating environment. Its only real advantage over other solutions is that it may already exist on your MCU - Atmega 328, for instance.
The new(er) kid on the block for non-volatile data storage is Ferroelectric RAM - FRAM. Write times are on the order of 30 times faster, at 150ns, and endurance is claimed to be 10^12 writes, or 10 million TIMES the endurance of E2. I've built a data logger that uses a ring-buffer in FRAM to store periodic data samples and write them on request.
The same techniques proposed in the answers for E2 will work equally well in FRAM with the additional advantage that you can ignore the complications meant to work around E2's limited write-endurance.
And by way of disclaimer: I don't sell this this stuff or have any other interest in it. But I do use it and it works like it says on the box.
Adafruit makes these on a breakout board in a couple of variations - size and serial-bus type - that are sold by them and other retailers. The link is for an 8K-byte, SPI-bus board.

source: Stack Exchange

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

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

sort: votes


text:
Arduino with 12 bit DAC (MCP4725) Not Working
I have an Arduino Mega AT2560 and need to have real DAC. I purchased the Sparkfun 12 bit DAC, however I don't think it is working properly.
I am using the Arduino wire library to communicate with the DAC. When I write 0, I am expecting to see 0v from the DAC's OUT pin. However, I see some seemingly random constant voltage. In reverse, when I write 4095 to the DAC I see the same voltage as when I write 0. I expected to see 5v.

Can someone verify that I hooked it up correctly?
Can someone verify the code I am using?

#include <stdint.h>
#include <stdio.h>
#include <Wire.h>

#define MCP4725_ADDR 0x60 // [0000 0110]
/*
* 12 Bit DAC MCP4725 gives a range of 4096 possible values.
*
*/
void setup() {
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MCP4725_ADDR);
  Wire.write(64);            // cmd to update the DAC [0100 0000]
  Wire.write(4095 >> 4);        // the 8 most significant bits...
  Wire.write((4095 & 15) << 4); // the 4 least significant bits...
  Wire.endTransmission();
}

Full scale should be 4095, not 4096.  In hex, 4095 id 0x0FFF, and 4096 is 0x1000.  You do have a range of 4096 possible values, from 0 to 4095.

I updated the code and tried with 4095 and still am not getting 5v.

Why are you left-shifting in the third "write" line? Does your communication protocol communicate in 4-bit chunks or 8-bit chunks?

I am using basically the same operations from the Sparkfun example: https://learn.sparkfun.com/tutorials/mcp4725-digital-to-analog-converter-hookup-guide?_ga=1.73644763.897386268.1444309037

The system uses 8 bit bytes of data.

Sorry I'm late -- I realize this question was asked 8 months ago, but it doesn't look like you fixed it, and I figure others can always benefit (or you might even, if you still want to try).
Your code looks correct (I compared it to the Sparkfun example, and also to the datasheet for the MPC4725).
However, it does look like you're using the wrong address for the part.
(The actual value for the address is not given in the Sparkfun example -- at least, I couldn't find it).
Your line:
#define MCP4725_ADDR 0x60 // [0000 0110]

is wrong in two places:
1) 0x60 is 0110 0000, not 0000 0110
2) According to the datasheet (section 7.2), the address should begin with the device code %1100, and then the address gets appended. So assuming an address of A2 = 0, A1 = 0, and A0 = 0 (default), the value for MCP4725_ADDR looks like it should be 0xC0 or %1100 000x.  If you soldered the address line to Vcc instead of ground, the address should be 0xC2 or %1100 001x.
The x in the address line represents the read/write bit.  If you're trying to command the DAC, it should not be asserted, so the addresses above are correct. If you're trying to read the current value, it should be asserted, which makes your address 0xC1 or 0xC3.
If you have the address wrong, even though the rest is correct, the part will ignore it, so that's probably the issue you're seeing.
Hope this helps someone!

SparkFun's example at https://learn.sparkfun.com/tutorials/mcp4725-digital-to-analog-converter-hookup-guide says: #define MCP4725_ADDR 0x60  //For devices with A0 pulled HIGH, use 0x61 and the same page says "we’ve broken out the address selection pin (A0) to a jumper pad. By default, this pin is pulled LOW to GND" so that indicates 0x60 is correct.

Remember that the (usual) I2C address is composed by a 7 bit identifier and one bit which indicates whether the master is asking for a write or a read operation. The 7-bit address is 0x60; the byte sent on the bus will be 0xC0 or 0xC1, depending on the operation. Arduino's function expects the 7-bit address and the datasheet provides the byte to be transmitted..

you want to make sure that there are pull-ups on the SCL/SDA lines;
you want to make sure that the address is correct. some routines use 7-bit notation for that, and others use 8-bit notation for that. end of the day, you want the transmission to be 0xc0 | (A2:A1:A0:R/W). so check the write.write() and see what it expects. I suspect that it expects 0xCx, rather than 0x6x.

having said that, here is your code running on an uno, with the dac configured as per sparkfun spec.

so I think it is fair to say that the code is ok but something happened on your end that prevented it from working.

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


text:
error: expected primary-expression before ',' token
I'm gettng an error "error: expected primary-expression before ',' token" in the following line of code - I have initialized an array with 220 ints. What am I doing wrong here?
const PROGMEM int P7Val[] = {1635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,12601635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,1260,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180,,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180};

#include using namespace std; class sample { int x; public: int get_val(int a); void show_val(); }; int sample::get_val(int a) { x=a; } void sample::show_val() { cout<<" "<<x; } int main() { sample obj[3]; for(int i=10;i<13;i++) { obj[i].get_val(int a); } for(int i=10;i<13;i++) { obj[i].show_val(); } return 0; }

Two things:

You have a comma missing: 1260,12601635,1635,
You have an extra comma: 1180,1180,,1255,1255

If you reformat your list into a nice regular table (say 10 entries per line) across multiple lines these things instantly become apparent.


text:
Can I run ESP8266 via Arduino using the PWM pins?
First question: Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3 V ESP8266?
Second question: Can we also use these PWM pins as software serial pins i.e. they will be sending instructions at 3.3 V?

First question, Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3v ESP8266?

No. The ESP8266 draws far too much current (in excess of 200mA) to use anything other than a proper supply.

Second question, Can we also use these PWM pins as Software serial pins i.e. they will be sending instructions at 3.3v?

We'll drop the "also", since we've decided that you're not doing that.
You can use SoftwareSerial on any GPIO pins you like, provided the RX pin supports pin change interrupts.

and... the answer to the "sending instructions at 3.3V" will also be... No! setting the output voltage to 3.3V in a PWM output means to tell the board to send a series of 5V pulses so that, IN AVERAGE, the voltage is 3.3V. see PWM on wikipedia for more info

Dont forget: Sending a 5V signal via serial connection to your ESP will destroy him !!! Use two resistors (2 * 10k) to divide your voltage (will work with 9600 baud)


text:
Arduino Interface with Serial device and LCD display
I want to connect my Arduino UNO to a serial device that once powered displays signature numbers. I want to then display those numbers on an LCD display. I have my 16x2 LCD wired correctly and it works fine even when I use the SerialDisplay example code from the library.
My questions are:

Can I use a USB to TTL serial cable to connect the RX/TX pins of the serial device to the TX/RX pins of the arduino?
The two numbers are more than 16 characters. How can I cut the numbers down and then display the two numbers on two seperate lines of the LCD display?

Let me know if I should provide further details.

You can only use a USB serial converter with something that is a USB host.  Watch out for mismatched voltage standards when directly connecting logic serial lines.  An easy way to split moderately consistent strings is either to count characters or look for a specific character you want to split on.

If the device is serial and you want to connect it to the Arduino serial port, why would you use a usb-to-serial converter?
For a serial to serial connection, you have to connect TX, RX and GND.
This is the bare minimum for bidirectional communication, if your device is really read only, you can use just the TX and GND.
it depends how you receive data from your "serial device" - btw, what is it? If the data comes as either ascii or individual characters, then it's easy: treat them as strings and display them separately. If the numbers arrive in binary format, you have to perform the conversion to string.

Questions like this should have attached at least a snippet, if not all, of code.

That's true! All I need is to connect TX of the device to the RX of the arduino and vice versa. I'm a newb. It's a handle of a medical device that I'm working with for a bionstrumentation school project.
Also, I used a USB to TTL serial cable to see how the data is transmitted on the terminal on my computer and it looks like the data comes as individual characters. I was thinking to display them as strings too.
I don't have much code yet apart from code that just gets input from the serial monitor. Thanks.


text:
How does this code move the bird sprite in this sketch?
I'm teaching this sketch in my class. I understand most of the sketch and can see the class that makes the bird move, but I still don't quite understand how the code makes the sprite "move." I can also see what generates the Pipes but I don't how the code creates them or randomizes them.
Here is the code for both:
Bird
class Chym {

private:
  int frameCount;
  int x;
  int y;
  int deltaIde;
  int delayFrame;

  int jumpCount;
  int maxJumpCount;
  int moveSpeed;

  bool _isDead;
public:
  void respawn() {
    x = 24;
    y = 20;
    deltaIde = -1;
    moveSpeed = 1;
    jumpCount = 0;
    _isDead = false;
  }

  Chym() {
    frameCount = 0;
    delayFrame = 0;
    maxJumpCount = 20;
    respawn();
  }

  void render() {
    if (frameCount < ANIM_FRAME / 2) {
      display.drawBitmap(x, y, flappybird_frame_1, 16, 12, 1);
    }
    else {
      display.drawBitmap(x, y, flappybird_frame_2, 16, 12, 1);
    }
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {
      y += deltaIde * moveSpeed;
      delayFrame = 0;
    }

    if (y > 35) {
      _isDead = true;
    }

    frameCount++;
    if (frameCount >= ANIM_FRAME) frameCount = 0;
  }

  bool isDead() {
    return _isDead;
  }

  void die() {
    _isDead = true;
  }

  void cancelJump() {
    jumpCount = 0;
    flyDown();
  }

  void flyUp() {
    if (jumpCount < maxJumpCount) {
      deltaIde = -1;
      moveSpeed = 3;
      jumpCount++;
    }
    else {
      flyDown();
    }
  }

  void flyDown() {
    deltaIde = 1;
    moveSpeed = 1;
  }

  int getX() {
    return x;
  }

  int getY() {
    return y;
  }

};

Pipe
class Bar {

private:
  int x;
  int y;
  int delayFrame;
  int moveSpeed;
public:
  Bar() {
    delayFrame = 0;
    x = 0; y = 24;
    moveSpeed = 2;
  }

  void setPos(int sx, int sy) {
    x = sx; y = sy;
  }

  void render() {
    display.drawBitmap(x, y - 30, bar_top, 8, 20, 1);
    display.drawBitmap(x, y + 10, bar_bottom, 8, 20, 1);
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {

      x -= moveSpeed;
      if (x < -10) x = 95;

      delayFrame = 0;
    }
  }

  int hitTest(int tx, int ty) {
    int hitX = ((tx >= x - 16) && (tx <= x))?1:0;
    int hitY = ((ty <= (y - 10)) || (ty + 12 >= y + 10))?1:0;
    if (hitX != 0) {
      return hitY;
    }
    return 0;
  }

};

https://www.youtube.com/watch?v=04cY78Y2d3g

This part of your code is what changes the sprite's y-value.
y += deltaIde * moveSpeed;

When you click the "jump" button or when the bird falls the y-value is changed to reflect either an upward movement or a downward movement. When your render() method is called the bird will either be drawn higher up on the y-axis (it's flying) or lower on the y-axis (it's falling).
As for the bars, if you watch closely in the video you can see that they aren't actually randomized.
Compound Assignment Operators
+= is the "plus assign" operator. It adds whatever is on the right side to the variable on the left side. Here is a table of other compound assignment operators: https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound_assignment_operators
int x = 5;
x += 2; // equals 7; equivalent to x = x + 2;
x = 5;
x = x + 2; // also equals 7; equivalent to x += 2;

What does the += mean?

@GabeRuiz, it was said in the same post:"x += 2; // equals 7; equivalent to x = x + 2;"

@Avamander if you'll notice the post was edited after my comment to include the answer to my second question, but thank you for pointing it out.

@Chris, thank you for the link. It has helped a lot.


text:
Arduno Uno voltage in via VIN pin or DC power?
I have an Arduino UNO. It has VoltageIN on a pin. Is there any difference between powering my UNO through VIN or powering it through the DC port?
The docs only say this,

5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

So it seems to imply VIN/USB/DC in all go through the voltage regulator? Is there any difference then?
Is there any advantage to running a variable power supply through an adapter like this:

Or should I just go through VIN?

What do the technical documents (data sheet) say? If you haven't found one, do try.

@Andyaka just updated the question 12 seconds after you said that.

Instructions seem clear enough but I have no idea what relevance the picture is. Hint - I don't need to know.

DC Jack has a Reverse Protection Diode, that drops 0.7V at usable currents. The VIN does not. Both go through the on board LM7805 or similar linear regulator. The USB does not, but it does go through a P-Channel Mosfet used to switch between USB and DC/VIN power before connecting to the 5V rail. The 5V pin bypasses the regulator, Diode, and P-Channel Mosfet completely.
The advantage of the DC jack is that the Reverse Protection Diode is used, preventing reverse voltage problems if you wire it wrong.

It's odd/cheap that they didn't put a MOSFET-based reverse polarity solution. I guess they had to cut corners somewhere to meet the target price.

If you have a "variable power supply" just set it to 5.00v and connect to the 5v pins.  Eg like the this http://blog.unixbigot.id.au/2015/10/make-5-volt-battery-supply-for-any.html?m=1

The post you linked to seems to be talking about batteries and a voltage regulator, rather than connecting a variable power supply.

@NickGammon yes, but it's the same connection point.


text:
Why does my analogRead work on Teensy but not Arduino Uno?
I have successfully made a voltage measurement circuit on my Teensy 3.1 that reads a voltage coming out of digital pin 0 set high and coming back into an analog pin A0 to read voltage.
Basically:
int timer = 100;
int ColA = 0;
int Output;

// Setting digital pin functions

void setup()
{
  Serial.begin(38400);
  pinMode(0, OUTPUT);

}

// Program

void loop()
{
  digitalWrite(0, HIGH);
  delay(timer);
  Output = analogRead(A0);
  Serial.println(Output);
  delay(timer);
}

It works fine with my circuit on a Teensy 3.1 running 3.3v however when i run this code on an Arduino Uno running 5v wired exactly the same way I just get this print out of numbers that cycles back and forth from ~128 down to 0 and back constantly.
Any insight on the differences here would be great. I need the 5v micro-controller to run a 4051 multiplexer!

What happens if your remove the digitalWrite from the loop and put it in setup? And do you have an oscilloscope? That'll tell you what electrickery is happening.

If you're still using D0 as your output on the Uno then yes you are doomed to failure.
D0 and D1 are the serial port. You are using that to communicate with the PC. You cannot use them for any other purpose at the same time.
Pick a different IO pin to be your voltage source.


text:
Stuck on upload
I just bought the SmartEverything FOX Board which is Arduino compatible http://www.smarteverything.it/wp-content/uploads/2015/10/SmartEverything-User-Guide-Ver-1.01.pdf and simply tried to get started with it.
My OS is Ubuntu 14.04, my laptop DELL XPS 13 bought in 2014
I cannot upload sketches on it, when I try, it gets stuck on uploading, whether it is a basic script (blinkRBG) or even the default one with empty setup and loop methods, my laptop processor keeps running at 100% and nothing happens.
The board does not do anything, tx/rx leds do not flash.
I can access to it with a Windows 7 laptop  (UPDATE: and another UBUNTU laptop) from a friend, I could upload the basic blinkRGB sketch. If I try to upload from my Ubuntu laptop after, it does erase the contents and stop the blinking but nothing follows.
When I try to upload, I only get the compiling logs:
Quote
Sketch uses 13,368 bytes (5%) of program storage space. Maximum is 262,144 bytes.

I could still upload sketches to another board from my Ubuntu laptop: to an Arduino micro.
I am connecting directly from my board to my laptop through USB 3.0, I don't have USB2.0 plugs on my laptop, and I currently don't have any programmer device.
I tried with different versions of arduino IDE (1.6.4 1.6.5 nightly), same issue every time.
The IDE sees that my board is connected on /dev/ttyACM0
I tried to run in command line but it gets stuck as well
Quote
/home/jcharlet/.arduino15/packages/arduino/tools/bossac/1.6-arduino/bossac --port=ttyACM0
I've been googling the world but could not find anything, could anyone help me to troubleshoot it please?

Have you added yourself to the dialout group? $ sudo usermod -a -G dialout jcharlet then log out and log in again or reboot.

thank you Majenko for your answer, but I already tried it, and it did not work.

Enable verbose upload log from the IDE's settings.

Moved to another board more suitable to our needs, but @sm4rteverything (Twitter) gave us the following solution (not tested):

This is a known bug of the bootloader.
to fix this U need to download the one i attach in this email with the
  ATMEL-ICE tool. http://www.atmel.com/tools/atatmel-ice.aspx
Copy the attched file under: \Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme
  (Linux) C:\Users\\AppData\Roaming\Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme
  (Windows)
last follow these three simple step Connect the ATMEL-ICE on the SWD
  J1 connector (pin 1 on top-rigth , the pin on eon cabel is the red
  one)

select on Arduino IDE to connect to ASME via atmel-ice (board menu)
  tool->burn bootloader

Please clarify if your answer indicates a solution to the problem. If so, please accept it by clicking on the "tick" icon next to the answer. This indicates to other users that the answer is useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!

marked as solved


text:
Serial print and sensor readings halts
I'm trying to write a state machine for my robot.
While the robot is moving around I would like to read the values of the sensors, but after some time the reading stops working.
For the first half hour it's ok, then I don't know what changes.
It looks like it halts when jumping from one state to another, or when the sensor value has a big jump...
I tried to move the debugOutput function inside the main loop, but the behavior is the same..
In addition to the serial halting, also the state machine itself seems to stop working good, since even if the sensor value change, the state is not updated..
Could you please help me with this?
Thanks a lot!
Here is the code:
    // motor one
    int enA = 13;
    int in1 = 12;
    int in2 = 11;
    // motor two
    int enB = 9;
    int in3 = 10;
    int in4 = 8;

    int sens1 = 0; //ingresso sensore bobina 1
    int sens2 = 1; //ingresso sensore bobina 2

    float soglia_barriera_norm = 1.5;
    float soglia_barriera_scarico = 390;

    // define the states
    #define DRIVE_FORWARD     0
    #define TURN_LEFT         1
    #define RADDRIZZA         2
    #define SCARICO           3 //Scarico cerca il filo

    int state = 3; //to start from state 3

    void setup()
    {
      // set all the motor control pins to outputs
      pinMode(enA, OUTPUT);
      pinMode(enB, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);
      pinMode(53, OUTPUT);
      Serial.begin(9600);

    }

    //------------------------ LETTURA SENSORI ---------------------------
    //average of n readings

    float sensorReadDX(int n_medie) {
      int i, temp = 0;
      for (i = 0; i < n_medie; i++) {
        int sensorValue1 = analogRead(sens1);
        temp += sensorValue1;
      }
      float volt = (temp / n_medie);
      return volt;
    }

    float sensorReadSX(int n_medie) {
      int i, temp = 0;
      for (i = 0; i < n_medie; i++) {
        int sensorValue2 = analogRead(sens2);
        temp += sensorValue2;
      }
      float volt2 = (temp / n_medie);
      return volt2;
    }

    float differenza(float volt1, float volt2) {
      float D = volt1 - volt2;
      return D;
    }
    //----------------------------------------------------------------------

    //----------- MOTOR MOVEMENTS ---------------------------------------------

    void moto_dx_forward(int vel) {
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      analogWrite(enA, vel);
    }

    void moto_dx_backward(int vel) {
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      analogWrite(enA, vel);
    }

    void moto_sx_forward(int vel) {
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);
      analogWrite(enB, vel);
    }

    void moto_sx_backward(int vel) {
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enB, vel);
    }

    // to stop motors
    void moto_dx_stop() {
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      analogWrite(enA, 0);
    }

    void moto_sx_stop() {
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      analogWrite(enB, 0);
    }

    //---------------------------------------------------------

    void debugOutput() {
      Serial.print(millis());
      Serial.print("\t");
      Serial.print(sensorReadSX(50));
      Serial.print("\t");
      Serial.print(sensorReadDX(30));
      Serial.print("\t");
      Serial.println(state);
    }

    void stateMachine() {
      float sensSX = sensorReadSX(30);
      float sensDX = sensorReadDX(30);

      if (state == DRIVE_FORWARD) {
        debugOutput();

        if (sensSX <= soglia_barriera_norm || sensDX <= soglia_barriera_norm) {
          moto_dx_forward(255);
          moto_sx_forward(255);
        } else {
          state = RIMBALZA;
        }
      }

      else if (state == SCARICO) {
        debugOutput();
        if (sensorReadSX(50) < soglia_barriera_scarico){ //|| sensorReadDX(20) < soglia_barriera_scarico) {
          moto_dx_forward(255);
          moto_sx_forward(255);
        } else {
          moto_dx_stop(); //ferma i due motori e poi raddrizza
          moto_sx_stop();
          state = RADDRIZZA;
        }
      }

      else if (state == RADDRIZZA) {
        debugOutput();
         while ( sensorReadDX(30) <= 490){
          //ruota su se stesso
          moto_sx_stop();
          moto_dx_forward(255);
        }

        moto_dx_stop();
        moto_sx_stop();
      }

    }

    void loop() {
      stateMachine();

    }

Try outputting the current state.  Is there any logic which can change from the RADDRIZA state to any other?  It sort of looks that it could become stuck there with both motors off.

no, at the moment when RADDRIZZA is finished it stays there with motor stopped.. however I found the problem, it stopped outputting because during the while ( sensorReadDX(30) <= 490) it doesn't execute what's outside the loop!


text:
Algorithms to reduce measurement error from analogue sensors
When reading analogue sensors - e.g. load cells, accelerometers - via a microcontroller's Analogue to Digital Converter, there are many sources of potential measurement error including:
a) Warm-up time for electronics
b) Mechanical inertia and resonance
c) Spurious random readings (due to e.g. vibration, electrical interference).
My current software hack for a) and b) is to simply add a suitable time delay before reading the sensors; however there must be a more robust way of detecting and screening for resonance...
My hack for c) is to take the mean of a given number of consecutive readings, but discard any individual readings which exceed a given percentage range from the current mean (pseudocode example below). The trouble with this approach is that it requires an inital `baseline' sensor reading, and if this happens to be spuriously high or low, it can cause subsequent correct readings to be rejected.
Another approach might incorporate a weighted moving average, but this would still be skewed by spurious random readings.
Are there any robust and elegant approaches / algorithms for the above which are commonly applied in commercial devices (e.g. domestic or laboratory weighing scales) that I could include in my code to improve the accuracy and reliability of measurements?
Many thanks in anticipation
// Take mean of multiple sensor readings excluding outliers:

# define SAMPLES 100 // number of samples to take mean of
# define TOLERANCE 0.1 // % range of allowable deviation
                       //between current mean and new values, expressed as decimal

n = 1; // loop variable
total = analogRead(analogPin); // Running total for calculation of mean & baseline reading
mean = total; // mean of all current data

while (n < SAMPLES) {
    new = analogRead(analogPin);
    if (new < (1 + TOLERANCE) * mean) and (new > (1 - TOLERANCE) * mean){
        total += new; // if new reading is within range, calculate new mean
        n += 1;
        mean = total / n;
        }
    // (else ignore new reading)
}
Serial.print mean;

You might want to investigate Standard Deviation and similar statistical models: https://en.wikipedia.org/wiki/Standard_deviation

Thanks Majenko - I'm aware of use of SD in statistical analysis of data.   Is this used in commercial algorithms for reading sensors with microcontrollers in real time though?

I use something very similar to what you are proposing to measure RSSI in an antenna pattern generator.  Say you have an array of 16 samples.  You start filling the array with samples but don't actually output a result until the array is full.  This will give you a startup period of 16 samples where no decisions are made.
After the array is loaded, set a semaphore that indicates that results may now be used to make decisions.  New samples overwrite the oldest sample in a recirculating buffer.  You will now get decision outputs at the same rate as the sample rate with a lag, i.e. when the inputs go to zero abruptly, it will take 16 sample periods for the output to catch up.  I call this a 16 sample rolling average.
For relatively stable inputs, simply take the mean of the array and output that result.
For inputs that are glitchy such as RSSI take the mean of the array and then find the sample(s) that is (are) the farthest away from that mean.  You then recalculate the mean without that sample included.  Note:  Do not discard that sample, simply ignore it for that cycle.  I call this a 15/1 outlyer average.  For my RSSI measurements, this gives me the equivalent of a 48 sample rolling average.  You can do an 8/1, 16/2 system etc requiring 9 and 18 samples per sample respectively, tuning the counts to your particular application.  I am able to get nearly anaechoic chamber results in the middle of a radio noisy office.
Again, note that the outlyers are NEVER discarded as they may represent a real trend.

... and here's my minimal working example for the Arduino. Feel free to adapt it for your own requirements, and please post any improvements or corrections to my script; or any alternative algorithms for the above.
Just noticed that my approach of using the SD to define and exclude outliers is a little more (? unnecessarily) complex than John's algorithm, which defines outliers in terms of the highest and lowest values from the mean; but both methods seem to work nicely.
Cheers!
#define BUFFER 5 // Buffer size (number of readings to use in rolling Mean)
#define SENSORPIN 3 // Analogue input pin from sensor
int data[BUFFER]; // Make an array of appropriate size for Buffer

void setup() {
  pinMode(SENSORPIN, INPUT);

  // Fill buffer with initial data
  int n = 0;
  while (n < BUFFER) {
    data[n] = analogRead(SENSORPIN);
    n++;
  }
}

void loop() {
  // Calculate Raw Mean & SD
  float datasum = 0;
  float diffsum = 0;
  for (int n = 0; n < BUFFER; n++) {
    datasum += data[n];
  }
  float mean = float(datasum / BUFFER);
  for (int n = 0; n < BUFFER; n++) {
    diffsum += ((data[n] - mean) * (data[n] - mean));
  }
  float sd = sqrt(diffsum / (BUFFER - 1));

  // Recalculate Corrected Mean only using data within range +/- 1SD of Raw Mean
  if (sd != 0) {      // Avoid divide by zero error if sd = 0
    float newSum = 0; // Sum of readings within acceptable range
    float newLen = 0; // Number of readings within acceptable range
    int n = 0;
    while (n < BUFFER) {
      if ((data[n] < (mean + sd)) and (data[n] > (mean - sd))) {
        newSum += data[n];
        newLen ++;
      }
      n++;
    }
    mean = newSum / newLen; // Corrected Mean
  }

  // Add your code here to do stuff with variable float 'mean' = the (Corrected) Mean

  // Read new sensor reading, append to buffer and delete oldest reading
  for (int n = (BUFFER - 1); n > 0; n--) {
    data[n] = data[n - 1];
  }
  data[0] = analogRead(SENSORPIN);
}

Thank you John! Your solution is what I was looking for: it resolves my conflict between preserving all the data and excluding the skewing effects of outliers; is simple enough to implement on a microcontroller; and seems to work perfectly. I'm guessing that the rolling mean will also smooth out any potential swings due to mechanical resonance.
I know this is an Arduino forum, but I find it quicker and easier to write interactive code in Python, so I've written a crude `test bed' implementation of your algorithm in Python so that I could get a feel for how it works in practice, with user keyboard input simulating real-life sensor readings. I've avoided any libraries or esoteric Python syntax, so this should be easy to adapt to C++/Arduino. I'm posting it here in case it is of interest to the community.
I've used the formula for Sample Std Deviation (n-1) rather than Population SD (n) which I think is correct in this context, but please let me know if not:
in LaTeX: $SD=\sqrt{\frac{\sum_{(i=1)}^{n}(x_{i}-\bar{x})^{2}}{n-1}}$
If there are any other algorithms or solutions to my post, I'd be very interested to know. Thanks again.
#===================================================
def SampleSD(data,bufLen):
    datasum = 0.0 # NB declare as float to prevent integer rounding error
    diffsum = 0.0 # NB declare as float to prevent integer rounding error
    for m in range (0,bufLen):
        datasum += data[m]
    mean = datasum / bufLen
    for m in range (0,bufLen):
        diffsum += (data[m] - mean) ** 2
    sd = (diffsum /(bufLen-1)) ** 0.5
    print "n: %d\tSum: %f\tMean: %f\tSD: %f" %(bufLen,datasum,mean,sd)
    return mean,sd

#=====================================
def addData(data,bufLen):
    print "\n------------------------------"
    new = input ("Sensor reading: ")
    for m in range(bufLen-1,0,-1):
        data[m]=data[m-1]
    data[0]=new
    return data

#======================================
bufLen = input ("Buffer Length: ")
print
data = [0] * bufLen # Declare an array of suitable length in Python
n = 0

# Fill buffer with initial data
while n < (bufLen):
    new = input ("Initial sensor reading: ")
    data[n] = new
    n +=1
print "\nBuffer initialised."
print "Data: ",data

while True:
    addData(data,bufLen)
    print "Data: ", data
    mean,sd = SampleSD(data,bufLen)
#===========================================
# Recalculate Mean only using data within range +/- 1 SD of mean
    if sd != 0: # Error trap to avoid divide by zero error if sd = 0
        print "\nChecking for outliers:"
        newSum = 0.0 # NB declare as float to prevent integer rounding error
        newLen = 0
        n=0
        while n < (bufLen):
            if ((data[n] < (mean + sd)) and (data[n] > (mean - sd))):
                print "Data [%d] = %d Included" % (n, data[n])
                newSum += data[n] # sum of data which is within +- 1SD of original mean
                newLen += 1 # number of data whic are within +/- 1SD of original mean
            else:
                print "Data [%d] = %d Excluded: Out of range" % (n, data[n])
            n+=1
    CorrMean = newSum / newLen
    print "New n: %d\tNew Sum: %f\tCorrected Mean: %f" %(newLen,newSum,CorrMean)


text:
Can I reuse crystal frequency of Arduino?
If I use some IC which requires clock frequency like 16MHz, can I take one from Arduino?
Or this it too high frequency to travel to neighboring board?

Set the CKOUT fuse to 1, will give you the clock output. And you have to set PORTB0 to an output (pinMode(8,OUTPUT);). You probably don't want to use to long of a trace/wire.

The expense of properly sending a clock off-board will be greater than generating a new one over there, so only do it if your signals must be synchronized.

Possible duplicate of Arduino constant clock output

am dividing arduino clock frequency from 16Mhz to 8Mhz but am getting spike in clock signal how can i reduce that

The frequency is important. Make sure they are the same or it will probably not work.

Yes but you need to know what you are doing.  You will need a clock driver and possibly a clock receiver depending on the devices you select.  Then you need to modify both boards voiding any possible warranty.
The best answer is NO!

I don't agree with that. I don't see any problem with using the arduino clock to clock another chip. The whole point of buying an Arduino is experiment and learn! Screw the warranty. I personally have done it often. Its not that hard.

I disagree. Why is it necessary to change the board given Gerben's comment? And I dunno understand, why you are referencing to warranty. Nobody will reasonably try to claim a warranty for a 15€ device where a failure is almost always user generated. If someone over here ever has successfully claimed a warranty for an arduino, let him now speak...

Why not download this application from TI: http://www.ti.com/lit/an/scaa082a/scaa082a.pdf Then download: https://www.elprocus.com/crystal-oscillator-circuit-and-working/ after you read them and understand them you will know why I answered as I did. Note this is an open ended question without the necessary specifics to do a proper design. Your solution may work but what happens if yo build thousands of them?


text:
Arduino constant clock output
I am controlling an ADC with my Arduino Uno. I would like the clock of the ADC to be the same frequency of the Arduino.
Is there any way that I can have a constant clock output from one of the Arduino pin ?
Thanks,
Liam

Sounds a lot like this question

Which ADC? If you are reading via SPI, than the clock speed is typically the SPI clock speed, default is 4 MHz, and 8 MHz, 2 MHz, 1 MHz, 512KHz, 256KHz, 125 KHZ and I think 62/5KHz are selectable as well.  If you just want a constant, free running clock, then 16 MHz is available at the CKPOUT pin with a change to Low Fuse byte bit 6: The CKOUT Fuse allows the system clock to be output on PORTB0 [on a '328P chip]. Refer to Clock Output Buffer section in the System Clock and Clock Options chapter for details.  Ah - 2015 - well, maybe this will come in handy for someone.

This outputs 8 MHz on pin 9:
#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

How can add a prescaler?

You change the prescaler bits. You can look at the datasheet or my cheat sheet here:

You may not need a prescaler, depending on the frequency. Change OCR1A to some number between 0 and 65535 to slow it down.
Edit by Edgar: I tested the OCR1A values with an oscilloscope. At the end of this answer are the frequencies.

you use TCR1A, COM1A0 and similar variables. Are these always present and implicitly defined when running code on the ATmega

Registers like TCCR1A and so on are defined in files which are automatically included by the Arduino IDE. If you use another toolchain they may be also automatically included. The start point is:
#define <avr/io.h>

Inside that file it checks your processor type (from a symbol passed to the compiler) and then includes an appropriate sub-file. Inside those files are defines which relate the register names to their address in the address-space of that particular chip. For example:
#define TCCR1A _SFR_MEM8(0x80)

The _SFR_MEM8 basically generates a pointer to a volatile address (because it might change without the compiler knowing it) and then dereferences that variable.
Notice that the number 0x80 in that define agrees with the number shown on my chart.
Underneath that define in the appropriate file are also the bit positions for the bits in that register, like this:
#define TCCR1A _SFR_MEM8(0x80)
#define WGM10 0
#define WGM11 1
#define COM1B0 4
#define COM1B1 5
#define COM1A0 6
#define COM1A1 7

Secondly, do I correctly understand that the output pin is defined in TCR1A, Output A and Output B, to be on Digital Pin 9 and 10 respectively?

Yes, in effect. The datasheet says that if you set the appropriate bits in TCCR1A (note the spelling) then OC1A (board pin 9 on the Uno) or OC1B (board pin 10 on the Uno) will be unchanged/toggled/cleared/set depending on the bits. You can find these names on the datasheet for the Atmega328P (and other devices) and then use the Arduino schematic to find which processor pins are connected to which board pins.
Atmega328P datasheet snippet:

Uno datasheet snippet:

Why do you set it to "Toggle" rather than "Set"?

Because every time the counter matches I want to flip the pin. That is, on/off/on/off etc.

What does CTC stand for?

Clear Timer on Compare. What this means is that (unlike other modes) once the compare match is made, the timer is cleared, thus it starts counting up from zero again.
Edit by Edgar: OCR1A values and frequencies
Value, MHz
 0 8.00
 1 4.00
 2 2.67
 3 2.00
 4 1.60
 5 1.33
 6 1.14
 7 1.00
 8 0.889
 9 0.800
10 0.727
11 0.667
12 0.615
13 0.571
14 0.533
15 0.500

This is exactly what I needed . How can add a prescaler ?

See amended reply.

Thank you for this helpful chart and code. I have trouble understanding some finer points.
First, you just, well, use TCR1A, COM1A0 and similar variables. Are these always present and implicitly defined when running code on the ATmega (or just on an arduino) or do you actually declare them outside of your shown code snippet?
Secondly, do I correctly understand that the output pin is defined in TCR1A, Output A and Output B, to be on Digital Pin 9 and 10 respectively?
Why do you set it to "Toggle" rather than "Set"?
And lastly, an easy one: What does CTC stand for?
Many thanks to you.

See amended reply.

This is an absolutely amazing answer. I wish I had more rep to give you bounty points. For now: Thank you!

In “The start point is: #define <avr/io.h>”, define presumably s.b. include

Huh? What is "s.b."?

I just added the frequencies for different values. I did this in the original answer because the formatting makes it a lot easier readable compared to a comment.

You can use one of the PWM pins on Arduino to output a PWM signal.
If you want a constant clock, you need to set the duty cycle of the PWM to be 0.5, i.e. 50%.
Syntax: analogWrite(pin, value) where the parameter "value" is the duty cycle ranges from 0 (always off) to 255 (always on) since it is a 8-bit PWM generator inside Arduino.
If you need a PWM wave with duty cycle of 0.5, you need to set the "value" above to be 127, which is exactly in middle of 0 and 255:
analogWrite(clkpin, 127);

analogWrite only works on PWM pins, not on the analog pins.

You are right, my fault.


text:
GSM GPRS module not getting any output from Rx , Tx
I am using a SIM800 GSM/GPRS module. I connected it using 4 wires: Vcc 3.7 volt (2 amp supply), RX and TX and GND.  Whenever I try to send a command it shows me nothing. Here is my code.
//Serial Relay - Arduino will patch a
//serial link between the computer and the GPRS Shield
//at 19200 bps 8-N-1
//Computer is connected to Hardware UART
//GPRS Shield is connected to the Software UART

#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);

unsigned char buffer[64];  // buffer array for data receive over serial port
int count=0;               // counter for buffer array

void setup() {
  GPRS.begin(19200);
  Serial.begin(19200);
}

void loop() {
  if (GPRS.available()) {
    while(GPRS.available()) {
      buffer[count++]=GPRS.read();
      if(count == 64)break;
    }
    Serial.write(buffer,count);
    clearBufferArray();
    count = 0;
  }
  if (Serial.available())
    GPRS.write(Serial.read());
}

void clearBufferArray() {
  for (int i=0; i<count;i++) {
    buffer[i]=NULL;
  }
}

It is an independent module. I've already read the hardware manual and AT command manual. I did everything according to the manual.

Are you sure the baud rate is correct? You could try 115200 and 57600. Is the serial monitor set to "Carriage Return" or "Both NL & CR"? If this isnt set, the modem won't respond to your commands since it requires a '\r' to terminate every command. Is there any indication that the modem is powered (like the net LED blinking)? Your code looks alright but, to be sure everything's okay, use this test program to interact with the modem using the serial monitor; just change your loop() to this:
    void loop(){
        while (Serial.available())
            GPRS.write(Serial.read());
        while (GPRS.available())
            Serial.write(GPRS.read());
    }

This way, everything you type in the monitor will be relayed to the modem and everything from the modem will be relayed to the PC, all via the arduino.

There doesn't seem to be anything wrong with your code.  I'm going to assume you have got the right VCC and the right Serial speed.
Do you have a way of connecting the device directly to your PC and then using a terminal emulator to see if the device is talking?
Is there a library that you could use?  Maybe there is some setting that you need that isn't documented.


text:
Can't figure out how to send Motor Values over Bluetooth, Arduino Bluetooth-controller robot
I was trying to make an Arduino Robot that is Bluetooth controlled but I've some problems!
I can't figure out how to parse strings in Arduino like c++/java/python!
I tried this, If the first letter is L, set the next value to left motor, same for R
but for example "L255" is received as L - 2 - 5 - 5 and it sets L to 2 and ignores 5 - 5.
Any ideas on what I should do?
EDIT: Thought of something else, Sending L or R will toggle the motors! but that's just terrible, it'll be my last option
Update: This is how it works now:
L(0-5) means Left motor speed 5 * 51, 6-9 are backwards! its go backwards at (L(6-9) -5 * 51)

Either collect characters until you have a full string (probably terminated with a newline) or else create a state machine which interprets characters one at a time as they are received, for example first deciding on a mode based on a letter, then doing a multiply-and-add on digits to create a value, and executing on the newline.

:O Good idea! I'll try that tomorrow :) thanks! But I just realized, I also don't need my speed to be so accurate, It can be from 0-9! but anyway that's also good for future stuff and way better than inaccurate speed :)

I'm starting to think my lpc1678 is better for this :) but its too hard to work with :S my board is so huge!

Further to Chris Stratton's comment, you can read about using state machines for processing serial data.

A state machine is the right way to go if you are sending multibyte commands.
However do you need to send 4 bytes for every turn? Do you need accuracy to one degree? Are you going to make regular turns of greater than 60 degrees?  If not I would consider encoding the dAta into a single byte.  You will reduce the radio bandwidth by 3/4, it will improve the responsiveness of. Your software and it will remove the need to have a handler for incomplete messages.
Of course there are probably other requirements that I don't know that will stop you doing this, but in case you haven't thought of it.

For my RC Car its enough! (0-9 speed) but I would love to know about it just for other projects :) But chris and Nick told me how to do so! Thanks :)


text:
Can Arduino libraries be compiled for ARM MCU's?
I am looking for a very low power Micro-controller to interface with the RockBlock Iridium modem. The MCU I am thinking of purchasing is the Gecko Zero by Silicon Labs.
I want to know if it is possible to compile the Rockblock-IridiumSBD Arduino library for the Gecko Zero. The Gecko Zero is a 32 bit ARM MCU.
IridiumSBD Library
Gecko Zero MCU

If you have the full source of the library and all its dependencies you should be able to port it.  The issue is not so much the CPU core, but rather the mechanics of peripheral interface.  There are already a number of supported ARM targets, both Atmel-based boards from Arduino.cc and others, as well as those with other vendor's ARM parts like the teensy series.  Note however that making a true low power design atop the Arduino framework may require extra work - at a certain point you may just want to create well designed firmware from scratch.  If you are new to this, buy a board not a chip.

It uses serial to communicate, so looking at it, the only thing you need to port is the IridiumSBD::send function (as far as I can see).

Depending on the rest of your application, you might find the easiest path is to use the Gecko with the mbed.org tools. There already seem to be mbed Gecko development boards so the task is, to port the Rockblock-IridiumSBD Arduino library.
The benefit of using mbed with the Gecko is it looks like mbed have all of the libraries, including low-power control implemented.
The Rockblock-IridiumSBD Arduino library won't compile 'out of the packet' on mbed.
However, the Rockblock-IridiumSBD Arduino library appears to be a serial interface over a few wires. They recommend 'soft serial' which uses digitalWrite, under program control, and no deep access to Arduino peripherals. That should be relatively straightforward to port to mbed. Mbed has equivalent library calls for digitalWrite, so a first attempt might be a few global search and replace edits.
The alternative would be to use Gecko with an Open Source or commercial development system. However, mbed would provide a faster start, if you have good internet access and are not too paranoid about security, because the tools are 'cloud based', saving you time to set up the tools, and their is an mbed community who might help you over the initial hurdles.

You can often (but not always) export an mbed project as a Makefile to drive gcc offline.  It can be a decent way to setup such an arm project, though the results often need some detailed adjustment.

@ChrisStratton - yes, agreed. Still, IMHO, having a working, tested tool chain, repo, and supportive community with little more effort than signing up has quite a lot to recommend it. It is not unusual for quite small obstacles at the beginning to waste quite a lot of energy Easy to install IDEs like Arduino, or zero-install systems like mbed can help. They can reduce the initial hurdles, leaving lots of time, energy and enthusiasm for later refinements like a local build system.


text:
Arduino Uno R3 board dead
I have an arduino uno Rs board and when connected to USB the board is dead. Yet when connected to the external supply the board will come to live. Power LED on and led near pin 13 blink on and off all time. I tried another computer and other new usb lead. Still computer will not see the board. When usb lead is on checked the 5 volt on the board and it is ok. Even checked the usb lead with multi meter and all  four connection are ok
Can you give me some advice

1.Yes I bought the new board from different source but still waiting for it to arrive.
2.  My clone board Arduino uno using microcontroller Atmega329P-PU and interphase chip Atmega16U2]
3 but the video link is still of help as my new board is as the one shown in the video. Will use it late. Great!!!
There should be a similar explanation for the one I have in the picture

When connected by USB, does the LEDs light up? Or is it only that the PC cannot find it?

Using the usb only board to computer  the board is dead no led comes on and computer does not see the board. Only when external 12v is applied in the dc socket the power LED comes on and led near pin 13 start blinking. But computer still does not recognize the board.

So basically two problems?
Not being powered by USB
AND not being recognized by PC?
You should check if these things are related. If it never worked before, it might just be a bad board. You can try programming with a regular AVR programmer.

I had a similar problem. though it was easily solved but not obvious.
I couldn't connect my nano to the computer, but other devices worked fine. After a while other devices started to be faulty such as portable hard-drives and my CC3D flight controllers. After a cable replacement all the items started working again even the Arduino that i otherwise had discarded as broken.
It might not be the solution you are looking for but im leaving it here in case others comes for a solution.

Does the Arduino show up at all in device manager or in mac/linux.(not sure what you are using)Is your board authentic or a clone? Did this happen the first time you plugged the arduino in or after uploading sketches etc? I had screwed up my firmware for my board that acted similar to what you describe.(I was trying to flash a different firmware) Eventually i ended up reflashing the right firmware and it went back to working again.Maybe it's that, maybe it isn't.

I am using window 7 . It says on the board made in Italy but I doubt it. I think it is a clone due the power led is red not green and the small chip near the usb is green not brown. But a lot of these boards work. Yes this happened first time I plug the usb in. How can I reflash the right filmware. I like to try your idea. Maybe it work. Thanks

I think you will need a working Arduino / usbtinyisp v3.0 or a usbasp programmer (I'm sure there are more options but that's what i know that works) I have read where people who bought the clones had faulty flashes on them when they get it.  Also the chipsets are different so you may have to do some research on that. The link that 'Matt' Posted would be a good starting point in learning how to reflash firmware.

You are happy the lead is ok. Good.
Can you test another Arduino on the PC? (Is it a driver issue?)
Can you connect to the serial pins on the Arduino and read the console output, is anything coming out on USB? (Is the USB socket on the board broken?)
Have you selected the right board type on the ide? (I know it's a dumb question but...)

I only have one arduino uno and bought another but still waiting for it to arrive. But if this is a driver issue a the computer still should recognize the board. When a new device is insert in the computer it should detect and say in the device manager "unknown device" up to my little knowledge. I must find a way how my computer see this new device.The usb on the board is solid and measured the 5volts the ok. But do not know how to measure date. maybe will put an oscilloscope.

Did you buy the second board from a different place? Otherwise you may have the same problem.

I don't agree with the title of this, but this MIGHT help
http://www.instructables.com/id/How-to-fix-bad-Chinese-Arduino-clones/


text:
Separate Timer Instance
I'm trying my best attempt here after failing in Googling the answer, but here goes:
I'm trying to get a separate instance to start running in the background when a pin goes HIGH. How should I attempt this? PLEASE explain your answer, so that I can learn as well. I'm using an Arduino Uno R3 with a Commercial Ir RX-Tx.
Basically:
Sensor -> Low -> Loop
Sensor -> High -> Start Other Event for 5 min -> Loop while Counting down to reset state.
My thoughts here are:
Do this via 555-timer OR get some functional coding (anyone maybe want to share here what solutions they have found?)
Thanks.

The answer can be summed up into one three word phrase: "Finite State Machine". A technique you should learn and learn well. Google it and marvel at the results now you know what to search for,

A separate instance of what?

Arduino Uno has two interrupt pins: 2 and 3, and by hooking up the output of your IR, which goes from LOW to HIGH, it will trigger the function that you defined in the code.
For example this is a piece of code that runs when the pin 2 RISING:
void setup() {
    attachInterrupt(0, doSomething, RISING);
}

void loop() {
}

void doSomething() {
    //Do your stuff
}

Look here for further information link


text:
using more than 8 temperature probe of DS18B20 on Arduino
I am trying to use more than 8 temperature DS18b20 on one bus. Is there any problem to make it work?

As far as I can see there is no limit on the number of sensors you can have on a bus.
So if you are having problems does your code work with less sensors? Try one and work up.
Is it a current issue are you pulling to much from the board?
Is the problem with the one wire library?
Have you got 4.7k pull ups on each sensor?

Is it possible that sharing the VCC is causing interference between the probes data lines do you need diodes after the resistors?

As long as you connect each sensor on a different pin, you should be able to collect the data without any problems.
Otherwise try to search for a I2C temperature sensor and use a demux to control 8 sensors.

DS18b20 uses OneWire, so you can have multiple on the same bus/pin.

It depends on the different address, so he is better of to use an individual pin each time

Each device has a unique 64-bit address. I don't think they made eighteen quintillion units yet, so they don't to have to reuse addresses.


text:
Sending Something to Serial and Writing it Returns a Correlated but Strange Number
I have an indescribable bug where read and write commands give back an array of numbers that are the digits of the input number except +48. Kinda hard to explain. Basically if I type 0 into this code:
    void setup(){
      Serial.begin(9600); //Begin serial connection
    }
    void loop(){
      if(Serial.available()){ //If serial available...
        double ser = Serial.read(); //Read serial value and write it to 'ser'
        Serial.println(ser); //Print 'ser'
      }
    }

I receive 48. 1 means 49, 2 means 50, 3 means 51... And then two digit numbers, which are the same except for each digit. 10 returns 49 48, 33 returns 51 51, 22 returns 50 50.

Serial.read returns a character. The character '0' is 48 in decimal. So this is doing what you expect (or what I expect, anyway). I suggest not using double there, eg.
    char ser = Serial.read(); //Read serial value and write it to 'ser'

Thanks, but I have to output the value I get to a servo, which needs an int and it still separates the different characters into an array. Do you mind telling me a way to convert it into a full int?

which needs an int and it still separates the different characters into an array - I don't understand that. What array?

When transmitted textually, multi-digital value will indeed appear as something like a character array of the ASCII encoding of its digits.

Often we send 4 characters like "1234" over the serial link and want to store them in a single integer like "int position = 1234". One way to do it is to store the characters into a temporary buffer, and then use "atoi()" or "atol()". Another way is convert digits to an integer on the fly. Yet another way is to use Serial.parseInt().


text:
Safely enabling voltage divider on a 12V battery
I'm planning to monitor voltage of a 12V battery with an Arduino's ADC pin connected via a voltage divider. Since I don't want the circuit itself to drain the battery when not in use, I want to use a transistor to "enable" it via an Arduino DIO pin like:

Is this a safe circuit to use?
If I set EN low to disable the divider, will that risk putting 12V directly on the ADC pin and burn it out? I've found alternative designs, but they seem overly complicated.
Edit: The battery is a Lipo which is also powering the Arduino through a step-down DC converter.

No, that will not accomplish your goal.  The top resistor may be large enough that the Arduino MCU's protection diode may be able to handle the current sourced from the battery, however you will still be draining the battery, which is what you were trying to avoid. What is the capacity and chemistry of your battery?  I'd expect something like a car battery may have a self discharge rate that hides the load of your voltage divider.

The "Controllable Voltage Divider" on the page you linked seems more sensible to me. Plus I chuckled at the "NdN" transistor you were using. ;)

@ChrisStratton, How is it still draining the battery? Would it be different if I relocated the transistor to the high-side?

It is still draining the battery because there is a protection diode from the input to the ATMEGA's power supply, which clamps the input voltage at around .6v above the supply voltage, and that will be fed by the top resistor in your circuit.  Potentially (with a smaller resistance) this could even end up powering the ATMEGA from an input, though doing so is out of specification as the diodes are tiny and easily damaged.

@ChrisStratton, Right, so wouldn't moving the transistor to the high side should fix that? With EN pulled low, there won't be a circuit connecting 12V to the ADC input.

No, because on the high side you would need a PNP, and when connected to an MCU pin, you can't not pull its base low which would turn it on. So you use an NPN to turn on the PNP, and are basically in the territory of the multi-stage circuits already proposed.

I use a similar system on a product I recently worked on to monitor the battery voltage - and of course I didn't want it on all the time to drain the battery.
The trick, though, is to do the exact opposite of what you are doing.  Instead of isolating the ground (which leaves the battery then directly connected to the Arduino) you need to completely isolate the battery from the divider.
This can be accomplished by using a P-channel MOSFET which you can then drive with an N-channel MOSFET:

The theory is, when the Arduino DOUT is either LOW or not connected (pulled low by 10K resistor) the N channel MOSFET is turned off.  That means the gate of the P channel MOSFET is being pulled up to the battery voltage by the other 10K resistor, so the P channel MOSFET is off, which isolates the whole divider from the battery.
When DOUT goes HIGH it turns on the N channel MOSFET which then pulls the gate of the P channel MOSFET down to ground which then turns it on, thus connecting the divider to the battery.
When the P channel is OFF the only circuit connected to the ADC is the connection between the ADC input and ground through a 10K resistor, so everything is happy and safe.
You should not use resistors greater than around 10K in size on the input to the ADC because the ADC itself has a resistance (the impedance) which is placed in parallel to the lower resistor of the divider.  If the divider's resistors are too large that impedance will affect the accuracy of your readings because the total resistance of the lower resistor will be skewed slightly.  Yes, it's possible to compensate in software, but as long as you keep to a limit of 10K or so for the resistors you won't need to worry about doing such things.
Note that it is important to use a P-channel MOSFET for this, not a PNP transistor.  A P-channel MOSFET, when on, looks like a very small resistor.  A PNP transistor is seen as a fixed voltage drop skewing your results.  The N-channel MOSFET can be replaced by an NPN transistor if you wish, it makes no real difference. I nearly always use MOSFETS these days instead of BJTs though as a matter of course.
As an aside, the only other way of achieving this whilst maintaining the isolation of the ADC from the battery would be to replace the P channel MOSFET with a small relay (say a reed relay), but then you still have to build a relay driving circuit which is just about as complex as this one.

Interesting analysis. That's a good point about MOSFET vs BJT, however, I'm still not sure how the overall design fundamentally differs from my approach. If I relocated my transistor to the high side, and turned it off, wouldn't the ADC be similarly disconnected from the battery? Also, why can't you wire the DOUT directly to the P-MOSFET's gate? Will the P-MOSFET only activate with 12V?

The P mosfet's gate has to be pulled up to the source potential to turn it off - i.e., 12V.  Wiring it to 5V it will never turn off. You can't just move your transistor, you have to change the transistor's polarity (PNP instead of NPN or P channel instead of N channel) which then also means driving it properly with an N channel or NPN.

It appears you have the Drain and Source mixed up on the P-FET. I created your circuit in tinkercad and was having an issue until I switched them. Thanks for the circuit design - I'll try building it for real now. Here's the Tinkercad link if you're curious.

I'd use some very large resistors (e.g. 1 and 2 Mega Ohm), and add a small capacitor to the center, to stabilize the value during sampling. Using 1 and 2 MOhm would result in 10uA of current loss, which is probably negligible in your cases.

No, don't do that. Think about the input impedance of the ADC and what affect such large resistors would have...

@Majenko That's what the capacitor is for. Just make sure there is some time between measurements for the capacitor remain charged at the right voltage. But I might be wrong here!

Oh, and I wouldn't call 10µA negligible.  My last project idled at 50µA total - adding another 10µA on top of that would have been an increase of 20% current consumption.

10uA would take about 2 years to discharge a CR2032 coin cell. Since this is a 12V battery I assume it's more that 240mAh. Indeed 10uA isn't always negligible.

Keep in mind that an ADC of the type used here is typically not a steady-state load, but rather a pulsed one.  If you go with this route, it would be a good idea to evaluate the readings for various resistor and capacitor sizes.  I do expect you will see some distortion of reading, but I also expect it will be possible to get a decent reading with a circuit whose load is dwarfed by the self-discharge rate of a larger lead-acid battery if that is indeed what is being monitored.

@Majenko, How would such large resistors affect the ADC? What is the maximum resistance that should be used?

Depends on the sampling rate. The resistor should be small enough, so that the capacitor is being "fully charged" between reads.


text:
Get 25 kHz PWM on a 16 MHz Arduino
I am trying to output a 25 kHz software PWM on at least four pins simultaneously with variable duty cycles on each pin individualy.
I've got all the actual PWM outputs via internal timers 2x8 1x16 with variable duty cycles and am looking for a way to output a 25 kHz PWM on the four pins (any pins) via an external timer if necessary. How can I do that?

The three available timers on a 328 give you six PWM outputs via their A and B compare outputs, with the only limitation being that the two outputs of the same timer have to have the same period (but can have different duty cycles). So as far as I can see, you don't need to do anything special.

At 16 MHz, your instruction cycle is 62.5 ns, and your PWM period is 40 \$\mu\$s. This is only 640 instruction cycles per PWM period.
To have any hope of doing this, the first thing you need to do is forget using anything Arduino other than the hardware. Download the datasheet for the AVR in question and start getting familiar with it. Your best bet is to use 8 bit timers to reduce the overhead of loading them.
My approach would be to use every 8 bit timer available, and divide the outputs up among the timers. Load the shorest pulse width output in the 8 bit tiemrs. Keep a 16 bit timer available to use for the PWM period. Start all the timers at once. On the first 8-bit timer interrupts, toggle the output, and reload the timers with the time between the next shorest pulse width. Rinse and repeat.
Alternatively you could run one timer, and write a little scheduler that puts the outputs in order from shortest to longest pulse width, constantly poll the timer, and toggle the bits as needed.
Both of these options have a ton of software overhead, and the pulse widths will all be semi-deterministic. Neither would be good for any application where the micro has to do anything else in a timely fashion, such as communication or drive a LCD.

I've been thinking of making a board using 2 or 4, PCA9553 then it's all getting the i2c set up to update them https://www.adafruit.com/products/2590 is the the arduino I'm using currently, but I've yet to use i2c and I haven't found reference to anyone using it with arduino yet

Look into using one of the AVR chips that have more PWM outputs. For example, AT90PWM81 which includes six hardware PWM outputs.

I do like the outputs available on that chip I'll definitely have to read up on the spi interface, I have not yet seen data regarding duty cycle changes but I'm just getting started reading into it

I was tinking that chip might even run arduino code.

I would like to have the option of reading sensors, temp and rpm mainly, and use collected data to change the duty cycle for the pwm outputs and had planned to use the serial connection to send and receive data on a computer to at least to display data, and possibly manual controlled of duty cycle via an application on the on the computer

AT90PWM216 has a UART, that might make for easier PC interfacing.

void setup()
{
    // Set the main system clock to 8 MHz.
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();

    // Configure Timer 0 for phase correct PWM @ 25 kHz.
    TCCR0A = 0;           // undo the configuration done by...
    TCCR0B = 0;           // ...the Arduino core library
    TCNT0  = 0;           // reset timer
    TCCR0A = _BV(COM0B1)  // non-inverted PWM on ch. B
        | _BV(WGM00);  // mode 5: ph. correct PWM, TOP = OCR0A
    TCCR0B = _BV(WGM02)   // ditto
        | _BV(CS00);   // prescaler = 1
    OCR0A  = 160;         // TOP = 160

    // Same for Timer 1.
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1  = 0;
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
        | _BV(COM1B1)  // same on ch. B
        | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
        | _BV(CS10);   // prescaler = 1
    ICR1   = 160;

    // Same for Timer 2.
    TCCR2A = 0;
    TCCR2B = 0;
    TCNT2  = 0;
    TCCR2A = _BV(COM2B1)  // non-inverted PWM on ch. B
        | _BV(WGM20);  // mode 5: ph. correct PWM, TOP = OCR2A
    TCCR2B = _BV(WGM22)   // ditto
        | _BV(CS20);   // prescaler = 1
    OCR2A  = 160;
}

void loop()
{
    analogWrite( 3,   1);  // duty cycle = 1/160
    analogWrite( 5,  53);  // ~ 1/3
    analogWrite( 9, 107);  // ~ 2/3
    analogWrite(10, 159);  // 159/160
}


text:
Can I connect an output pin to an input pin to measure it's voltage on a single board?
So just bought an arduino Uno and I've been playing around with it. I want to connect one of the input pins to one of the PWM outputs and measure the output from there by sending it to my computer through Serial and then plot it in python.
Sorry if this is a basic question.
Thanks

PWM pins don't give an analog value. They are either 0v of 5v. Your idea is possible, but you'll receive almost exclusively 0's and 1023's.

ok cool, I'm just worried that I'll burn out the board...

That won't happen here. Just be careful to never connect two pins that are both outputs (as setting one to HIGH and the other to LOW would create a short). If you want to be super-save, you could put a resistor between the two pins (e.g. 1kΩ) instead of a wire.

PWM are digital output pins, and it seems that you wish to measure analog equivalent voltage generated by PWM output. If so, you'd need a filter.
Construct a unity gain op-amp based RC filter with cut-off frequency significantly smaller than PWM clock frequency. This will generate a analog waveform that can drive analog circuits. You could connect this to ADC input pin.
You could Google "Active low pass filter" for a lot of schematics and formula.
BUT
To be able to faithfully reproduce analog signal captured through ADC on a computer screen graph, your ADC sample rate must be more than ~2.5 times analog signal's bandwidth.
If your sample rate is close to Nyquist rates,  you'd need to filter (interpolate) your digitized signal in software to generate a smooth graph. This is a bit involved in maths and software. Otherwise you'd only get a "spikey" waveform.
Or preferably have a sample rate > 10 times analog bandwidth. This will give large enough sample counts to reliably show analog data without much processing.

nope not interested in an "analog equivalent voltage". I just wanted to measure the PWM waveform, and wasn't sure if by using the same board for measuring and generating (of the signal) I could potentially burn it out

Usually digital waveforms are better captured by counters + interrupts, because exact voltage level is usually of no concern. i.e. for all transitions (hi->lo, lo->high), trigger interrupt. In ISR record a timer counter value and store. Capture timer clock needs to be (much) faster than PWM clock


text:
How to change the usb name of Atmel 32u4?
I want to change my Arduino Leonardo's name that Windows shows me when it's plugged in.
I know that i have to change its firmware to change the name but I cant find firmware for it on the Internet.
On Arduino Mega, I have changed it with a downloaded firmware via flip, but I can't change the file because it's a .hex.

you can change the hex, if you're brave enough

Start looking here for the actual implementation https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/caterina/Descriptors.c and at the Makefile for a start towards building from source.  You may be able to modify the .hex (the strings appear to be fixed length and padded with spaces) but will need a tool which fixes the checksums - possibly you can objcopy to a flat binary and back to hex.

The Arduino '32U4 bootloader, Caterina, can be found under hardware/arduino/bootloaders/caterina. It requires LUFA in order to build.
With the technical part aside, note that you are not allowed to use the USB IDs assigned to Arduino LLC with products you intend to distribute under another name. You will need to acquire your own vendor ID from the USB-IF if you want to do so.