text:
Individual control of multiple RGB leds
I'm trying to control several RGB leds individually. So far I've been able to control multiple RGB leds using only 3 PWM outputs using NPN transistors as shown here (pic below).

I would like to control each led individually in order to display different colors in each led. If I used the Arduino Mega, which has 12 PWM pins I could only control 4 different groups of leds using the approach mentioned above. It would be nice to be able to control them using the Arduino Uno or other boards with less PWM pins.
What would be a good solution for this? I've been taking a look to shift registers using ShiftPWM and solutions like the TLC5940 but I haven't got enough experience to tell which way would work better.

I do wish people would draw proper schematics. I can't work out head nor tail what is going on in that circuit. Use the TLC59116 - it's the best LED driving chip ever.

simply because of availability, try the software solution first, then try the hardware one.

@guardabrazo If by good you mean cheap solution to control several RGB lights. Then you can use a 4017 decade counter to multiplex the RGB lights so control several RGB lights. with a single 4017 is about 20 times cheapper than the TLC59116 costing about 17 cents. With a few 4017's you can control more than 100 RGB lights. This would only use a on the Arduino.(including a few PWM pins).

"Digital led strips" have individually colorable LED's. Thuis would be much more favourable as a tricky solution.

Here is a 1/2 software 1/2 hardware solution:
You actually have 6 pwm pins (from the silk screen notation in your picture).  So you can control 2 RGB LEDs independently.  If you added 4 more transistors that are used to gate the common 5v going to each of the 4 RGB LEDs you could control them in pairs.  That is, you could turn on 2 independently controlled RGB LEDs and let the 6 PWM outputs control the brightness and color of each of the 2 for, say, 100ms.  Then you could turn those off and turn on the other 2 independently controlled RGB LEDs for 100ms.  During the switch, you would change the PWMs for the 2nd set of RGB LEDs.  The draw back to this approach?  You may start noticing the LEDs flickering.  You may have to adjust the rate which you switch between the two pairs of LEDs.  And, of course, it may not work as you expect it to.
Totally different approach:
You can use programmable RGB LEDs:

And use this Arduino software library. These types of RGB LEDs have the PWM build in.  The Arduino sends out serial data to the first LED which strips off its RGB data.  Then sends the data to the next RGB LED which does the same.  So you can control many RGB LEDs using a single pin on your Arduino.

There is an alternative that gives you more PWM pins when using an Arduino Uno. You need a 74HC595 shift register which has eight additional output pins. By default, these pins are not PWM capable, however, with a library that I have developed they are.
You can then easily replace your analogWrite calls with something like that sr.set(i, val);. The parameter i indicates with shift register pin you want to update and val is a PWM value (from 0 to 255).


text:
How can I attach sensors without a shield for a wearable project?
I am looking for a solution regarding the gsr, accelerometer, heart rate, skin temperature. From this other question seems that Grove isn't clear enough with their documentation. So I am looking for other ideas. I already know cooking hacks and I am afraid that with their hardware I can't make my Arduino wearable and comfortable enough, because at the end I'd like to attach a lithium battery with a case (that's why I don't want the extra bulk of a shield).
More details of what I am looking for.
Accelerometer:
Range: +/- 1.0g
Minimum resolution: 0.01g
Galvanic Skin Response
Range: 56k Ohms to 20M Ohms
Two-standard-deviation error of +/- 4.0% otherwise
Skin Temperature
Range: 20.0°C to 40.0°C
Resolution: 0.05°C
Error: +/- 0.8°C

Shield are just for lazy people :-). Also, stacking shield will lead to problems a lot of time. Use regular breakouts and wire them yourself to the appropriate arduino pins. You can move them around, till you have the best fit for your enclosure.

"tacking shield will lead to problems a lot of time" Why?
"Use regular breakouts and wire them yourself to the appropriate arduino pins." I'm totally new in this field and what I know at the moment is that I have to see which kind of wire goes in which kind of holes. These things are typically written with letter and numbers (on the board), right?

Sorry, I meant to say 'shields' not 'shield'. A lot of times different shields use the same pins, leading to problems. This forum is full of those cases. As to which connection on the breakout, goes to which pin on the arduino; sometimes it doesn't matter which arduino pin. Sometimes it has to be a specific pin (e.g. SPI or I2C pins). That's the advantage of shield. They've already done this for you. You however miss the flexibility using different pins, when required.

I ran into a similar quandary when making a prototype for a device that needed real test-data from an external, glove-worn accelerometer. I wound up running the data/power/etc pins from my Arduino board to a female RJ-45 jack (I've used a telephone jack on another project where only 4 wires were needed). Then I cut an old cat-5 network cable in half and soldered the wire-ends to data/power/etc pins on my external sensor board. This allowed me to separate one component's wiring scheme from the other's. (FYI: longer lengths of cable between components does increase the risk of noise/interference corrupting digital signals. This can usually be resolved by reducing data rates or by adding a few resistors/capacitors to filter the signal, but I have limited knowledge on this)
Even if you don't have any old RJ45 cables/jacks laying around, it can really help to find some way to "modularize" the various pieces that will be working together when your device is complete. If you're familiar with object oriented programming, think of it as "designing an interface" for each component. Then, even if you completely redesign the wiring for a particular component, you only need to ensure that your "interface" (aka connection) is the same, and you wont need to resolder anything on the other end of the line.

The accelerometer may be pretty easy (since it may not need to be in close contact with the person), but the GSR and skin temperature will need to be touching the person to work.
The first thing you will want to do is to identify the sensors that you want to use, and then come up with some ideas for how to make them wearable so that you can measure the parameters that you're looking for. Will you be able to attach them with straps, or does the attachment need to be more subtle or more comfortable? Small breakout boards are handy, but they may make the sensor uncomfortable to wear.
I'd suggest taking at look at the Adafruit site for some ideas on wearables and sensor interfacing. There is a lot of useful information there and much of it focuses on Arduino based designs. For the most part the sensors they sell and use are well documented either with data sheets or code (or both).

Do you advice specific tutorials?

Then on adafruit there is only one sensor :(

What you'll want to do is figure out which sensors you want to use. Some will interface with a voltage that is proportional to the value being sensed. Those are easy, you just connect those to one of the analog pins. In most cases you could just change the pin being used if there is a conflict. There are also devices that use an interface like 1-Wire that permit multiple devices on a single pin. It will help a lot of you can say more about your project and sensors that you are interested in using.

For accelerometer sensing I used LIS3DH from STMicroelectronics, its low power(down to 2uA), small (LGA package 3x3x1 mm) and has cool build-in features (like orientation, tap and doble tap detection among other things). http://www.st.com/web/catalog/sense_power/FM89/SC444/PF250725?icmp=pf250725_pron_pr_feb2014 and there are a lot of libraries like https://github.com/adafruit/Adafruit_LIS3DH
For intro to GSR check this project http://cwwang.com/2008/04/13/gsr-reader/ Pretty easy ;) More advanced design will require a signal generator and an instrumentation amplifier. An example of such design can be found here https://www.maximintegrated.com/en/design/reference-design-center/system-board/6147.html/tb_tab1 Another interesting project is the truth wristband http://produceconsumerobot.com/truth/
The temperature part can be done with a thermistor (IC temperature sensors do not compliant with your resolution spec) and a bridge circuit. For reference check this sensor http://www.digikey.com/product-detail/en/PR103J2/615-1069-ND/2651611 and also some literature about Wheatstone Bridge http://www.ametherm.com/thermistor/ntc-thermistors-temperature-measurement-with-wheatstone-bridge
Hope be helpful.

source: Stack Exchange

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

sort: votes


text:
How do I choose a battery to power my Arduino Nano project?
I was wondering if anyone would be willing to teach me how to logically choose/calculate which battery I should/can use to power my Arduino nano project (so I don't have to keep it connected to my computer to use it)? I am interested in learning, not just being given an answer because my goal is to be able to figure this out on my own for my next project. (Also, I got this far by myself because of a lot of trial and error in addition to reading as much as possible, but I don't want to buy an assortment of batteries for my trial and process of learning.) Thank you kindly.
If you are willing to teach, I have included all of the details about my project in the code below or at least I think I did.
Before I get to my code, one problem (I think) is that the two digit seven segment LED display that I bought for my project does not have a data sheet. However, even if it did, I am not sure that I would understand how to use it. I looked up other similar LED displays and if I understand what I am looking at, they seem to use between 2-3 V and 20-30 mA.
I thought that because I saw 2-3 V on the similar looking LED displays, I would be able to use a 3V battery to power my project. However, when I tried the following two batteries to power my project they did not work:

3V CR2032 lithium cell battery (for LilyPad) - this was enough power to dimly turn the power light on the nano, but not enough to turn the lights on for my project.
E-Textiles Battery 3.7 V - 110mAh (2C Discharge) - this was also enough to dimly turn the power light on the nano, but not enough to turn the lights on for my project.

Because those did not work and it's all I had left, I tried a 9V battery:

9V battery - this powers the project just fine, but I was hoping to calculate the actual voltage and/or current because I was hoping to use one of the tiny lithium ion batteries from SparkFun.com (or elsewhere) to power my project if this is possible.

Here is my code (Sorry that the code is a bit long. I couldn't figure out how the SevSeg library worked, so I just wrote my own code):
/************************************************************************************************************************
Rebecca Wilson
12/17/18

This program is for using an arduino nano to run a 2 digit 7 segment LED display. I made it as a life counter for
MTG, so it displays "20" to start and there are two buttons that can be used to change the life total by +/- 1.

These are the pieces I used:

1x Nano 3.0 Controller compaitible with arduino nano CH340 USB driver (taydaelectronics.com; SKU A-2864)
    *You must select "ATmega328P (Old Bootloader)" for the processor (otherwise it can't upload the file to the nano).
    *This also works with an arduino UNO, but I prefer to change the negativeButtonPin to 13 for the arduino Uno (I don't
     think pin 13 works on my nano because it is connected to the practice LED that comes attached to the board).

1x LED Display 7 segment 2 digit 0.28 Inch common anode HI RED (taydaelectronics.com; SKU A-1701)

2x Tact switch 6x6mm 5mm through hole SPST-NO (taydaelectronics.com; SKU A-5127)

2x 330 Ohm 1/4W 5% carbon film resistor (taydaelectronics.com; SKU A-2067)

breadboard and jumper wires

This is what I understand about the LED display:
  LOW means that the segment is turned on
  HIGH means that the digit is turned on and when that digit is turned on all segments are set to LOW (turned on)
*****************************************************************************************************************************/

//declare constants
int tensDigit = 10; //330 Ohm resistor between digit pin and nano pin
int onesDigit = 11; //330 Ohm resistor between digit pin and nano pin

int pinA = 2;
int pinB = 3;
int pinC = 4;
int pinD = 5;
int pinE = 6;
int pinF = 7;
int pinG = 8;
int pinDP = 9;

int positiveButtonPin = 12; //and the other side of the button is connected to the GND pin next to D2
int negativeButtonPin = A0; //and the other side of the button is connected to the GND pin next to D2

//declare variables
unsigned long lastPositiveDebounceTime = 0;
unsigned long lastNegativeDebounceTime = 0;
unsigned long debounceDelay = 100;
unsigned long previousMillis = 0;

int currentPositiveButtonState = HIGH;
int currentNegativeButtonState = HIGH;
int lastPositiveButtonState = LOW;
int lastNegativeButtonState = LOW;
int trueLastPositiveButtonState = LOW;
int trueLastNegativeButtonState = LOW;
int buttonPushCounter = 0;
int startingValue = 20;
int currentValue = startingValue;

//declare functions
void delayTime(unsigned long milliseconds);
void setDigit(int place, int number);
void setNumber(int number);

void setup() {

  pinMode(tensDigit, OUTPUT);
  pinMode(onesDigit, OUTPUT);
  pinMode(pinA, OUTPUT);
  pinMode(pinB, OUTPUT);
  pinMode(pinC, OUTPUT);
  pinMode(pinD, OUTPUT);
  pinMode(pinE, OUTPUT);
  pinMode(pinF, OUTPUT);
  pinMode(pinG, OUTPUT);
  pinMode(pinDP, OUTPUT);

  pinMode(positiveButtonPin, INPUT_PULLUP);
  pinMode(negativeButtonPin, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {

  setNumber(currentValue);

  //read the current button state
  currentPositiveButtonState = digitalRead(positiveButtonPin);
  currentNegativeButtonState = digitalRead(negativeButtonPin);

  //if the positive button state has changed then record the new current time
  if (currentPositiveButtonState != lastPositiveButtonState)
  {
    lastPositiveDebounceTime = millis();
  }

  //if the button state did not change during the debounceDelay time, then consider it a true state change and...
  if ((millis() - lastPositiveDebounceTime) > debounceDelay)
  {
    //if the last true button state has changed then...
    if (currentPositiveButtonState != trueLastPositiveButtonState)
    {
      trueLastPositiveButtonState = currentPositiveButtonState;

      //if the button was pressed then increment the button pressed counter
      if (currentPositiveButtonState == LOW)
      {
        currentValue++;
        setNumber(currentValue);
        Serial.println(currentValue);
      }
    }
  }

  //change the last button reading to the current button reading
  lastPositiveButtonState = currentPositiveButtonState;

  //if the negative button state has changed then record the new current time
  if (currentNegativeButtonState != lastNegativeButtonState)
  {
    lastNegativeDebounceTime = millis();
  }

  //if the button state did not change during the debounceDelay time, then consider it a true state change and...
  if ((millis() - lastNegativeDebounceTime) > debounceDelay)
  {
    //if the last true button state has changed then...
    if (currentNegativeButtonState != trueLastNegativeButtonState)
    {
      trueLastNegativeButtonState = currentNegativeButtonState;

      //if the button was pressed then increment the button pressed counter
      if (currentNegativeButtonState == LOW)
      {
        currentValue--;
        setNumber(currentValue);
      }
    }
  }

  //change the last button reading to the current button reading
  lastNegativeButtonState = currentNegativeButtonState;

}

void setNumber(int number) {

  int onesPlace = number % 10;
  setDigit(1, onesPlace);
  delay(5);
  int tensPlace = number / 10;
  setDigit(10, tensPlace);
  delay(5);
}

//place is 1 if setting the ones place and 10 if setting the tens place
void setDigit(int place, int number) {
  switch(place)
  {
    case 1:
      digitalWrite(onesDigit, HIGH);
      digitalWrite(tensDigit, LOW);
      break;
    case 10:
      digitalWrite(onesDigit, LOW);
      digitalWrite(tensDigit, HIGH);
      break;
  }

  switch(number)
  {
    case 0:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, HIGH);
      digitalWrite(pinDP, HIGH);
      break;
    case 1:
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, HIGH);
      digitalWrite(pinDP, HIGH);
      break;
    case 2:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, HIGH);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 3:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 4:
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 5:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 6:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 7:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, HIGH);
      digitalWrite(pinDP, HIGH);
      break;
    case 8:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 9:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
  }
}

Your post seems to have two questions.  One, battery power, is well documented and you can find the answer on the Arduino website.  The other is to do with understanding the 7-seg display, which is not apparent in the title of the question.  Did you use current-limiting resistors?  Google "7 segment display resistor" and there are plenty of tutorials (including video) on how to use.

How are you attempting to connect the various batteries you have tried?

Stackexchange works best one question at a time.  The assumed goal is to build a searchable data base of questions and answers for others with similar questions.  Multiple questions and long discussions make this goal difficult to realize.  That said, batteries are chosen for a number of reasons.  Some, like cost and weight, you may not even care about.  And more then not, several different batteries can be used for the same application.  So, it may come down to opinion.  Yet another format which stackexchange uses normally avoid...

(1) Yes, as I stated in my code, I used a 330 ohm resistor between each of the two seven segment digit pins and the Arduino nano pin.

(2) I connected the positive terminal of my battery to pin 30 which is labeled as VIN on the Arduino Nano and the negative terminal of my battery to pin 29 which is right next door and labeled as GND.

(3) Sorry, my question may not have been clear because I was/am so confused. I don't understand how my computer is powering my project and I thought that when I added a different power source that there was some kind of calculation I needed to do to determine what voltage I should use depending on what I put in my circuit. I am now guessing there is no calculation. There are an overwhelming number of batteries to choose from and I thought this calculation would narrow it down. However, I guess I should just use any battery between 7 and 12 V and it doesn't matter what I put in my circuit.

Consider the length of time needed with out external power and the average current the project demands.  Multiply these two giving Amp-Hours.  Then, given the Amp-Hours are reasonable, choose a battery with twice the Amp-Hour capacity.  Battery ratings are usually ideal.  In that the slower the power is pulled from the batteries the larger the battery capacity will appear.
It goes without saying you need enough cells to generate the specified voltage.  Cell voltage varies by chemistry.  Consequently note the exact voltage of a cell or pack of cells.  Especially when building your own serial battery packs where slight differences add up to significant voltages.
Lastly consider if primary or secondary batteries are to be used.  Primary cells such as alkaline batteries are long lasting and generally safer.  Secondary batteries such as Lithium-ion offer good power density but are difficult to care for.

Thank you for your help. I attempted to follow the directions that came with my multimeter and measured the current of my circuit as 28 mA. If I understand correctly, if I want my project to run for 4 hours at a time then I should buy a battery with at least 224mAh.

Concerning the voltage, I feel really stupid. For some reason, I was imagining that I should use ohm's law (or something else) to do some kind of calculation (which I was not grasping) to determine the proper voltage of the battery to use. However, would I now be correct to assume that there is no calculation that I should do? Instead, I just need to use between 7 and 12 V because that is what the instructions say that the nano needs and it doesn't actual matter what pieces I put in my circuit.

I believe both of your comments are correct.  Most batteries are have better than 224mAh so it should be easy to find even small batteries that satisfy this minimum.  Processors current demands can vary depending on what the processor is doing.  And over engineering battery life by an order of magnitude rather than double may be prudent.  When using any on board regulator, inferred by the wide range of acceptable voltages, be careful and double check you are connecting to the proper power pins.  Directly powering a 3 or 5 volt processor with these higher voltages can damage the processor.

I should add that managing portable processor based devices to extend battery life is not trivial.  Professional developers spend hours if not days selecting and configuring processors to operate as expected while only "sipping" nAmps and uAmps of current 90% of the time.

I don't think this will be a fully fledged answer, but I want to tell you a useful alternative to batteries you already used. I usually power my projects through a 5V "powerbank" that I do myself. All you need is a step-up board like for example 134N3P and any Li-Po/Li-Ion 3,7V cell. The 134N3P is very small and it contains a undervoltage and overcurrent protection circuits so you won't destroy the cell. It also allows to safely charge that cell using any USB charger. The Li-Po/Li-Ion cells come in all shapes and sizes. For miniature projects you can find one in size of a two coin batteries, but for regular size projects I suggest 18650 cells as the cheapest option.

Thank you. This is very interesting. I was not aware of this option.

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


text:
How do I upload the sensor data from arduino into a database?
I have just connected a Libelium shield to connect many sensors to Arduino UNO, that measure water ph level, temperature,...etc. I really couldn't figure out how do I upload the sensor data into a database(MySQL). I have the code for database connectivity, but still couldn't figure out how(Querying) to upload the sensor data into the database.
The main problem here is how do I make the arduino recognize the sensor data to upload it into database or send to to another Arduino or Raspberry pi through XBee.
Code for database connectivity:
void sendData(){

          Serial.println("Connecting...");
          if (my_conn.mysql_connect(server_addr, 3306, user, password)){
            delay(500);
            Serial.println("Starting SQL!");
            Serial.println(INSERT_SQL);
            my_conn.cmd_query(INSERT_SQL);
            Serial.println("Query Success!");
            my_conn.disconnect();
            Serial.println("\n");
          }
          else {
            Serial.println("Connection failed!");
          }
}

You might be mixing concerns and you may benefit from decomposing your mental model of the situation a bit.  You should have sensor reading components, a component that consumes the sensor data (does something with it, e.g. drop into DB), and your network layer.
Ideal architecture
(1) Arduino connected to sensor.  Read in measurements of environment and transmit data via ZigBee
(2) Arduino or, ideally, Raspberry Pi listens for messages on ZigBee mesh network.  On message, sanitize data and insert into DB.  Even better there is a queue process between "sanitize data" and "insert into DB"

First you have to create the table in your MySQL database, like:
CREATE TABLE IF NOT EXISTS `table_log` (
  `log_id` int(11) NOT NULL AUTO_INCREMENT,
  `log_date` date NOT NULL,
  `log_time` time NOT NULL,
  `log_t1` float NOT NULL,
  `log_t2` float NOT NULL,
  `log_t3` float NOT NULL,
  `log_t4` float NOT NULL,
  `log_vbatt` float NOT NULL,
  PRIMARY KEY (`log_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1;

You can execute it in your phpmyadmin page (or create the table manually there). Above we have columns for auto-increment id ('log_id' - necessary), date & time, 4 temperature values and voltage value (modify these according your requirements).
Than the query to create a new record would be like this:
INSERT INTO `table_log` (`log_id`, `log_date`, `log_time`, `log_t1`, `log_t2`, `log_t3`, `log_t4`, `log_vbatt`) VALUES
    (0, '2016-03-04', '01:53:30', 1.0, 2.0, 3.0, 4.0, 3.0);

You need to create this string dynamically (with real values) and use instead of INSERT_SQL.

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


text:
Digit LED has single input, multiple outputs for each segment. Concerns about "sinking" 5v supply into digital pins
The model name is 5161BS

Pins 3/8 are input and the rest are output for each individual segment.
I have connected pin 3 to the 5v pin on the Arduino, and the rest to individual digital pins.
With a simple sketch with the pins set to mode output, all segments are lit.
My concern is that the way I am turning off each segment is by setting the output pin to high.
Meaning
5v pin --> LED <-- Digital pin

Is this dangerous to have two voltage sources going in the same direction? Is there another way to do this?

Do you have current-limiting resistors? This is the first question. Otherwise you are probably damaging something.

Fortunately I put a 330 ohm resistor from the 5v pin. But no other resistors.

Well that is better than nothing. However when multiple segments are displayed they will have different brightnesses because that one resistor will have different currents through it. You really need 330 ohm on all the pins except the 5V one.

@NickGammon I'm not sure about that. I'd expect any segments that are lit to have the same brightness, though the brightness of each LED will increase as fewer LEDs are lit, since theres more current to go around.

@TisteAndii, they would have the same brightness if they are identical.  But only a slight difference in the voltage drop leads to a large bias for current flow when hooked up this way.

If there was a difference it wasn't noticable. https://photos.google.com/share/AF1QipP6Iu9o1PD-RNipc_BTrsXK7nRzVLYJW2y1YnLTNN_77PJ8C-p51hIno2YDOdtKVw/photo/AF1QipPV3GTbBiy80Gbe3I1roi4pKFCxMRerhH68xS6b?key=eFVKdER2RTFNQTNtM0lqSjZYbHRJZUU3VmZDckpB Although it does seem that the final digit "-" was significantly brighter from the video than when the multiple segments were lit.

This is called a common-anode LED. The anodes (+ side) are shared. They probably dedicate two pins (3 and 8) to share the current to the anodes.
Connecting the common anode to +5V is fine. However you should have current-limiting resistors between each of the other pins (the cathodes) and the Arduino digital pin. Otherwise you are getting the Arduino to try to "sink" its own 5V supply through a digital pin, which far exceeds its rating. You will probably damage the output driver MOSFETs and they will stop working. Plus the excessive current will damage the LEDs as well.
See the LED resistor calculator. Something like a 330 ohm resistor, in series with each of the cathodes, should be adequate.
Now, setting the digital pins to output will "sink" 10 mA or thereabouts from +5V, through the LED (which lights up) and through the digital pin to ground.
You control what "number" you see on the LED by turning off the appropriate pins, to make the segments light up.
Also see The care and feeding of LEDs.

The device you have is a common anode display. This means that the anodes (+ve terminals) of all the LEDs are connected to one common pin (well, 2 pins actually, pin 3 and 8 are connected internally) . Their cathodes (-ve terminals) are what make up the remaining pins. Now, to light up any LED, you need 5 V at its anode and GND at its cathode. You have connected 5 V to pin 3, which stands for the common anode of every LED, so all that is left for any LED to turn on, is for you to connect GND to its corresponding cathode. So when you made all the remaining pins (the cathodes) OUTPUT, by default the Nano sets those pins to a logic LOW (or GND) value, so ALL the LEDs got lit up. Each LED now has 5 - 0 = 5 V across its terminals and is forward-biased.
However, when you write HIGH to any cathode, the potential difference across the associated LED/segment is now zero, because that LED has 5 V at its anode (pin 3/8) and 5 V at its cathode (as a result of writing HIGH), and 5 - 5 = 0 V so it is reverse-biased (at least 2 V or thereabouts is needed for a red LED to become forward-biased) and so the segment turns off. And this is how you control which segment is on at any time: You write a LOW to a cathode to turn on the associated segment, and write HIGH to turn it off. It sounds counter-intuitive but it follows if you think about it. Regarding your question, there's no damage being done to anything; the minimum voltage across the LED is 0 V (well below its maximum peak inverse voltage), while the maximum voltage across the LED is around 2 V, if you use the highly recommended current-limiting resistors (220/330 ohms is good) in series between each cathode and its Arduino digital pin.
Without any resistors, you will be drawing a lot of current through each pin, in total, a lot more than the Nano can safely supply. Use resistors that limit the current through each LED to 10-20mA.


text:
Need help with my project
Can anyone give me the full code of my project because my code is not working?
My aim is that when the Z axis of an accelerometer is below 370 and a pushbutton connected to a pin 2 becomes high, then pin 13 turns high and remains high.  When the Z axis is above 370 and pushbutton is high then the pin 13 goes low and remains low.
P.S I am also a noob to Arduino
Here is my code :
const int ledPin = 13;
const int threshold = 370;
const int pull_up_resistor = 12;
const int pull_down_resistor = 11;
const int groundpin = A1;
const int powerpin = A5;
const int xpin = A2;
const int ypin = A3;
const int zpin = A4;

int pushButton = 2;

void setup() {

  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);

  Serial.begin(9600);

  pinMode(pushButton, INPUT);
  digitalWrite(pushButton, HIGH);
  Serial.begin(9600);

  pinMode(groundpin, OUTPUT);
  pinMode(powerpin, OUTPUT);
  digitalWrite(groundpin, LOW);
  digitalWrite(powerpin, HIGH);
}

void loop() {

  int buttonState = digitalRead(pushButton);

  Serial.println(buttonState);
  delay(100);        // delay in between reads for stability

  Serial.print(analogRead(xpin));

  Serial.print("\t");
  delay(100);
  Serial.print(analogRead(ypin));

  Serial.print("\t");
  delay(100);
  Serial.print(analogRead(zpin));
  Serial.println();

  delay(100);

  if (buttonState = 0) {
    digitalWrite( ledPin, HIGH);
  }
  if (buttonState = 1) {
    digitalWrite (pushButton, LOW);
  }

}

You can format your code nicely in the Arduino IDE before pasting it here. This is clearly wrong: if (buttonState = 1). You need a double equals.

I got bored after the 400th word of the first sentence OK ...

... and I think you forgot to take your Ritalin this morning ...

You also seem to be a noob at English. How about re-writting the question so that it makes more sense and doesn't stop mid sentence. Obvious errors - = in place of ==, you never set ledPin low, you are writing to your button input, you initalize the serial port 3 times. And seeing digital outputs called powerpin and goundpin make me worry that you've made some very bad mistakes wiring things up.

Use some formatter before posting it here. For example here is great one, written by KrzaQ edit: didn't noticed that was fixed by Mark
Next thing to do is keep your code clean. Three times you initialized Serial communcation. Why?
You should also first initalize Serial then set pinModes into state and then put digitalWrite. It helps reading the code.
Example:
Serial.begin(value);
pinMode(x,x);
pinMode(y,x);
pinMode(z,x);
digitalWrite(x,x);
digitalWrite(y,x);
digitalWrite(z,x);

More readable, isn't it?
Next step: Pull-up and pull-down resistors... It is not thing you need to set in your code. It is hardware connection of 1 resistor, sometimes capacitor and device. There is no use for it in your device.
Read about them here: Pull-up/pull-down
Next thing: You must not define your outputs as power pins and treat them like one. AVR's have limited power output from each pin and by doing so you can fry it very quickly.
If I understand your sentence correctly you need to save your angle values into variable like this (pseudo code, you have to adjust it to your case no one will write it for free):
int xvalue, yvalue, zvalue, button;
void setup(); // all setup should go here do not skip this like me here
void loop() {
  xvalue = analogRead(xpin);
  yvalue = analogRead(ypin);
  zvalue = analogRead(zpin);
  if (button == 1) {
    if (zvalue > 370)
      digitalWrite(ledPin, HIGH);
    else
      digitalWrite(ledPin, LOW);
  } else
    actionWhenPushButtonIsZero();
}

If you think about what I wrote and focus on your task I am sure that everything will work in your device. THINK first then ask next questions.


text:
Arduino IDE fails on Fedora with arduino-builder error "Parameter 'tools' is mandatory"
The arduino-builder app when invoked directly with parameter --tools /usr/bin works, but the IDE fails with the error in the title for any sketch (including the Blink example).
I've tried adding things to preferences.txt like
tools.path=/usr/bin

And variations, but I keep getting the same failure in the IDE.  This is using a fresh distro package install on Fedora 27 (I did not have this problem previously using Fedora 25).

I'd be interested to hear whether the official version of the Arduino IDE downloaded from https://www.arduino.cc/en/Main/Software also has this issue. I've noticed the Arduino IDE version that is in the package managers is always mucked around with so you will encounter strange bugs like this that don't happen with the official version.

Thanks a lot my friend!!!!! All is working

I don't understand why this worked, but I found this comment in Redhat Bugzilla (it doesn't seem to be a bug report specifically about that...but anyway):

Parameter 'tools' is mandatory
    [...]

However, if I create the packages directory in ~/.arduino15, compilation now works.
mkdir ~/.arduino15/packages

Seemed like an easy thing to try, and voila -- after an hour of fuss.
I do not understand why this is so (nothing ends up in that directory, either) but I'm leaving this in hopes it may save someone else some time.

Yep, this looks stupid, but works :)

Yep, worked! Thanks.

I'm glad you posted this. I just updated to Fedora 33 and the latest Arduino IDE to find this issue.

The problem occurs because arduino does not have permission to modify directory in /usr/share/arduino to create tools-builder
All you have to do is navigate to usr/share/arduino create 'tool-builder' directory
sudo mkdir /usr/share/arduino/tools-builder

This is what I needed to do. Fedora 27, arduino IDE 1.8.4

Ditto for Fedora 32

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


text:
Store String using F() Macro
I'm new to the Arduino and do not quite understand the F() macro yet.
In my code, I have a String, and as I want to transfer it via WebServer, I need to write it to the answer.
Somehow I need to convert the String, to fit it into the fastrprintln() function.
String weather_json = getWeatherData();
char weather[2048];
weather_json.toCharArray(weather,2048);
client.fastrprintln(F(weather));

Do you have any idea for me?

What do you mean by "I need to write it to the answer."? Is that a typo?

The F() macro is for literals (eg. F("foo") ) not variables.

“I need to convert the String, to fit it into the fastrprintln() function.” No, you don't: client.println(getWeatherData());

The Arduino core macro F() takes a string literal and forces the compiler to put it in program memory. This reduces the amount of SRAM needed as the string is not copied to a data memory buffer. Special functions are required to access the data stored in program memory. The Arduino core hides a lot of the typical usages such as:
Serial.println(F("Hello world"));

Further details of the low level access program memory access may be found in the AVR GCC libc documentation. The F() macro is defined as:
class __FlashStringHelper;
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper*>(PSTR(string_literal)))

The FlashStringHelper class is used to help the compiler recognize this type of string literal when passed to Arduino functions. Below are some examples:
// String constructor with program memory string literal
String::String(const __FlashStringHelper *str);

// Print (Serial, etc) of program memory string literal
size_t Print::print(const __FlashStringHelper *);
size_t Print::println(const __FlashStringHelper *);

You should not use the Arduino core F() macro with anything other than a string literal.

I was having an issue with my program locking up so after reading your answer I added the F() macro to my string literals and that was literally all it took to resolve this issue. I must be lower on memory than I had previously imagined.. Anyway, thanks for introducing me to this lock-up saving macro.


text:
How can I load fonts into Adafruit GFX for TFT display (ILI9341)
I get a compile error when I try to set a different font in Adafruit GFX on a TFT display on my Arduino Uno.
I'm testing a new TFT shield for Arduino equipped with an ILI9341 by using the Adafuit GFX libraries and examples. The test program supplied with the library works fine out of the box displaying text and all kind of drawings on the screen.
However, the standard font built into the Adafruit GFX library is "blocky" to save memory space. They do provide other fonts, but I get an error when I try to invoke them.
The segment of code that throws the compile error is this one:
unsigned long testText1() {
  tft.setFont();    // When I remove this line the sketch compiles OK
  tft.fillScreen(BLACK);
  tft.setCursor(0, 50);
  tft.setTextColor(RED);
  tft.setTextSize(13);
  tft.println("1234");
}

When compiling I get this error:

"error: ‘class Adafruit_ILI9341_8bit_AS’ has no member named ‘setFont’"

According to Adafruit's GFX manual, the setFont() procedure allows to define a new font or revert to the standard one.
I examined the libraries and nowhere could I find a procedure to select a font, yet the example has declarations like these below, so changing fonts should be possible:
#include <Adafruit_GFX_AS.h>
#include <Adafruit_ILI9341_8bit_AS.h>
#include <Font16.h>
// #include <Font32.h>
// #include <Font64.h>
// #include <Font72.h>
#include <Font7s.h>
#include <Load_fonts.h>

I would like to load the 7segment font with:
tft.setFont(&Font7s);

Does anybody have experience to share loading these fonts?

Tested on Windows, with newest libraries Adafruit-GFX and  Adafruit_PCD8544 (Nokia5110 LCD connected to Arduino Nano).
#include <Fonts/FreeSerifBold12pt7b.h>

and then
matrix.setFont(&FreeSerifBold12pt7b);

Then there is one very important difference how to use function drawChar(...). Coordinates of character (x,y) begins in left-bottom corner of character instead of top-left corner so this will not work (you will see only about 1 px of character):
matrix.drawChar(0,0,'1', 1, 0, 6),

Use this to show all pixels of character:
matrix.drawChar(20,20,'1', 1, 0, 6),

Full manual for using fonts here: Adafruit GFX Graphics Library - Using Fonts

Newer versions of the library CAN use fonts.
#include <Fonts/FreeSerifBold12pt7b.h>

and then...
matrix.setFont(&FreeSerifBold12pt7b);

Whether they work or not, I dunno. Case closed, lol!

Looking further into documentation on the Adafruit website they indicate that indeed, their GFX library published on GitHub does not handle different fornts.
Case closed :-)

Cosa, https://github.com/mikaelpatel/Cosa, supports both this display and has multiple fonts. Fonts example sketch: https://github.com/mikaelpatel/Cosa/blob/master/libraries/Canvas/examples/CosaCanvasFonts/CosaCanvasFonts.ino


text:
Arduino IR remote control hold value
I am trying to make a remote controlled robot with Arduino and the IR remote control is kinda weird. When I press a button, sometimes I get the right hex value, other time I get the hold value FFFFFF.
How can I implement some code so that I can, for example, run the motors as long as I hold the button or detect which button it was since the hold code is the same for all codes?
Since I know that the hold value is 0xFFFFFFFF, is there a function that:
(any hex not 0xffff) func(OR?) (0xffffffff) = (any hex ...)

and
( 0xfffff)           func (0xffffff)   != (0xffffff)

Or do I need to implement some kind of state machine? It is kinda difficult with the delay() as well.
By the way, I'm using Keyes KY 022. What are the signal length times? (I don't have an oscilloscope).
Maybe would be useful to set the press value to other? Or to ignore it?
LE: And some code to test: one single key:
Maybe other libraries are interrupting the timer...
    #include <IRremote.h>
    #define IR_PIN 11
    IRrecv irrecv(IR_PIN);
    decode_results results;
    long int Key;
    const unsigned long int UP = 0x00FF629D;
    const unsigned long int DOWN = 0x00FFA857;
    const unsigned long int LEFT = 0x00FF22DD;
    const unsigned long int RIGHT = 0x00FFC23D;
    const unsigned long int OK = 0x00FF02FD;
    const unsigned long int k1 = 0x00FF6897;// C101E57B
    const unsigned long int k2 = 0x00FF9867;// 97483BFB
    const unsigned long int k3 = 0x00FFB04F;// F0C41643
    const unsigned long int k4 = 0x00FF30CF;
    const unsigned long int k5 = 0x00FF18E7;
    const unsigned long int k6 = 0x00FF7A85;
    const unsigned long int k7 = 0x00FF10EF;
    const unsigned long int k8 = 0x00FF38C7;
    const unsigned long int k9 = 0x00FF5AA5;
    const unsigned long int STAR = 0x00FF42BD;
    const unsigned long int k0 = 0x00FF4AB5;
    const unsigned long int HASH = 0x00FF52AD;
    const unsigned long int HOLD = 0xFFFFFFFF;

   void setup(){
   // put your setup code here, to run once:
      Serial.begin(9600);
      delay(2000); while (!Serial);
      irrecv.enableIRIn();
  //irrecv.blink13(true);
  //setup1(); From IRremoteInfo TAB
   }
char buff[1000];
unsigned long int msg;
void processIR(unsigned long int msg)
{
  sprintf(buff, "READ IR %x \n", results.value);
  Serial.print(buff);
  switch (msg)
  {
    case UP:
      Serial.println("UP");
      break;
    case DOWN:
      Serial.println("DOWN");
      break;
    case LEFT:
      Serial.println("LEFT");
      break;
    case RIGHT:
      Serial.println("RIGHT");
      break;
    case k1:
      Serial.println("k1");
      break;
    case k2:
      Serial.println("k2");
      break;
    case k3:
      Serial.println("k3");
      break;
    case k4:
      Serial.println("k4");
      break;
    case k5:
      Serial.println("k5");
      break;
    case k6:
      Serial.println("k6");
      break;
    case k7:
      Serial.println("k7");
      break;
    case k8:
      Serial.println("k8");
      break;
    case k9:
      Serial.println("k9");
      break;
    case STAR:
      Serial.println("STAR");
      break;
    case k0:
      Serial.println("k0");
      break;
    case HASH:
      Serial.println("HASH");
      break;
    case HOLD:
      Serial.println("HOLD");
      break;
      //case default:
      //    delay(500);
      //       irrecv.decode(&results);
      //       msg = results.value;
      //       processIR(msg);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  if (irrecv.decode(&results))
  {
    irrecv.resume();
    char buff[255];
    sprintf(buff, "Val %010x \n " , results.value );
    Serial.print(buff);
    //results.decode();
    //results.DumpResults();
    //      msg = results.value;
    //      Serial.println(msg, HEX);
    //      Serial.println(results.decode_type);
    //      processIR(msg);

  }

}

And values, of course:
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x000002fd
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x000022dd
 Val 0x0000ffff
 Val 0x0000c23d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x00005282
 Val 0x000038d6
 Val 0x0000ffff
 Val 0x0000efb5
 Val 0x00006897
 Val 0x00006897
 Val 0x00006897
 Val 0x0000ffff
 Val 0x00006897
 Val 0x00006897
 Val 0x0000ffff
 Val 0x00006897
 Val 0x00009867
 Val 0x00009867
 Val 0x0000b04f
 Val 0x0000ffff
 Val 0x00004794
 Val 0x00009424
 Val 0x0000ffff
 Val 0x000042bd
 Val 0x0000ffff
 Val 0x00004ab5
 Val 0x0000ffff
 Val 0x000052ad
 Val 0x0000ffff
 Val 0x00004ab5
 Val 0x00005aa5
 Val 0x0000ffff
 Val 0x000038c7
 Val 0x000010ef
 Val 0x0000ffff
 Val 0x000030cf
 Val 0x0000ffff
 Val 0x000018e7
 Val 0x0000ffff
 Val 0x00007a85
 Val 0x0000ffff
 Val 0x00004ec5
 Val 0x00007a2a
 Val 0x00007d4f
 Val 0x0000a33f
 Val 0x00007a28
 Val 0x00008dd8
 Val 0x00004b78
 Val 0x0000144b
 Val 0x00006781
 Val 0x0000040a
 Val 0x0000ffbf
 Val 0x00007d4f
 Val 0x0000ee7c
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff

So each press of a key gives 2 values.

char buff[1000]; - what Arduino is this? You know Arduinos generally don't have a lot of RAM? Using 1000 bytes to hold READ IR abcd \n seems a little excessive.

Yes, I know. Was just testing ... Maybe the real question when I changed the size was if "sprintf() overflows" Maybe it is, but it just overflowed, but didn't had any shellcode.

If I understand your question correctly, a button press will first generate a distinct hex code, and then after a while a series of 0xFFFFFF?
In that case, why don't you simply store the last distinct code you received, and replace occurrences of 0xFFFFFF with the stored code?

I found out that by adding this while loop to an IRremote use, the code after it won't run until the button is released.
while(irrecv.decode(&results)){
    irrecv.resume();
    delay(150);
}

This will keep the buttons pressed if the code at the end on loop() ends the input.

Man you are a genius! it works :)


text:
How to solve "error 2" from the Arduino MPU6050 accelerometer
I'm new to Arduino and Stack Exchange. I've been building a fitness tracker and am receiving a certain error in the serial monitor. The accelerometer seems the work, but it seems to go to sleep after a while. I'm using an Arduino Uno (for the time being), a Bluetooth HC-05 module and an MPU6050 accelerometer. I connect it to an app, Retroband to monitor the steps taken and calories burnt.
I've wired it like this:
Accelerometer:
 SDA-A4
 SCL-A5
 VCC-3.3v
 GND-GND

Bluetooth:
 VCC-3.3v
 GND-GND
 TX-2
 RX-3

Here is the code I'm using:
#include <math.h>
#include <Wire.h>
#include <SoftwareSerial.h>

/* Bluetooth */
SoftwareSerial BTSerial(2, 3); //Connect HC-06. Use your (TX, RX) settings

/* time */
#define SENDING_INTERVAL 1000
#define SENSOR_READ_INTERVAL 50
unsigned long prevSensoredTime = 0;
unsigned long curSensoredTime = 0;

/* Data buffer */
#define ACCEL_BUFFER_COUNT 125
byte aAccelBuffer[ACCEL_BUFFER_COUNT];
int iAccelIndex = 2;

/* MPU-6050 sensor */
#define MPU6050_ACCEL_XOUT_H 0x3B // R
#define MPU6050_PWR_MGMT_1 0x6B // R/W
#define MPU6050_PWR_MGMT_2 0x6C // R/W
#define MPU6050_WHO_AM_I 0x75 // R
#define MPU6050_I2C_ADDRESS 0x68

typedef union accel_t_gyro_union {
  struct {
    uint8_t x_accel_h;
    uint8_t x_accel_l;
    uint8_t y_accel_h;
    uint8_t y_accel_l;
    uint8_t z_accel_h;
    uint8_t z_accel_l;
    uint8_t t_h;
    uint8_t t_l;
    uint8_t x_gyro_h;
    uint8_t x_gyro_l;
    uint8_t y_gyro_h;
    uint8_t y_gyro_l;
    uint8_t z_gyro_h;
    uint8_t z_gyro_l;
  } reg;

  struct {
    int x_accel;
    int y_accel;
    int z_accel;
    int temperature;
    int x_gyro;
    int y_gyro;
    int z_gyro;
  } value;
};

void setup() {
  int error;
  uint8_t c;

  Serial.begin(9600);
  Wire.begin();
  BTSerial.begin(9600);  // set the data rate for the BT port

  // default at power-up:
  // Gyro at 250 degrees second
  // Acceleration at 2g
  // Clock source at internal 8MHz
  // The device is in sleep mode.
  //
  error = MPU6050_read (MPU6050_WHO_AM_I, &c, 1);
  Serial.print(F("WHO_AM_I : "));
  Serial.print(c,HEX);
  Serial.print(F(", error = "));
  Serial.println(error,DEC);

  // According to the datasheet, the 'sleep' bit
  // should read a '1'. But I read a '0'.
  // That bit has to be cleared, since the sensor
  // is in sleep mode at power-up. Even if the
  // bit reads '0'.
  error = MPU6050_read (MPU6050_PWR_MGMT_2, &c, 1);
  Serial.print(F("PWR_MGMT_2 : "));
  Serial.print(c,HEX);
  Serial.print(F(", error = "));
  Serial.println(error,DEC);

  // Clear the 'sleep' bit to start the sensor.
  MPU6050_write_reg (MPU6050_PWR_MGMT_1, 0);

  initBuffer();
}

void loop() {
  curSensoredTime = millis();

  // Read from sensor
  if(curSensoredTime - prevSensoredTime > SENSOR_READ_INTERVAL) {
    readFromSensor();  // Read from sensor
    prevSensoredTime = curSensoredTime;

    // Send buffer data to remote
    if(iAccelIndex >= ACCEL_BUFFER_COUNT - 3) {
      sendToRemote();
      initBuffer();
      Serial.println("------------- Send 20 accel data to remote");
    }
  }
}

/**************************************************
 * BT Transaction
 **************************************************/
void sendToRemote() {
  // Write gabage bytes
  BTSerial.write( "accel" );
  // Write accel data
  BTSerial.write( (char*)aAccelBuffer );
  // Flush buffer
  //BTSerial.flush();
}

/**************************************************
 * Read data from sensor and save it
 **************************************************/
void readFromSensor() {
  int error;
  double dT;
  accel_t_gyro_union accel_t_gyro;

  error = MPU6050_read (MPU6050_ACCEL_XOUT_H, (uint8_t *) &accel_t_gyro, sizeof(accel_t_gyro));
  if(error != 0) {
    Serial.print(F("Read accel, temp and gyro, error = "));
    Serial.println(error,DEC);
  }

  // Swap all high and low bytes.
  // After this, the registers values are swapped,
  // so the structure name like x_accel_l does no
  // longer contain the lower byte.
  uint8_t swap;
  #define SWAP(x,y) swap = x; x = y; y = swap
  SWAP (accel_t_gyro.reg.x_accel_h, accel_t_gyro.reg.x_accel_l);
  SWAP (accel_t_gyro.reg.y_accel_h, accel_t_gyro.reg.y_accel_l);
  SWAP (accel_t_gyro.reg.z_accel_h, accel_t_gyro.reg.z_accel_l);
  SWAP (accel_t_gyro.reg.t_h, accel_t_gyro.reg.t_l);
  SWAP (accel_t_gyro.reg.x_gyro_h, accel_t_gyro.reg.x_gyro_l);
  SWAP (accel_t_gyro.reg.y_gyro_h, accel_t_gyro.reg.y_gyro_l);
  SWAP (accel_t_gyro.reg.z_gyro_h, accel_t_gyro.reg.z_gyro_l);

  // Print the raw acceleration values
  Serial.print(F("accel x,y,z: "));
  Serial.print(accel_t_gyro.value.x_accel, DEC);
  Serial.print(F(", "));
  Serial.print(accel_t_gyro.value.y_accel, DEC);
  Serial.print(F(", "));
  Serial.print(accel_t_gyro.value.z_accel, DEC);
  Serial.print(F(", at "));
  Serial.print(iAccelIndex);
  Serial.println(F(""));

  if(iAccelIndex < ACCEL_BUFFER_COUNT && iAccelIndex > 1) {
    int tempX = accel_t_gyro.value.x_accel;
    int tempY = accel_t_gyro.value.y_accel;
    int tempZ = accel_t_gyro.value.z_accel;
    /*
    // Check min, max value
    if(tempX > 16380) tempX = 16380;
    if(tempY > 16380) tempY = 16380;
    if(tempZ > 16380) tempZ = 16380;

    if(tempX < -16380) tempX = -16380;
    if(tempY < -16380) tempY = -16380;
    if(tempZ < -16380) tempZ = -16380;

    // We dont use negative value
    tempX += 16380;
    tempY += 16380;
    tempZ += 16380;
    */
    char temp = (char)(tempX >> 8);
    if(temp == 0x00)
      temp = 0x7f;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;
    temp = (char)(tempX);
    if(temp == 0x00)
      temp = 0x01;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;

    temp = (char)(tempY >> 8);
    if(temp == 0x00)
      temp = 0x7f;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;
    temp = (char)(tempY);
    if(temp == 0x00)
      temp = 0x01;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;

    temp = (char)(tempZ >> 8);
    if(temp == 0x00)
      temp = 0x7f;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;
    temp = (char)(tempZ);
    if(temp == 0x00)
      temp = 0x01;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;
  }

  // The temperature sensor is -40 to +85 degrees Celsius.
  // It is a signed integer.
  // According to the datasheet:
  // 340 per degrees Celsius, -512 at 35 degrees.
  // At 0 degrees: -512 - (340 * 35) = -12412
//  Serial.print(F("temperature: "));
//  dT = ( (double) accel_t_gyro.value.temperature + 12412.0) / 340.0;
//  Serial.print(dT, 3);
//  Serial.print(F(" degrees Celsius"));
//  Serial.println(F(""));

  // Print the raw gyro values.
//  Serial.print(F("gyro x,y,z : "));
//  Serial.print(accel_t_gyro.value.x_gyro, DEC);
//  Serial.print(F(", "));
//  Serial.print(accel_t_gyro.value.y_gyro, DEC);
//  Serial.print(F(", "));
//  Serial.print(accel_t_gyro.value.z_gyro, DEC);
//  Serial.println(F(""));
}

/**************************************************
 * MPU-6050 Sensor read/write
 **************************************************/
int MPU6050_read(int start, uint8_t *buffer, int size)
{
  int i, n, error;

  Wire.beginTransmission(MPU6050_I2C_ADDRESS);

  n = Wire.write(start);
  if (n != 1)
    return (-10);

  n = Wire.endTransmission(false); // hold the I2C-bus
  if (n != 0)
    return (n);

  // Third parameter is true: relase I2C-bus after data is read.
  Wire.requestFrom(MPU6050_I2C_ADDRESS, size, true);
  i = 0;
  while(Wire.available() && i<size)
  {
    buffer[i++]=Wire.read();
  }
  if ( i != size)
    return (-11);
  return (0); // return : no error
}

int MPU6050_write(int start, const uint8_t *pData, int size)
{
  int n, error;

  Wire.beginTransmission(MPU6050_I2C_ADDRESS);

  n = Wire.write(start); // write the start address
  if (n != 1)
    return (-20);

  n = Wire.write(pData, size); // write data bytes
  if (n != size)
    return (-21);

  error = Wire.endTransmission(true); // release the I2C-bus
  if (error != 0)
    return (error);
  return (0); // return : no error
}

int MPU6050_write_reg(int reg, uint8_t data)
{
  int error;
  error = MPU6050_write(reg, &data, 1);
  return (error);
}

/**************************************************
 * Utilities
 **************************************************/
void initBuffer() {
  iAccelIndex = 2;
  for(int i=iAccelIndex; i<ACCEL_BUFFER_COUNT; i++) {
    aAccelBuffer[i] = 0x00;
  }
  aAccelBuffer[0] = 0xfe;
  aAccelBuffer[1] = 0xfd;
  aAccelBuffer[122] = 0xfd;
  aAccelBuffer[123] = 0xfe;
  aAccelBuffer[124] = 0x00;
}

This is the error I got in serial monitor:
    WHO_AM_I : 0, error = 2
PWR_MGMT_2 : 0, error = 2
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, -3840, at 2
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 8
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 14
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 20
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 26
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 32
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 38
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 44
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 50
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 56
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 62
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 68
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 74
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 80
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 86
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 92
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 98
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 104
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 110
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 116

I'm not too good at Arduino, and any help will be immensely appreciated.

What is missing to be able to help you with this?

Function MPU6050_read is never defined. You are obviously using a library, but unless you tell us which one you can't get any support

The code is for MPU6050 which is an I2C device but adxl335 is an analog device?!?!

It looks defined to me - it's sat there in the code...  By the way, error 2 is "TW_MT_SLA_NACK" which is "error: address send, nack received"

Sorry, I am using the MPU6050. My bad!

Please provide the wiring. The error code says that the MPU is not detected. Have you the correct address? Do you have the right pullup resistors?

Okay, there's the wiring.

Which version of the Uno are you using?

I have got same problem and you can solve it in minutes! Firstly check all your I2C addresses with same code:
#include "Wire.h"

byte start_address = 0;
byte end_address = 127;

void setup()
{
  byte rc;
  Wire.begin();

  Serial.begin(9600);
  Serial.println("\nI2C Scanner");

  Serial.print("Scanning I2C bus from ");
  Serial.print(start_address,DEC);  Serial.print(" to ");  Serial.print(end_address,DEC);
  Serial.println("...");

  for( byte addr  = start_address;
            addr <= end_address;
            addr++ ) {
      Wire.beginTransmission(addr);
      rc = Wire.endTransmission();

      if (addr<16) Serial.print("0");
      Serial.print(addr,HEX);
      if (rc==0) {
        Serial.print(" found!");
      } else {
        Serial.print(" "); Serial.print(rc); Serial.print("     ");
      }
      Serial.print( (addr%8)==7 ? "\n":" ");
  }

  Serial.println("\n-------------------------------\nPossible devices:");

  for( byte addr  = start_address;
            addr <= end_address;
            addr++ ) {
      Wire.beginTransmission(addr);
      rc = Wire.endTransmission();
      if (rc == 0) {
        Serial.print(addr,HEX); Serial.print(" = ");
        switch (addr) {
          case 0x50: Serial.println("AT24C32/AT24C64 - EEPROM"); break;
          case 0x68: Serial.println("DS1307"); break;
          default: Serial.println("Unknown"); break;
        }
      }
  }

  Serial.println("\ndone");
}

// standard Arduino loop()
void loop()
{
    // Nothing to do here, so we'll just blink the built-in LED
    digitalWrite(13,HIGH); delay(300);
    digitalWrite(13,LOW);  delay(300);
}

And you will get something like this:
I2C Scanner
Scanning I2C bus from 0 to 127...
00 2      01 2      02 2      03 2      04 2      05 2      06 2      07 2
08 2      09 2      0A 2      0B 2      0C 2      0D 2      0E 2      0F 2
10 2      11 2      12 2      13 2      14 2      15 2      16 2      17 2
18 2      19 2      1A 2      1B 2      1C 2      1D 2      1E 2      1F 2
20 2      21 2      22 2      23 2      24 2      25 2      26 2      27 2
28 2      29 2      2A 2      2B 2      2C 2      2D 2      2E 2      2F 2
30 2      31 2      32 2      33 2      34 2      35 2      36 2      37 2
38 2      39 2      3A 2      3B 2      3C 2      3D 2      3E 2      3F 2
40 2      41 2      42 2      43 2      44 2      45 2      46 2      47 2
48 2      49 2      4A 2      4B 2      4C 2      4D 2      4E 2      4F 2
50 2      51 2      52 2      53 2      54 2      55 2      56 2      57 2
58 2      59 2      5A 2      5B 2      5C 2      5D 2      5E 2      5F 2
60 2      61 2      62 2      63 2      64 2      65 2      66 2      67 2
68 2      69 found! 6A 2      6B 2      6C 2      6D 2      6E 2      6F 2
70 2      71 2      72 2      73 2      74 2      75 2      76 2      77 2
78 2      79 2      7A 2      7B 2      7C 2      7D 2      7E 2      7F 2

-------------------------------
Possible devices:
69 = Unknown

done

The address 69 is your device, MPU-6050! Now check your code and you can see that you use:
#define MPU6050_I2C_ADDRESS 0x68

But you must use the correct address of MPU, change it:
#define MPU6050_I2C_ADDRESS 0x69

Code source.

I have added a link to the original author and removed the bold

From examination of the sketch, the error '2' that you are seeing is returned from MPU6050_read(), by the line
n = Wire.endTransmission(false); // hold the I2C-bus

Looking at the reference for the Wire library, endTransmission() returns 2 when

2:received NACK on transmit of address

So, when you transmit to the MPU6050, the MPU6050 appears to be returning a Not Acknowledged (NACK) packet.
Why a NACK is being returned is not too clear. From Mpu6050 - error 2 - endTransmission:

It means the chips is either not connected (or not correctly) or the wrong address was sent.

From the MPU-6050 page on Arduino Playground, it seems that the address should be 0x68 or 0x69

The pin "AD0" selects between I2C address 0x68 and 0x69. That makes it possible to have two of these sensors in a project. Most breakout boards have a pullup or pulldown resistor to make AD0 default low or high. Connect AD0 to GND or 3.3V for the other I2C address.

What is AD0 connected to? You do not mention that, in your wiring list for the MPU-6050. If you connect AD0 to GND then address 0x68 is used, if it is to 3.3V then the address is 0x69. From MPU6050 SparkFun Breakout to Arduino Uno - No Communication.

AD0 must be connected to ground or 3.3V (with solder jumper). Connect it to ground for I2C address 0x68.
  SCL and SDA are connected directly to the Arduino, but you could add extra pull-up resistors to the 3.3V. The resistors could be 4k7 or 10k (the board already has 10k pull-up resistors, but I prefer 4k7).
  You don't need the INT, you could leave it open.
  The CLKIN and FSYNC can be tied to ground, because they are not used.

I would suggest checking your wiring, and look for any loose contacts on the MPU6050 board.

You have a problem that you can see (the error 2) and a theory about what might be causing it (the accelerometer going to sleep). That's a great place to start from!
I have a few of suggestions to make:

Collect documentation for the components you are using, a data sheet for the accelerometer, tutorials and instructions for the code to drive it, etc.
A search on:
MPU6050 accelerometer data sheet
is likely to get you lots of links to sites hosting data sheets for the accelerometer. With luck you'll be able to find the actual vendor and in addition to the data sheet you may able to find application notes there as well.
For the library, you may find a tutorial or an API description on the site where you downloaded it. You can also do a search on something like:
MPU6050 accelerometer tutorial
to find suggestions for how to get started with the device and the code to use it. Tutorials often have sections on testing and avoiding common pitfalls with the device.
Once you have some documentation see what you can learn about the error. Who generates "error 2?" What does it mean? When does it occur? Once you understand the problem, the answer may be obvious.
Create minimal test cases. The code sample above is a lot for you, or us, to make sense of and then to test/debug. Pare your code down (or build it up, depending where you are in the process and how you like to work on problems) until you have the minimum code needed to test the accelerometer.
Do you see the problem in that code? If you do, then you have many fewer possible problems to look at. If you don't, then add the next piece – perhaps in this case, try to exercise the condition that "error 2" is supposed to report (does it still seem likely that "going to sleep" is the problem?

If you're still stumped at this point you've got the resources at hand to post a great question and the evidence that you've worked on it and understand it for yourself will go a long way towards establishing good will with the people who are trying to help you find answers.
Since this is (potentially) a hardware and a software problem, be sure to include an accurate schematic, or photo, of how your project is put together. If you are using someone else's schematic be especially cautious of any potential differences!

authors: ابو ريان حيمور

authors: عيسى عبد العزيز


text:
Flashing ESP8266
I can't flash my ESP8266 (ESP-01). I have 3.3 V and ground connected, Rx to Tx and Tx to Rx on my USB to serial adapter. I also have GPIO0 connected to ground too.
I am using an external power supply but the USB adapter and power adapter share a common ground.
I'm using a Mac and ESP tools to flash it, and it has worked before.
The command I am using is:
sudo ./esptool.py --port /dev/tty.wchusbserial1410 write_flash 0x00000 AT22SDK10020150320boot12.bin

But the response is:
A fatal error occurred: Failed to connect to ESP8266

This make me think something is wrong with receiving data from the ESP because when attempting to connect, the ESP's blue LED flashes.
My USB to serial adapter works fine though as I've tested it with my Arduino.

CH_PD must also be connected to 3.3v

If you've got led flashes and signs of activity and such a non-descriptive error, just try disconnecting / reconnecting and try again (if you havent already)

Did you ever find a solution to this?

@mh00h yes, I just bought a new one. Wasn't worth spending time on when they're as cheap as they are.


text:
The importance of I/O pin DC current
I am thinking about buying Arduino or Raspberry Pi.  I generally know Arduino advantages (fast start-up, low consumption, ADC converters) and disadvantages (low memory, low connectivity, hard programming), but I simply cannot figure out maybe the most important issue: current output for controlling devices.
One of the common cited advantages of Arduino system compared to Raspberry Pi system is that power per I/O pin is much larger.  Arduino Uno allegedly has up to 20 mA @ 5 V per pin and 50 mA @ 3.3 V per pin making quite substantial power of 0.15 W, compared to say typical 10 mA @ 5 V per pin for Raspberry Pi (although there is no official number available).
On the other hand

this power is far too low to control any motors and you still have to
provide shields,
new version Arduino 101 reduced that current to 20 mA and even less for some other Arduino models.

So, what is really the importance (if any) of these higher currents for home projects, compared between different Arduinos themselves and compared to Raspberry Pi?
There is also a question of total current for all pins together, which is also limited, but it is soooooo difficult to get official limits (for both Arduino and Raspberry Pi).
Please give me some insight into this issue, so I can decide.

I have a silly question which might help - how much drive current does your project actually need? Do you have lots of LEDs (which an Arduino might be able to handle directly) or are you driving motors (which all common microcontrollers will need a driver circuit for)?

The problem is that I need microcontroller for learning and playing and I do not want to limit my ideas by bad choice of device in advance.

The simple answer is: It doesn't matter.
Both Arduino and the Raspberry Pi, and every other common microcontroller board, are designed to control things, not provide power to things.
Digital IO pins aren't designed to drive heavy loads. Yes, some (like the Arduino) can provide slightly more current, but that is really unimportant for most projects.
Yes, some boards have more powerful power supply circuits on them so you can draw more current from their power supplies, but again that is largely irrelevant.
The one thing that you seem to be forgetting (or haven't realised) is that the microcontroller board does not have to supply all the power.
The Arduino, Pi, Teensy, chipKIT, whatever, is merely a controller. If your system needs more current it is up to you to provide that current. The Arduino etc merely controls the circuit or device that it is connected to.
It is very common to have multiple power supplies in a large project - each providing different voltages, or being used for different specific tasks within the project.
Just one thing you need to remember: Connect the grounds.

...or use an opto-isolator ;)

@fabrosell ... or a relay ... or an arrangement of motors, pulleys, elastic bands, and small rodents.

Where can I get this small-rodent-isolator? mouser.com?

I mean, you can avoid connecting grounds if you use an opto-coupler.

@gerbem of course. They specialize in them.

So Arduino 101 should't be worse than Arduino Uno in any aspect?

@Pygmalion As long as you're not driving heavy loads, and interfacing things with the correct driver circuits, then there should be no real difference

After doing a lot of study I realized that opto isolators are themselves current hungry devices.  So if you need, say input 20 mA to run opto isolator you are back to square one.  Or are there some low-current opto isolators?

You don't need 20mA to run an optoisolatoe. That value is an upper limit. Check the datashete and look at the pretty graphs to see the switching characteristics. Most will switch from aroud 5mA.

Since RPi provides pathetic total 50mA for all GPIO combined (to use all 17 pins you need at least 17*5mA = 85mA, not mentioning usage of SPI and I2C), it seems that RPi sucks for serious projects.  Do you know by any chance what is total current for all pins for Arduino 101?

Nobody outside of intel knows and they aren't telling anyone.

Oh well.  Arduino and RPi are great projects, but occasionally I get an impression that some details are not well conceived.  They are particularly tight with currents...

My conclusion would be "Both Arduino and the Raspberry Pi are designed to control things, but they did not really provide enough current to safely use all control pins." :)

@Pygmalion That depends on how you define "use". Drive heavy loads - not always. Interface with logic and other similar devices - perfectly adequate.

I partially agree.  But let stop here and not turn this discussion into a flame.

Bottom line is: the controllers are just not meant for supplying power.
They do have the ability to do so, within limits - fairly stringent limits for a controller chip itself, and slightly more generous limits for the on-board power supply. If you really need an all-in-one, you might consider making building your own controller board with a more capable on-board power supply and a number of transistor switches to provide power for the hungrier devices, that can be switched by the MCU chip.
Note that this will not improve the chip's ability to supply power - you can't, by any practical means - but the board can, through the switching transistors.
Figure out your project's power budget, or the budget you'd like to have for your future projects, and design an on-board power supply to exceed that by a healthy margin-of-safety. Likewise, for the individual switched circuits, in order to choose a sufficiently robust switching transistor.
If you prefer an off-the-shelf solution, one of the available motor-driver boards is probably a good choice but it will need to have an independent power supply if there isn't one on the driver board.

I bought a Pi a while back, and found it so tedious to use I put it in my parts drawer and haven't used it since. A Pi is like a small Unix PC - you have to install an operating system, boot it up (which takes time) and then install device drivers etc.
The Arduino (particularly the Uno) boots in under a second, and "just works". It is much easier to use for small to medium projects.
As for the current, as others have replied, you aren't supposed to be powering things, like motors, from the output pins. 20 mA is a nice amount of current to flash an LED, or send data to another device. The output pins are for data not for driving things like motors. If you need more than 20 mA you should be looking at driver circuits, like transistors or MOSFETs.

... hard programming ...

I wouldn't say that. You program in C++. What are you going to program the Pi in? There are many libraries for the Arduino to simplify programming, but you can get down to the "bare metal" quite simply.

I actually did program Raspberry Pi for a research project and I used Python.  I know both Python and C++ and the former is far more user friendly.  Which is a bonus if you want your kids not only to learn electronics but programming too.
Otherwise, yes, I like the fact that Arduino "just works", but it also has extremely small memory, far too small for a serious project.

@Pygmalion Python is beginner friendly. C++ is programmer friendly. Choose which you want to be in the long term.

it also has extremely small memory, far too small for a serious project - it depends on your definition of "serious". I have one right now controlling access to my house. It's been there for a few years now, and works perfectly. It's a microcontroller, not a supercomputer. For projects - ones suitable for a microcontroller - it does a great job.

I did a lot of programming for controlling relatively small science projects and I usually end with a source code of cca 20 kB.  I know that C++ source code is compiled, but this by the rule of thumb only increases the required space.

The AVR compiler is quite good at generating compact code. Especially if you choose sensible data types, like 1-byte or 2-byte types. Once you start using long and float code necessarily bloats somewhat.


text:
Maximum potentiometer resistance
I want to hook up a potentiometer to my arduino (Leonardo) as a voltage divider with the middle pin to an analog pin. I want to use the highest resistance to save power. I looked on the datasheet and it said the maximum output impedance is 10kOhm (§24.7.1 on Atmega32u4 datasheet). I also found another question that said I should use a 10kOhm potentiometer. What doesn't make sense is if the knob was turned towards the middle so that there is 5k on both sides, it's not the maximum capable resistance. So should I use a 20kOhm potentiometer?

Aren't you more interested in input impedance?

Oh yeah. But the datasheet said output impedance... I'm confused. I'm ensentially asking what is the maximum potentiometer resistance for analog input without the chip stuffing up.

The voltage divider is Thévenin equivalent to a voltage source having no more than 1/4 the resistance of the pot. You could then use a 40 kΩ pot and still be within spec.

If you are sequentially reading various analog inputs and your resistance is too high, you might get some cross-talk. If this is the only analog input you are reading, there should be no issue. If you really care about sub-mA consumption, you should probably use a barebones ATmega instead of your Leonardo.

I'm actually using two pots for two analog input pins. I also kinda get with your meaning of cross talk as I heard the analog pins are multiplexed into one capacitor. Also I am planning to use barebones Atmega but I'm using a Leonardo as my prototype. I want to know how changing the pot resistance affects the chip.

Take a look at the block diagram in the datasheet. The nature of multiplexing is you make a choice. You choose input 0 or input 1. They aren't somehow combined into a single input at the same time.

There is a lengthy discussion about this on the Arduino Forum. As I understand it, the input impedance is only important if you are sampling a rapidly varying signal, as it takes a finite time to charge the sample/hold capacitor. However your potentiometer would not vary rapidly (certainly not in the order of thousands of herz). Thus I don't think the potentiometer resistance will be particularly important, particularly if you are not changing the analog inputs (eg. from one channel to another). The continuous current through the 10k pot would be 0.5 mA.
If you are worried about power, then rather than connecting the +5V side directly to 5V, connect it to an output pin, which you can bring high when you want to take a measurement, and make low at other times. That reduces the power through the pot, since there won't be a voltage potential. You might allow a few microseconds for the reading to stabilize when you need to take one.

So the lower the pot resistance, the faster response time? Also I will constantly always be taking a measurement

No, I don't think this is an issue. The "response time" is really the time taken to do the ADC calculation (nominally 104 µs if you don't fiddle with the registers).
See ADC conversion on the Arduino (analogRead). As mentioned on that page you can speed up the measurement by changing the ADC prescaler. However even with a prescaler of 128 you get 9615 conversions per second. I doubt you can turn the pot fast enough for this to be a meaningful issue.
Regardless of the response time, the issue here is accuracy. Will a lower pot value give more accurate results? Well, I doubt it. The ADC effectively copies the analog input into a 14 pF capacitor (the "sample and hold" capacitor) which it then tests against the reference voltage divided up in various ways.
The input impedance would be relevant if you were sampling a high-frequency input. On the page I linked I sampled a 4 kHz sine wave and got good results. You just won't be turning the pot that fast (4000 times a second).

I'm still unsure with how potentiometer resistance affects the data ...

If you keep sampling the same ADC input (eg. A0) then I think the sample and hold capacitor can be charging in the background (while your code is doing other things).
But even if that were not the case, the datasheet says the sample and hold operation takes place 1.5 ADC cycles after the conversion starts. So at 16 MHz clock rate, and a prescaler of 128 for the ADC clock, this means we have:
128 * 62.5 ns * 1.5 = 12 µs

Now since the datasheet says the sample-and-hold capacitor is 14 pF, and the time taken to (almost fully) charge a capacitor is reckoned to be:
5 * R * C

Given R = 110k and C = 14e-12 (14 pF) then it will take:
5 * 110000 * 14e-12 = 7.7 µs

I quoted 110k because the datasheet mentions a resistance of 1 to 100k in series with the capacitor, plus the 10k impedance they recommend.
This means the capacitor will charge within the 12 µs it has available. Bump R up to 1e6 (1 megohm) and the calculation now gives:
5 * (100e3 + 1e6) * 14e-12 = 77 µs

This exceeds the 12 µs quoted for the sample-and-hold.
This is why, I suggest, that for fast-changing signals they recommend a lower input impedance.
However if I am correct that the sample-and-hold capacitor is normally connected to the ADC input, then that 77 µs can be spread over the time you deal with the calculation. Still, that is quite a few clock cycles. :)

My recommendation is to stick with 10k or so potentiometer (as recommended by the datasheet) and use my earlier suggestion of connecting the 5V side of the pot to an output pin instead of continually having it connected to the +5V signal. That way you only need to "power" the pot when you actually need to take a reading. However you can see that a 20k pot (or even 50k) will probably still be in an acceptable range for an accurate conversion.
For example, a 50k pot could charge the capacitor in:
5 * 150000 * 14e-12 = 10.5 µs

I would also be cautious about a 1 megohm pot because then slight variances in other things (eg. heat on the wire, nearby noise) could swamp the reading from it.

Wait, sorry do I need to half my potentiometers' resistance if I'm using two analog inputs?

No, because the multiplexer chooses one input at a time (the others are effectively out of circuit).
However if you are choosing between two pots (to measure two) then the resistance becomes more relevant. As I showed, with a high value pot it takes longer to charge the capacitor, so if you read A0 and then immediately afterwards A1, you don't want a lengthy charging time for the capacitor, because that would give erroneous readings.

So the lower the pot resistance, the faster response time? Also I will constantly always be taking a measurement

See amended reply.

So in conclusion, resistance doesn't matter, and I could use a potentiometer in the mega ohms? And this is because I'm twisting a potentiometer, right?

I can't tick your answer because I'm still unsure with how potentiometer resistance affects the data even though you said it doesn't matter that much.

See more details in reply about timings.

Ah math formulas now I get it thanks! Wait, sorry do I need to half my potentiometers' resistance if I'm using two analog inputs? Cuz don't all analog inputs have to share one capacitor?

You have two pots? The multiplexer (see the datasheet) chooses one port or the other. You don't have to second-guess that part. - See further amendments to the answer.

Sorry halving is not correct. Im using both ports at the same time so would it take double the time to sample both?

These chips only have one ADC. It is impossible to sample them both at the same time. You have to do one after the other. For example: foo = analogRead (0); bar = analogRead (1); - that's two reads. That takes twice as long as one read.

A 50 K pot has a maximum Thévenin resistance of 12.5 kΩ.

Wait, you mean 40k pot is actually the 10k impedance recommendation?

Sounds like it. :)


text:
Keyboard input arduino speed
I have an Arduino clone of a Leonardo and I was just wondering how many keyboard commands I can send to the computer per second via USB. I'm not talking about the delay between send and receive (because that could vary between computer), I'm talking about the minimum possible time between something like stimulating a key press down and key press up as fast as possible.

From my tests, it has been at least 1 millisecond, however, it can depend on what is running simultaneously on the Arduino.

Well what if you were doing key up and key down of a single character, with that only being in the void loop?


text:
Pin 9 and 10 with different duty cycles
I want to control the contrast and backlight of an HD44780 LCD display with two PWM signals. I would like to use PB1 and PB2 (Pin 9 and Pin 10) for this.
As far as my research goes, timer1 is responsible for the two pins.
OCR1A and OCR1B are responsible for the pulse length.
With the code below I get a frequency of 7.823 kHz and a duty cycle of 88%. But it works only on PB1. PB2 is still constant 0V. I am using the AtmelStudio, therefore I don't have access to functions like pinMode(10, Output)
How can I have different duty cycles on pin 9 and 10?
#define F_CPU 16000000UL
#include <avr/io.h>

int main(void)
{
    DDRB |= (1 << DDB1) | (1 << DDB2);
    OCR1A = 900;
    OCR1B = 400;
    TCCR1A |= (1 << COM1A1);
    TCCR1A |= (1 << WGM11) | (1 << WGM10);
    TCCR1B = (TCCR1B & 0b11111000) | (1 << CS10);

}

You can't control the contrast with PWM unless you filter it properly to provide the correct voltage. Personally I use a digipot for contrast.

I want to use PB1 for backlight and PB2 for contrast. analogWrite() is not inside AtmelStudio.

Maybe you should use the Arduino IDE with your Arduino. Or copy and paste the Arduino source code into your project.

As far as I have been able to test it. It will work. I might add a circuit to filter it but that's down the line.

Without a filter you will get flicker as it switches rapidly between full contrast and zero contrast.

Thanks for the info. I will add one once I get the source code working.

Start by examining the Arduino source code. That works, so why not use it as a basis?

After trying  a lot of things i got it working.
And even the contrast is working directly on the pwm signal.
#define F_CPU 16000000UL
#include <avr/io.h>
void main(void){
    DDRB = 0x06;
    OCR1A = 200; //Duty cycle for PB1 ~80%
    OCR1B = 100; //Duty cycle for PB2 ~40%
    TCCR1A = 0; //Set TCCR1A to zero. We will configure it manually
    TCCR1A |= (1 << COM1A1) | (0 << COM1A0) | ( 0 << COM1B0) | (1 << COM1B1);
    TCCR1A |= (0 << WGM12) | (0 << WGM11) | (1 << WGM10);
    TCCR1B = 0; //Set TCCR1B to zero. We will configure it manually
    TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
    while(1){

    }
}