text:
HTTP GET request only works sometimes
I am sending a HTTP GET request to a server I deployed on digital ocean (Ubuntu/Node.js). On the web browser when I go to my URL 'http://Server_Ip_Address/event/astarttime' or 'http://Server_Ip_Address/event/aendtime' the application on the web successfully performs its transaction.
However, I tried doing the same on my D1 R2 ESP8266 with this code in Arduino IDE: Sometimes it works sometimes it doesn't...I can't figure out why it only works some times and other times it doesn't work at all. Any idea of what it could be? Thank you for your help in advance.
Using these libraries:
#include "ESP8266WiFi.h"
#include <ESP8266HTTPClient.h>

http.begin("http://Server_Ip_Address:80/event/astarttime");
int httpCode = http.GET(); //Send the request
http.end();  //Close connection
http.begin("http://Server_Ip_Address:80/event/aendtime");
int httpCode = http.GET(); //Send the request
http.end(); //Close connection

arduino core version? 2.4.1? which lwip? 2? try 1.4. and erase the flash with esptool

Does the web server see the requests in the failing case?

Using arduino 1.6.13 it acctually works sometimes but not all of the time — Mark Smith how would I see the log file of the web server & it’s failing requests?

Perhaps I should, somehow, have a confirmation response from server to arduino to confirm that the http get request was successful (& if it wasn’t then it would keep trying? Does that sound like something that could be possible to implement?)

I've no idea how to see the logs but I'll eat my hat if Google doesn't tell you. Generally you should handle failures cleanly and sensibly, but I would investigate and fix the cause rather than bodging it and pushing the problem elsewhere.

@JoeB, esp8266 arduino core packages version? https://github.com/esp8266/Arduino/releases


text:
Use SD Card while Pin 11 is being used for PWM
On Arduino Uno Rev3, I just ran the speaker_pcm demo that used TIMER1 and TIMER2 to generate a PWM wave. However, this means that the Pins 3, 9, 10 and 11 can not be used anymore; according to the documentation:
Takes over Timer 1 (16-bit) for the 8000 Hz timer. This breaks PWM
(analogWrite()) for Arduino pins 9 and 10. Takes Timer 2 (8-bit)
for the pulse width modulation, breaking PWM for pins 11 & 3.

I wanted to change the program such that the WAV data was read from a SD card. However, this is what documentation for SD.h library says:
The communication between the microcontroller and the SD card uses SPI,
which takes place on digital pins 11, 12, and 13 (on most Arduino boards)

This means both the SD.h and speaker_pcm want to use pin 11, and the requirement to use these pins is dictated by the hardware. I am guessing that this clash will create problems.
Is there any way I can make this work? Can I switch between SD card reading and Audio playing somehow (essentially multiplexing in software)? Or will this collision of pin usage not be a problem?

The program you link to does not take over pins 3, 9, 10 and 11, it
takes over Timer 1 and Timer 2, which are used to provide PWM capability
on those pins. This means you cannot do analogWrite() on those pins
anymore, but you still can use them for other purposes, including SPI
access to an SD card.
Note, however, this line of code:
int speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2

This of course will conflict the SPI port using pin 11 as MOSI. You can
fix this conflict simply by setting speakerPin to 3 instead of 11.

source: Stack Exchange

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

sort: votes


text:
Variables not saving
I'm trying to write web server code. However, I am having trouble with part of it.
Currently, to get it to save a bool variable I have it use a pin, as when I ran the code without it, after the page refreshes it resets the variable to its original value.
How do I get it to save the variable in this code without it using the pin?
digitalWrite (equalPin, server.arg("equal").toInt());
char equalText[80];
if(equalState) {
  strcpy(equalText, "priority is equal. Deactivate");
  equalState = false;
} else {
  strcpy(equalText, "priority is not equal. Activate");
  equalState = true;
}
equalState = digitalRead(equalPin);

I also have several over copies of this for different pages but if I change 1 of them they all change and reset after 10 seconds.
The code follows the example on this site.

so you want to set it or leave it as is? in if and else you change it and then you revert to the value before if and else. perhaps learn coding first.

I want it to set it then potentially change again in the future. I remeber doing it in the past but ive completely forgotten how. How do I stop it from reverting?

I can't understand what you're asking. Perhaps someone else can, but perhaps writing the question more clearly would help you get more responses. Consider a minimal, complete, verifiable example (Google to find what that is).

What are your trying to achieve? The code you linked to presumably works fine. Please, state clearly the purpose of your modifications.

same code snippet without using pin
char equalText[80];

if (equalState){
  strcpy(equalText, "priority is equal. Deactivate");
  equalState = false;
}
else {
  strcpy(equalText, "priority is not equal. Activate");
  equalState = true;
}
equalState = server.arg("equal").toInt();

but it does not make much sense to set the value if you already switched the state based on it's previous value

That seems to have worked it just doesnt auto refresh the page anymore but thats fine.

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


text:
SIM800L Mini and Arduino Uno
I know there are a lot of threads about this, but i cant find answer for my problem.
I have SIM800L Mini and arduino uno. I want to create basic SMS send application, but problem is with SIM800L. I can connect it with USB-UART and communicate with it via AT terminal. I can set baud rate, send sms etc. But when I connect it with arduino, it doesnt work. Im using LM350 for powering it (4V) and voltage divider with 4k7 and 10k resistor.
Thank you for your help
EDIT:
Here is code:
#include <SoftwareSerial.h>

String Arsp, Grsp;
SoftwareSerial gsm(10, 11); // RX, TX

void setup() {
   // put your setup code here, to run once:

   Serial.begin(9600);
   Serial.println("Testing GSM SIM800L");
   gsm.begin(9600);

}

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

   if(gsm.available())
   {
      Grsp = gsm.readString();
      Serial.println(Grsp);
   }

   if(Serial.available())
   {
      Arsp = Serial.readString();
      gsm.println(Arsp);
   }
}

Here is wiring

Codes for arduino
Schematics
SIM800L

Are you have connected ground between arduino and SIM800L?

thank you for your reply, yes I used one of GND on arduino and connect to the common ground (sim800l, dc-dc, arduino, voltage divider)

Could you please post your wiring and code what you used? Maybe you have wrong wiring.

i edited it, so you can check if its something wrong :)

You're not connected reset pin to arduino. You can try to connect it.
Pin 2 Arduino > Transistor > Reset pin SIM800

and it needs to be? because i read that reset pin dont need to connect

so how can i modify code? to use reset pin?

Ok sorry for missunderstanding. I think you must check that your cable is work perfectly.I doubt if rx pin arduino is not connected properly to tx gsm module. And are you have connected VCC gsm module into GND using resistor?

no those resistors are from lm350 dc-dc buck, im using 10V/3A and converting it to 4V for VCC sim800l

and cables are good, i tested them

Then i'm sorry i have no more clue. I have tested your circuit and mine is working. My only suggestion you rewiring it. Good luck buddy.

Let us continue this discussion in chat.


text:
Save Leading Zero HEX into String RFID RC522 Arduino
I'm using RC522 to read RFID card. All is until if the HEX leading by 0 then i can't save it into String. But if i print it to Serial all is well. Here is my code:
#include <SPI.h>
#include <MFRC522.h>
#include <stdlib.h>

#define RST_PIN         9
#define SS_PIN          10

String inStringHex = "";

MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  // Look for new cards
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial())
  {
    //Serial.print("Card UID:");
    for (byte i = 0; i < 4; i++) {
      Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
      Serial.print(mfrc522.uid.uidByte[i], HEX);
      inStringHex += String(mfrc522.uid.uidByte[i], HEX);
    }

    Serial.println();
    Serial.println(F("Hex normal"));
    Serial.print(inStringHex);
    Serial.println();
    Serial.println();

    inStringHex = "";
    delay(5000);
  }
}

Here is what displayed in serial monitor:

What i want is the String under "Hex normal" would be "04292e5a" not "4292e5a"
Please anyone help me.
Thank You.

String(mfrc522.uid.uidByte[i], HEX) means you want to convert number into hexadecimal string repesentation, if you pass 4 as input parameter, it will convert it into "4", not "04". You need to apply similar approach as you have used when printing the value through UART. For example:
if (String(mfrc522.uid.uidByte[i] < 0x10)
  inStringHex += " ";
inStringHex += String(mfrc522.uid.uidByte[i], HEX);

Personally, I would recommend switching from Strings into static buffers (because arduino has too small memory to use dynamic allocation and there could be issue with running out of memory due to memory fragmentation):
char id[16];
sprintf(id, "%02x%02x%02x%02x", mfrc522.uid.uidByte[0], mfrc522.uid.uidByte[1], mfrc522.uid.uidByte[2], mfrc522.uid.uidByte[3]);

Hi, i need to save into string because i will it convert it again to decimal. If i use your recommendation, can i still convert it to decimal?

Yes of course, you will get the same string and for conversion you can use strtol with radix 16. But if you only want to convert four bytes into one long int, there is much simpler way

I will try your suggestion. Thank you sir.

unsigned long result = 0; result |= (long)mfrc522.uid.uidByte[0] << 24;  result |= (long)mfrc522.uid.uidByte[1] << 16; result |= (long)mfrc522.uid.uidByte[2] << 8; result |= (long)mfrc522.uid.uidByte[3];

Is d[0] taken from char id[16]?

I edited the code to match your situation

Thank you sir. your recommendation worked as what i want.

you can try ;
for (byte i=0; i < uidLength; i++)
{
  Serial.print(uid[i] < 0x10 ? " 0" : "");
  Serial.print(uid[i], HEX);
  if (uid[i] < 0x10) inStringHex += "0";
      inStringHex += String(uid[i], HEX);
} Serial.println(); Serial.println(inStringHex);

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


text:
3.3v Arduino I2C communication with motor controller powered at ~6v
I am trying to just use the voltage from 4 Alkaline AA batteries in series (6v nominal) to power a motor with the TI drv8830 IC.
My question is, will this circuit (specifically just pulling the sda and scl pins to 3.3v) work reliably?   The datasheet says at maximum of 6.8v vcc the chip will still recognize 3.3v i2c lines (minimum 3.13V at that vcc voltage) but will the varying voltage of the battery cause the communication to be unstable?   There is a 10uf capacitor between vbat and gnd (not shown).

will the varying voltage of the battery cause the communication to be unstable?

No. As the battery voltage drops the input HIGH threshold (which is a function of VCC) also drops. If anything as the battery voltage drops the communication becomes more stable.
Since I2C is an open drain protocol the voltage makes no different for sending data - that voltage is set by the pull-up resistors to 3.3V.


text:
Arduino + Solenoid Lock
I was trying to use a solenoid lock alongside the arduino, using a 12V 2A DC adapter, TIP120, and a diode.
The circuit looks something like this. However, the lock isn't going in automatically (it requires a push).
I've tested the circuit using a multimeter, and the output given by the transistor, is indeed 12V, however, when connected to the lock, the potential difference is around 8V. I don't know if that's normal, but the lock isn't going in on it's own.
Can anyone help me with this issue?

Welcome to Arduino:SE. You might find this helpful: How to ask a good question for Arduino Stack Exchange

lock isn't going in ... what does this mean? .... lock or unlock?

@jsotola by this I mean that it is not unlocking. When I provide it direct 12V dc, it is going unlocking perfectly.

It sounds like your 12 volt adaptor is not powerful enough to operate the lock solenoid. If you power up the solenoid only and directly using the adaptor it should work. If it doesn't, you'll need a more powerful adaptor. If it does work, then the problem is somewhere in your driver circuit or Arduino sketch.

Well, the lock works (goes in) when I power it directly. I don't know what am I doing wrong. :/

The next step is to connect the lock to the TIP120 driver circuit. Apply 12V to the base of the transistor through a 1k ohm resistor. The solenoid should work.

Well...I still have to push the lock in that configuration.. :/ Don't tell me the lock is faulty...

I think the power adaptor and lock are OK. The TIP120 driver circuit is not allowing enough current to flow through the solenoid. The next step would be to verify the driver circuit has been built correctly. Are any of the components getting hot? With everything connected, try using a jumper wire between the TIP120 emitter and collector. The solenoid should activate.

Well, no part was getting heated, however, a jumper wire between the collector and the emitter worked. Any leads?

For some reason, the TIP120 circuit is not able to operate the lock solenoid, so your question is more of a "general electronics" question, not an Arduino question. For the price of $1 CDN, you can get a relay that will definitely do the job: https://www.aliexpress.com/item/One-1-Channel-Isolated-5V-Relay-Module-Coupling-For-Arduino-PIC-AVR-DSP-ARM/32669140447.html. There is a chance that your power adaptor is "just powerful enough" to engage the relay, yet when combined with the transistor's voltage drop it is not. You could check this with a power adaptor that can deliver more current.

Yes use a well protected relay, check the voltage ratings so you don't fry your Arduino.


text:
Can I connect more than one IR receiver to an Arduino Uno?
I want to use #include <IRremote.h> to receive information from an infrared remote control. It works perfectly with one IR receiver.
But I want to put three or four IR receivers:
IRrecv irrecv6(pin6);
IRrecv irrecv7(pin7);
IRrecv irrecv8(pin8);
IRrecv irrecv9(pin9);
IRrecv irrecv10(pin10);

And:
void setup() {
  Serial.begin(9600);
  irrecv6.enableIRIn(); // Start the receiver
  irrecv7.enableIRIn(); // Start the receiver
  irrecv8.enableIRIn(); // Start the receiver
  irrecv9.enableIRIn(); // Start the receiver
  irrecv10.enableIRIn(); // Start the receiver
}

Inside the loop function, I am checking each pin to see if there is any data received. But only the last pin (which means pin 10 above) is receiving the data and others are not.

you can connect multiple receivers, but why?

But always only one of them, which is initialized last, is receiving the Data.

@jsotola you could use it to get a very coarse sense of the direction the signal came from.

did you find the solution, because i also want to put 4 ir receiver on Arduino in my fyp. if you have a solution plz help mee.

Try my link
https://github.com/gerivega/Arduino-IRremote I wanted to do the same thing. I modified the latest library to incorporate the changes done by a previous programmer neco777.

That library only supports one IR receiver at a time. Try this fork that seems to have added multiple receivers support.

Just add some delay between irrecv.decode()s and everything will work just fine.


text:
Understanding USBHID_DESC report
Recently Ran the USBHID_DESC program on my Arduino Uno with a USB hub attached to my joystick. I wanted to be able to program my joystick to integrate with my project. Circuits@Home developed the code and have 2 articles dealing with understanding the report. But they are very sparse with details and only have a single example to go off of. Many of the fields that I got returned are not described at all in the tutorial. Further more, attempting to dig through the official documentation from USB.org itself has been extremely overwhelming. I don't really know how to start. Can anyone help me interpret the data fields for this controller?
This is the data that I recieved from the serial monitor:

Start
  0000: 05 01 09 04 A1 01 09 01 A1 00 09 30 09 31 09 32
  0010: 09 BB 15 80 25 7F 46 FF 00 66 00 00 66 00 00 75
  0020: 08 95 04 81 02 C0 09 39 15 01 25 08 35 00 46 3B
  0030: 01 65 14 75 04 95 01 81 02 05 09 19 01 29 04 15
  0040: 00 25 01 75 01 95 04 81 02 95 08 81 01 05 08 09
  0050: 43 15 00 26 FF 00 35 00 46 FF 00 75 08 95 04 91
  0060: 82 55 00 65 00 55 00 65 00 55 00 C0
  Usage Page Gen Desktop Ctrls(01)
  Usage Game Pad
  Collection Application
  Usage Pointer
  Collection Physical
  Usage X
  Usage Y
  Usage Z
  Usage Undef
  Logical Min(80)
  Logical Max(7F)
  Physical Max(FF00)
  Unit(0000)
  Unit(0000)
  Report Size(08)
  Report Count(04)
  Input(00000010)
  End Collection
  Usage Hat Switch
  Logical Min(01)
  Logical Max(08)
  Physical Min(00)
  Physical Max(3B01)
  Unit(14)
  Report Size(04)
  Report Count(01)
  Input(00000010)
  Usage Page Button(09)
  Usage Min(01)
  Usage Max(04)
  Logical Min(00)
  Logical Max(01)
  Report Size(01)
  Report Count(04)
  Input(00000010)
  Report Count(08)
  Input(00000001)
  Usage Page LEDs(08)
  Usage Slow Blk On Time
  Logical Min(00)
  Logical Max(FF00)
  Physical Min(00)
  Physical Max(FF00)
  Report Size(08)
  Report Count(04)
  Output(10000010)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  End Collection Game Pad Pointer X Y Z Undef(00)(00)(7F)(00)
  Hat Switch(00)
  Btn0001
  (00) Btn0002
  (00) Btn0003
  (00) Btn0004
  (00)
  (00)(00)(00)(00)(00)(00)(00)(00)
  Slow Blk On Time

Which bits don't you understand?

well i didn't understand a lot of it. it seems to have come out formatted very strangely, your explanation helped a lot...ty*1.1^100

It's pretty easy to follow if you indent and break it up right.  Let me add some annotation too:
Usage Page Gen Desktop Ctrls(01)  // Usages describe what the
Usage Game Pad                    // following data is used for.
Collection Application
    Usage Pointer        // Use the settings for a physical
    Collection Physical  // pointing device
        Usage X       // It has four axes -
        Usage Y       // X, Y, Z and some other undefined axis.
        Usage Z
        Usage Undef
        Logical Min(80) // Output the values 0x80 to 0x7F, which when
        Logical Max(7F) // interpeted as signed bytes is -128 to 127.
        Physical Max(FF00) // The input has a range 0 to 255
        Unit(0000)
        Unit(0000)
        Report Size(08)  // The report value is 8 bits long,
        Report Count(04) // and there are 4 of them (one per axis)
        Input(00000010)  // This ends this "input" section.
    End Collection

    Usage Hat Switch // Describing a HAT Switch now.
    Logical Min(01)  // Interpret it as a value between 1 and 8
    Logical Max(08)
    Physical Min(00) // The input to it is between 0 and 0x3B01.
    Physical Max(3B01) // Not sure that value is interpreted properly.
    Unit(14)
    Report Size(04)  // The report has 4 bits in it,
    Report Count(01) // and there is just one of them.
    Input(00000010)  // And end the input section.

    Usage Page Button(09)  // Next come the buttons.
    Usage Min(01)      // These are basically button numbers
    Usage Max(04)      // - there's 4 buttons, 1 through 4.
    Logical Min(00)    // A button is either off (0)
    Logical Max(01)    // or on (1).
    Report Size(01)    // And can only have one state, so size 1.
    Report Count(04)   // There's 4 buttons, so 4 reports.
    Input(00000010)    // And end the input.

    Report Count(08)   // This is a special one. It keeps the settings
    Input(00000001)    // from before (the haven't been changed), but
                       // is just a dummy one to pad out the data to
                       // the right size. Alignment is key.

    Usage Page LEDs(08)    // Now we have 4 LEDs with an
    Usage Slow Blk On Time // 8-bit PWM value. 0-FF which doesn't
    Logical Min(00)        // need interpreting, so 0=0 and FF=FF.
    Logical Max(FF00)
    Physical Min(00)
    Physical Max(FF00)
    Report Size(08)    // As I said, 8 bit,
    Report Count(04)   // and there's 4 of them.
    Output(10000010)   // And it's output.

    Unit Exp(00)   // Now there seems to be a bit of junk.
    Unit(00)
    Unit Exp(00)
    Unit(00)
    Unit Exp(00)
End Collection Game Pad // And the end.

So interpreting that, you get a report sent to you that has:
Byte     Function
0        X Axis 0-255 which you map to -128 to 127
1        Y Axis 0-255 which you map to -128 to 127
2        Z Axis 0-255 which you map to -128 to 127
3        Another Axis 0-255 which you map to -128 to 127
4        Upper 4 bits buttons, lower 4 bits HAT direction
5        Padding byte to make ita multiple of 16 bits long

And you can send a 4 byte report where:
Byte     Function
0        LED 1 PWM
1        LED 2 PWM
2        LED 3 PWM
4        LED 4 PWM

Those "LEDs" could be force feedback motors or vibrators.
Also I suspect there is maybe a small amount of corruption or mis-interpretation of multi-byte values in the output.


text:
How to use a DC buck converter to regulate Uno R3 input voltage?
I have had a rough time trying to understand why this isn't working correctly. Quick background: I set up a system to pop open car doors using touch sensors. I heard that powering the Arduino Uno R3 straight off the car battery is not a good idea, so I bought a buck converter. I wired it up and calibrated the output on the converter for 5V. When I hooked it up to the Arduino (via the barrel jack), I experienced some odd effects. The output pins and the 5v power pins were only getting 3.5V.  I had to adjust the buck converter up to about over 7V in order to get 5v on the Uno.
Then the sensors started acting oddly. Auto triggering and alternately not working. Anyone know what I am doing wrong?
Converter I bought:  https://www.amazon.com/gp/product/B0159W0UL2/ref=oh_aui_detailpage_o07_s00?ie=UTF8&psc=1

Connect the output of the buck converter directly to the 5V (and GND) pin, thereby bypassing the voltage regulator. Or do as Michel said. I'd suggest the latter, if you are running from a car, as the battery voltage in a running car can have a lot of spikes.

The barrel jack needs 9-12 V, the internal voltage regulator of the Arduino will reduce this to 5 V.
Since you only supply 5 V, there is a loss in the internal voltage regulator why you probably get only 3.5 V.
And after applying 7 V, probably some (sub) system gets less than the necessary voltage, or there are occasional 'downspikes' lower than 5 V.
The default adapter that you use for supplying voltage to the Uno, also is 9V-12V. Also, check the polarity.
See the following link for more info:
What adapter

I did not know about the 9V.  I just assumed that since the board ran on 5v, it would need 5v in.  Makes sense now, but I still don't know what the converter should output to maintain the Uno's optimal 5V bus, while maintaining minimal drain on the car battery (efficiency).  Is there an efficient ideal voltage to output?

The Arduino can handle anything between 9 and 12V. Normally it is used if you have another device using 9 or 12V and you can use the same power source for both the other device and the Arduino. If you use 12V, there will be more heat generated in the Arduino, if you use 9V, there will be more heat generated in the buck converter.

If you are getting a clean 5v from the buck converter, you can/should run that directly to the 5v pin on the Arduino. Using the barrel jack(at 7-12V) still uses the on board linear(inefficient) Regulator to produce the 5v the board needs. You will want to ensure you are outputing a clean 5v during all phases of the car being on/off/startup.


text:
Making a distance sensor for human interaction
I want to make a sensor that senses a person between 1.5 m and 0.2 m, connected to an LED that is on 100% at 0.2 m and 1% at 1.5 m and gradually scales.
Is an ultrasonic sensor the best sensor to use here?

Welcome to Arduino:SE. You might find this helpful: How to ask a good question for Arduino Stack Exchange

The 'best' sensor might be a $100K Computer vision system with 400 cameras.

are you talking about a swimmer underwater? ... you did not actually say anything about the usage of the system.

Most arduino compatible ultrasonic sensors should work perfectly for your use case. You would just have to program the arduino then but I am going to assume that you know how to do that.
Here is a link to the one that I personally use: https://www.amazon.com/HC-SR04-Ultrasonic-Distance-MEGA2560-ElecRight/dp/B01MA4O5G5/ref=sr_1_3?ie=UTF8&qid=1524520770&sr=8-3&keywords=ultrasonic+sensor


text:
What's the newest way to use C++ stdlibs in Arduino 1.8.2?
(My Arduino version is 1.8.2.)
For example,if I want to #include <vector> or <string>, <iostream>, <memory> etc, the compiler always complains that such libs are not found.
So what's the newest/most efficient way to use C++ libs in Arduino 1.8.2?

It would be nice but with the available memory resources (Arduino Uno, 2KB SRAM) makes it difficult to implement and use this. The 2KB has to hold all data, stack and heap; https://www.nongnu.org/avr-libc/user-manual/malloc.html

Most Arduino Core don't include the Standard C++ Library, that's why headers like <vector> and <string> are missing.
This decision makes a lot of sense because the STL relies heavily on heap allocation, which would ruin the little RAM of the microcontroller.
If you're looking for an alternative to the STL, you might check out the ETL, the Embedded Template Library.. However, the code will not be the same because all the containers of the ETL have a fixed capacity. Here is a string for example:
etl::string<32> s = "hello world";

In practice, I never saw a project using the ETL. Most projects use the standard Arduino classes (String, Stream, Print...) and learn to live with their flaws. Since there are no generic container classes in the Arduino core, the common usage is to use plain old C arrays.


text:
Teensy 2.0 with MCP23017-E
I've recently bought two more MCP23017-E's for a project, but after hooking them up to my Teensy 2.0 I couldn't get them to react to anything. Suspecting faulty hardware, I hooked them up to an old LCP1114, and got them running just fine. I've tried porting the code I used, which still gave no result.
I'm using the following code:
#include "Wire.h"
const byte device=0b01000000; //default addrress of IO chip

const byte IODIRA=0x00;
const byte IODIRB=0x01;

const byte GPIOA=0x12; //IO pins, port A
const byte GPIOB=0x13; //IO pins, port B
const byte OLATA=0x14;//O pins A
const byte OLATB=0x15;//O pins B

const byte GPPUA=0x0C; //pull up resistors ,port A
const byte GPPUB=0x0D; //pull up resistors ,port B

char iCounter = 0;

void setup() {
  Wire.begin();
  seti2cbyte(device,IODIRA,0x00);
  seti2cbyte(device,IODIRB,0xFF);
  seti2cbyte(device,GPPUB,0xFF);  //enable pull-up resistors on port B
}

byte geti2cbyte(byte address, byte ptr) {
  Wire.beginTransmission(address);
  Wire.write(ptr);
  Wire.endTransmission();
  Wire.requestFrom(address, 1); // request one byte of data from MCP20317
  byte inputs=Wire.read();
  return inputs;
}

void seti2cbyte(byte address, byte ptr, byte value) {
  Wire.beginTransmission(address);
  Wire.write(ptr); // set MCP23017 memory pointer to GPPUA address
  Wire.write(value); // enable pull up resistors
  Wire.endTransmission();
}

void loop() {
  seti2cbyte(device,OLATA,iCounter);
  byte port_b = geti2cbyte(device,GPIOB); //get status of pins 21-28
  Serial.print(iCounter++);Serial.println(port_b);
  delay(500);
}

I don't see a blinking LED, and port_b stays at 255 (or -1 I figured after reading the Wire.cpp)
I've tried different methods, even running SPI myself (setting pins high and low manually). The only difference I see is that the Teensy 2.0 is 5V, and the LCP1114 runs at 3.3V. The data sheet for the MCP23017-E states that it is also rated for 5V though.
Why does it seem like my MCP23017-E's won't work at 5V, while the data sheet states they should?
MCP23017-E datasheet

• Operating Voltage:
  - 1.8V to 5.5V @ -40°C to +85°C
  - 2.7V to 5.5V @ -40°C to +85°C
  - 4.5V to 5.5V @ -40°C to +125°C

Those solder connections look really bad in the last picture. On D1 you can see that half of the hole isn't even filled with solder. You should first try to resolder all pins and check continuity between GND,VCC,D0 and D1 to your chips.

@Maximilian Gerhardt I've checked the connections, they're fully functional. They're indeed not filled, since it's temporary, but there is no measurable resistance over the connections.

No I2C pullup resistors? Also did you run an I2C scanner sketch?

The I2C scanner will help determine if the device is connected correctly and verify the address. The address in the code seems to be a "bit" off.

You have the wrong device address. You've included the R/W bit in the address, which you shouldn't.  An I2C address is only 7 bits, not 8.  Drop one bit:
const byte device=0b0100000; //default addrress of IO chip

HA!!! Thank you! I'm used to it just getting OR'd by libraries.


text:
Fio Keyboard program out of control, how to reset?
My question involves a Sparkfun Fio v3, similar to the Arduino Fio.
I had a student who was testing his understanding of the Keyboard library.  He uploaded a sketch that continuously sends output, emulating a keyboard, saying "Hello!If you're reading this, then you did things right!" (I don't have his code, unfortunately, so I can't post it.)
So, now, whenever I connect it via the USB, I can't upload a new sketch because the Serial channel is clogged with this output.  (Error Message: "avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00" and so on)
I've tried putting the cursor inside the header comment in 'Blink', so that the new characters that are being spammed to my code are all inside a comment, and this makes it possible to compile, but it won't sync and upload.  I've tried burning a new bootloader, and this fails as well (Message: "Error while burning bootloader.").
It seems to me that the only way to get this device back is to reset the memory without connecting to a computer, but I can't find any way to do this.
Is there any way to rescue this device?

Hehe... This is a fun one to try and get out of. The normal way is to reflash the bootloader...
If it's the same as the Leonardo you get about 8 seconds after a reset while just the bootloader runs before it starts to spam everything with text. So you can try:

Open notepad or something similar
Plug in the board
Press and hold the RESET button (or connect the RESET pin to GND with wire)
Open the IDE and load Blink.ino

Now the tricky bit.  If the correct serial port isn't selected, you need to, within the space of 8 seconds:

Release the reset button.
Let the PC enumerate the device
Open the serial ports menu and select the right port
Press and hold the RESET button again.

Now you can program it, in a similar way:

Press UPLOAD in the IDE.
Just before it finishes compiling (turn on verbose output can help you time it better) release the RESET button.

If you timed it right the bootloader should run and accept the new program before the existing sketch runs and starts spamming everything.

I tried this many times, and couldn't get anything to work. Thanks, though.

Majenko's suggestion should work - the bootloader should give you a few seconds in which to upload the new sketch, although timing it can be critical.
If that fails, you can reburn the bootloader which will erase the existing sketch. I have a sketch which uploads various bootloaders, the ATmega32U4 being one of them.
Judging by the schematic and also a photo of the board, you would need to solder on a 6-pin header (circled).

Then run 6 wires as described on my page above to another Arduino (see "Wiring for Leonardo") and burn the bootloader. That only takes a couple of seconds. You could make up a suitable cable with a 6-pin socket to make it easier next time a student does the same thing. :)
This will definitely work (if you get the wiring right) because it uses ICSP programming, which means the sketch on the board doesn't have a chance to run. In fact the programming is not via the USB interface at all.
The bootloader uploading starts with a chip erase, which therefore removes any existing sketches.

Thank you twice!  I discovered that I had already downloaded your sketch before, I think this helped me rescue a Mega some time ago.

Your sketch successfully identified the SF Fio V3 as an ATmega32U4, and transferred the bootloader.  It took a little fiddling because SF didn't put a dot to tell me which end is up on the ICSP header, and it is upside-down compared to the Uno I was using to send it.  However, now my Mac won't recognize the Fio at all when I connect it to the USB.  When I look in /dev/, I see a new device, so linux is picking it up, but the Mac isn't recognizing it as anything interesting.  I'll do a little more playing.  I realized that this computer is new so I might just not have all the drivers installed.

A Leonardo driver should do it.


text:
Want criticism on my code
The code is controlling 3 blinds. There are 2 buttons for each blind for going each way and 2 buttons controlling all of them at the same time. The motorSerial is a way to control all of the blinds through the serial monitor where sending 1 goes one way and 2 the other way.
What I'm most concerned about is when pressing a button, it turns on the motor, waits for 0.2 seconds and turns the off. But if I'm holding the button down it will continuously keep turning it on and off. Does anyone have a better way of doing this?
const int PWMA = 13;
const int AI2_left = 12;
const int AI1_left = 11;
const int PWMB = 18;
const int BI1_middle = 10;
const int BI2_middle = 9;

const int PWMA2 = 8;
const int AI2_right = 7;
const int AI1_right = 6;

const int greenLeft1 = 5;
const int greenLeft2 = 4;
const int redMiddle1 = 3;
const int redMiddle2 = 2;
const int yellowRight1 = 14;
const int yellowRight2 = 15;
const int blueAll1 = 16;
const int blueAll2 = 17;

int motorSpeed_left = 0;
int motorSpeed_middle = 0;
int motorSpeed_right = 0;
int motorSpeed_all = 0;
int motorSerial = 0;

void setup() {
  pinMode(PWMA, OUTPUT);
  pinMode(AI2_left, OUTPUT);
  pinMode(AI1_left, OUTPUT);
  pinMode(BI1_middle, OUTPUT);
  pinMode(BI2_middle, OUTPUT);
  pinMode(PWMA2, OUTPUT);
  pinMode(AI2_right, OUTPUT);
  pinMode(AI1_right, OUTPUT);

  pinMode(greenLeft1, INPUT_PULLUP);
  pinMode(greenLeft2, INPUT_PULLUP);
  pinMode(redMiddle1, INPUT_PULLUP);
  pinMode(redMiddle2, INPUT_PULLUP);
  pinMode(yellowRight1, INPUT_PULLUP);
  pinMode(yellowRight2, INPUT_PULLUP);
  pinMode(blueAll1, INPUT_PULLUP);
  pinMode(blueAll2, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {

  if(Serial.available() > 0) {
    motorSerial = Serial.parseInt();
  }

  if(digitalRead(greenLeft1) == LOW) {
    motorSpeed_left = 200;
    spinMotor_left(motorSpeed_left);
    delay(200);
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
  }
  else if(digitalRead(greenLeft2) == LOW) {
    motorSpeed_left = -200;
    spinMotor_left(motorSpeed_left);
    delay(200);
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
  }
  else if(digitalRead(redMiddle1) == LOW) {
    motorSpeed_middle = 200;
    spinMotor_middle(motorSpeed_middle);
    delay(200);
    motorSpeed_middle = 0;
    spinMotor_middle(motorSpeed_middle);
  }
  else if(digitalRead(redMiddle2) == LOW) {
    motorSpeed_middle = -200;
    spinMotor_middle(motorSpeed_middle);
    delay(200);
    motorSpeed_middle = 0;
    spinMotor_middle(motorSpeed_middle);
  }
  else if(digitalRead(yellowRight1) == LOW) {
    motorSpeed_right = 200;
    spinMotor_right(motorSpeed_right);
    delay(200);
    motorSpeed_right = 0;
    spinMotor_right(motorSpeed_right);
  }
  else if(digitalRead(yellowRight2) == LOW) {
    motorSpeed_right = -200;
    spinMotor_right(motorSpeed_right);
    delay(200);
    motorSpeed_right = 0;
    spinMotor_right(motorSpeed_right);
  }
  else if(digitalRead(blueAll1) == LOW) {
    motorSpeed_left = 200;
    motorSpeed_middle = 200;
    motorSpeed_right = 200;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    delay(200);
    motorSpeed_left = 0;
    motorSpeed_middle = 0;
    motorSpeed_right = 0;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
  }
  else if(digitalRead(blueAll2) == LOW) {
    motorSpeed_left = -200;
    motorSpeed_middle = -200;
    motorSpeed_right = -200;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    delay(200);
    motorSpeed_left = 0;
    motorSpeed_middle = 0;
    motorSpeed_right = 0;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
  }
  else if(motorSerial == 1) {
    motorSpeed_left = 200;
    motorSpeed_middle = 200;
    motorSpeed_right = 200;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    delay(2500);
    motorSpeed_left = 0;
    motorSpeed_middle = 0;
    motorSpeed_right = 0;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    motorSerial = 0;
  }
  else if(motorSerial == 2) {
    motorSpeed_left = -200;
    motorSpeed_middle = -200;
    motorSpeed_right = -200;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    delay(2500);
    motorSpeed_left = 0;
    motorSpeed_middle = 0;
    motorSpeed_right = 0;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    motorSerial = 0;
  }

}

/*****************************************************/
void spinMotor_left(int motorSpeed_left)
{
  if (motorSpeed_left > 0)
  {
    digitalWrite(AI1_left, HIGH);
    digitalWrite(AI2_left, LOW);
  }
  else if (motorSpeed_left < 0)
  {
    digitalWrite(AI1_left, LOW);
    digitalWrite(AI2_left, HIGH);
  }
  else
  {
    digitalWrite(AI1_left, LOW);
    digitalWrite(AI2_left, LOW);
  }
  analogWrite(PWMA, abs(motorSpeed_left));
}

void spinMotor_middle(int motorSpeed_middle)
{
  if (motorSpeed_middle > 0)
  {
    digitalWrite(BI1_middle, HIGH);
    digitalWrite(BI2_middle, LOW);
  }
  else if (motorSpeed_middle < 0)
  {
    digitalWrite(BI1_middle, LOW);
    digitalWrite(BI2_middle, HIGH);
  }
  else
  {
    digitalWrite(BI1_middle, LOW);
    digitalWrite(BI2_middle, LOW);
  }
  analogWrite(PWMB, abs(motorSpeed_middle));
}

void spinMotor_right(int motorSpeed_right)
{
  if (motorSpeed_right > 0)
  {
    digitalWrite(AI1_right, HIGH);
    digitalWrite(AI2_right, LOW);
  }
  else if (motorSpeed_right < 0)
  {
    digitalWrite(AI1_right, LOW);
    digitalWrite(AI2_right, HIGH);
  }
  else
  {
    digitalWrite(AI1_right, LOW);
    digitalWrite(AI2_right, LOW);
  }
  analogWrite(PWMA2, abs(motorSpeed_right));
}

ratchet freak's long answer has many good points. I would also agree
with Code Gorilla's suggestion to add a constructor to the struct.
However, once you have a constructor, it pretty much looks like a
regular C++ class¹, so it would make sense to add the motor-related
functions as members of the class. Thus I would start by building a
class that abstracts out the details of driving the motors:
class Motor {
public:
    Motor(uint8_t pin_1, uint8_t pin_2, uint8_t pin_pwm)
    : pin_1(pin_1), pin_2(pin_2), pin_pwm(pin_pwm) {}

    void begin() {
        pinMode(pin_1, OUTPUT);
        pinMode(pin_2, OUTPUT);
        pinMode(pin_pwm, OUTPUT);
    }

    void spin(int speed) {
        digitalWrite(pin_1, speed > 0 ? HIGH : LOW);
        digitalWrite(pin_2, speed < 0 ? HIGH : LOW);
        analogWrite(pin_pwm, abs(speed));
    }

private:
    const uint8_t pin_1, pin_2, pin_pwm;
};

I have left the buttons out of the class, because you have those blue
“all motors” buttons that do not fit well with the notion that each
button “belongs” to a particular motor.
Then, I would use some other abstraction for representing the buttons.
Maybe from a debouncing library. If button bounces are not problematic
in this application, then the “abstraction” would simply be:
// Is that button pressed?
static inline bool pressed(uint8_t pin) {
    return digitalRead(pin) == LOW;
}

Of course, as an abstraction, this does not provide a lot of value. It
can be seen as a small bit of “syntactic sugar” that makes writing (and
reading) the rest of the code easier.
With those in place, the program would look like:
// Pinout.
const uint8_t left_1   = 5;
const uint8_t left_2   = 4;
const uint8_t middle_1 = 3;
const uint8_t middle_2 = 2;
const uint8_t right_1  = 14;
const uint8_t right_2  = 15;
const uint8_t all_1    = 16;
const uint8_t all_2    = 17;
const int button_count = 8;
const uint8_t buttons[button_count] = {
    left_1, left_2, middle_1, middle_2, right_1, right_2, all_1, all_2
};

// Motors.
const int SPEED = 200;
Motor motor_left(11, 12, 13);
Motor motor_middle(10, 9, 18);
Motor motor_right(6, 7, 8);

void setup() {
    motor_left.begin();
    motor_middle.begin();
    motor_right.begin();
    for (int i = 0; i < button_count; i++)
        pinMode(buttons[i], INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    // Read the serial command, if any.
    int serial_command = Serial.read();  // is -1 if there is no input
    bool serial_1 = serial_command == '1',  // serial request for '1'
         serial_2 = serial_command == '2';  // serial request for '2'

    // Operate the motors.
    if      (pressed(left_1))   motor_left.spin(SPEED);
    else if (pressed(left_2))   motor_left.spin(-SPEED);
    else if (pressed(middle_1)) motor_middle.spin(SPEED);
    else if (pressed(middle_2)) motor_middle.spin(-SPEED);
    else if (pressed(right_1))  motor_right.spin(SPEED);
    else if (pressed(right_2))  motor_right.spin(-SPEED);
    else if (pressed(all_1) || serial_1) {
        motor_left.spin(SPEED);
        motor_middle.spin(SPEED);
        motor_right.spin(SPEED);
        if (serial_1) delay(2500);
    } else if (pressed(all_2) || serial_2) {
        motor_left.spin(-SPEED);
        motor_middle.spin(-SPEED);
        motor_right.spin(-SPEED);
        if (serial_2) delay(2500);
    } else {
        motor_left.spin(0);
        motor_middle.spin(0);
        motor_right.spin(0);
    }
}

¹ The struct keyword in C++ actually declares a class.

if(digitalRead(greenLeft1) == LOW) {
    motorSpeed_left = 200;
    spinMotor_left(motorSpeed_left);
    delay(200);
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
}
else if(digitalRead(greenLeft2) == LOW) {
    motorSpeed_left = -200;
    spinMotor_left(motorSpeed_left);
    delay(200);
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
}

Doesn't quite do what you want it to do.
Instead you want something like:
if(digitalRead(greenLeft1) == LOW) {
    motorSpeed_left = 200;
    spinMotor_left(motorSpeed_left);

} else if(digitalRead(greenLeft2) == LOW) {
    motorSpeed_left = -200;
    spinMotor_left(motorSpeed_left);
} else {
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
}

However because you also want a master switch and control through serial. You can pull out the tests on each button to a variable and then make the master switch override those:
int motor_left = 0;
if(digitalRead(greenLeft1) == LOW) {
    motor_left = 1;
} else if(digitalRead(greenLeft2) == LOW) {
    motor_left = -1;
} else {
    motor_left = 0;
}

//...

if(digitalRead(blueAll1) == LOW){
    motor_left   = 1;
    motor_center = 1;
    motor_right  = 1;
} else if(digitalRead(greenLeft2) == LOW) {
    motor_left   = -1;
    motor_center = -1;
    motor_right  = -1;
}

if(motor_left > 0) {
    motorSpeed_left = 200;
    spinMotor_left(motorSpeed_left);

} else if(motor_left < 0) {
    motorSpeed_left = -200;
    spinMotor_left(motorSpeed_left);
} else {
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
}

Also the pin number is just and int so you can pull those out as a parameter as well and have only one copy of the spinMotor function.
void spinMotor(int motor_pin1, int motor_pin2, int motorSpeed)
{
  if (motorSpeed > 0)
  {
    digitalWrite(motor_pin1, HIGH);
    digitalWrite(motor_pin2, LOW);
  }
  else if (motorSpeed < 0)
  {
    digitalWrite(motor_pin1, LOW);
    digitalWrite(motor_pin2, HIGH);
  }
  else
  {
    digitalWrite(motor_pin1, LOW);
    digitalWrite(motor_pin2, LOW);
  }
  analogWrite(PWMA, abs(motorSpeed));
}

To reduce the number of globals you can group the state for each motor into a struct and initialize them in init():
struct motorState {
   int motor_pin1, motor_pin2;
   int pwm_pin;
   int button1, button2;
   int direction;
   int speed;
}

motorState motor_left;
motorState motor_center;
motorState motor_right;

then pass the globals by pointer or ref to the functions doing the input and output.
void readMotorButton(motorState *motor){
    if(digitalRead(motor->button1) == LOW) {
        motor->direction = 1;
        motor->speed = 200;
    } else if(digitalRead(motor->button2) == LOW) {
        motor->direction = -1;
        motor->speed = 200;
    } else {
        motor->direction = 0;
        motor->speed = 0;
    }
}

void spinMotor(motorState *motor)
{
  if (motor->direction > 0)
  {
    digitalWrite(motor->motor_pin1, HIGH);
    digitalWrite(motor->motor_pin2, LOW);
  }
  else if (motor->direction < 0)
  {
    digitalWrite(motor->motor_pin1, LOW);
    digitalWrite(motor->motor_pin2, HIGH);
  }
  else
  {
    digitalWrite(motor->motor_pin1, LOW);
    digitalWrite(motor->motor_pin2, LOW);
  }
  analogWrite(motor->pwm_pin, abs(motor->speed));
}

If neither blueAll1 nor greenLeft2 are pressed, your else clause will prevent the other button from affecting the motors. 2. By motor_left > 1 you probably mean motor_left > 0. 3. The PWM pin should also be a parameter of spinMotor(). 4. readMotorButton() and spinMotor() look like they want to be methods of motorState.

1&2 yeah mistake; 3. I didn't realize that each motor had its own PWM pin; another argument in favor of grouping the motor states like that; 4. I'm not that much of a fan of creating member functions for simple stuff like this. YYMV though

There is a code review group on here where you will get a more generic code review if you want.
First thing I noticed is there are no comments.  You have written a paragraph explaining what the code does, but that should be in the code where you will be able to read it when you find the code 12 months down the line.
Rachet Freak has covered loads of good points, but one point I would disagree with is passing globals to functions using pointers.  I would use references instead, the only reason for this is IF you mess up references can't be NULL, so you don't need to check within the function to see if they are NULL.  Of course it will never happen, you never pass a NULL pointer to one of these functions, but as you code grows in size the chances of you doing that will increase and should you ever write a library, the chances of someone else passing a NULL pointer to your library is very high, and then you have got "a problem in your library".
Moving on from that if the parameter's value will not be modified during the life of a function pass it in as a const reference.  The main reason for this is it explains to the reader that the value won't change in the function, its a simple way of documenting your intention without having to write a comment.  So
void spinMotor(int motor_pin1, int motor_pin2, int motorSpeed){...}

would become
void spinMotor(const int& motor_pin1, const int& motor_pin2, const int& motorSpeed) {...}

Personally I would always add a constructor to structures.  This way you know that every field has the correct value to start with.  (I believe the Arduino compiler will initialise everything, but not all compilers are so kind.)  Also it allows you to write neater code, i.e.
struct motorState {
   int motor_pin1;
   int motor_pin2;
   int button1;
   int button2;
   int direction;

  // Parameterised constructor can be called either:
  //    motorState mState;
  //    motorState mState2 = motorState (2, 3, 4, 5, -1);
  motorState (const int& pin1 = 5, const int& pin2 = 6, const int& b1 = 7, const int& b2 = 8, const int& dir = 1)
  : motor_pin1(pin1)
  , motor_pin2(pin2)
  , button1(b1)
  , button2(b2)
  , direction(dir)
{}

}
Finally, I have always been told to never put two declarations on the same line.
int motor_pin1, motor_pin2;

There is no difference between the above and this as far as the compiler is concerned.
int motor_pin1;
int motor_pin2;

It is purely for readability you don't realise you are doing it, taking longer to read the first case than the second because your brain is more attuned to seeing a type, variable name and optional value.
int
motor_pin1,
motor_pin2;

The above is legal, but what type in motor_pin2?  It is just a convention that is widely used and makes code easier to read, even though it is harder to write, in the same way that code has to be indented by 4 spaces on here.  If it isn't indented it has the same text, but is virtually unreadable.
Finally, if you find yourself copy and pasting lines, it should probably be a function or an array or both.

You don't want to pass an int as a reference unless the intention is for the function to change the original value. Ints are too small, and the overhead of passing a reference is larger than the overhead of copying the int. And if you do want the original value to be modified, your intention may be clearer with a pointer (though there is more potential for a crash).

I see what you mean but it may depend on the platform you are targeting.

Very good point. Though I don't think a reference could possibly have less overhead than a small primitive type.


text:
Set variable value with serial?
so I need to make a arduino program, generates 2 random numbers, makes a + calculation with them and asks user the right answer. If the answer is right AKA Calculation==User Answer, then led is set to LOW, and serialprint sent. If its wrong, Led lights up and serialprint sent again. It works if i set the variables manually etc. But the I think the problem is with my serialRead, somehow it doesnt set the value it got from the user as the value of the variable (Luku4)
Here is the code, I hope you can help me.
int Luku1 = 0;
int Luku2 = 0;
int Luku3 = 0;  //Summa
int Luku4 = 0; //Vastaus
const int ledPin = 13;
byte i = 0;

void setup() {

  for (i=0; i<4; i++){
pinMode(ledPin, OUTPUT);
}

randomSeed(analogRead(0));
Serial.begin(9600);
Serial.println("Arvotaan 2 satunnaislukua ja summataan ne yhteen. Kerro oikea vastaus");
}

void loop() {
  Serial.println("Arvotaan 2 satunnaislukua");
  Luku1 = random(1,5);
  Luku2 = random(1,5);
  Serial.println(Luku1);
  Serial.println("+");
  Serial.println(Luku2);
  Luku3 = Luku1 + Luku2;
  delay(100);
  Serial.println("Mika on vastaus?");
  Luku4 = Serial.read();
    while(Serial.available() == 0){}

  if (Luku4==Luku3) {
    digitalWrite(ledPin, LOW);
    Serial.println("Oikea vastaus");
    delay(2000);
  }

  else{
    digitalWrite(ledPin, HIGH);
    Serial.println("Vaarin");
    delay(2000);
    digitalWrite(ledPin, LOW);

  }
}

You should move the Serial.read to after the  "wait for serial input"-line. Secondly. Serial.read will return a character, not a number. So you have to convert the ascii value of the letters "0"-"9" to the integer value of 0-9. This can be done by subtracting 48, as "0" is ascii code nr 48.

Oh, never heard of that. Thanks alot, it worked!

but it still works only for one digit and not for a number. use parseInt https://www.arduino.cc/reference/en/language/functions/communication/serial/parseint/

These could all by byte, vs int, as they will not be more than 255:int Luku1 = 0;
int Luku2 = 0;
int Luku3 = 0;  //Summa
int Luku4 = 0; //Vastaus
const int ledPin = 13;

And why do you need to set this pin to an  output 4 times? Once is enough   for (i=0; i<4; i++){
pinMode(ledPin, OUTPUT);
}

You are comparing a byte which was read through uart with a number. If you send number '5' through uart, you won't get number 5, but character '5'. To convert single character to number, you can do following:
Luku4 = Serial.read(); // '0' .. '9'
Luku4 = Luku4 - '0'; // 0..9

But this will work only for single digit numbers, for more robust solution please refer to readString function to see how you can read strings from UART and to function atoi which converts string to number.

You are reading Serial before you check that there is anything valid to read:
Luku4 = Serial.read();
while(Serial.available() == 0){}

Try swapping those two lines.

Swapped, Still not working. Only gives the "else", no matter what I input. Thanks for the help still.

Try changing these lines
Luku4 = Serial.read();
while(Serial.available() == 0){}

to these lines
while(Serial.available() == 0){}
Luku4 = Serial.parseInt();

As shown in the Arduino documentation, Serial.parseInt() will read a number from Serial. If a non-number character is entered it will return 0.


text:
how to set the pin 13 only HIGH for 1 minute if sensor at pin 8 give HIGH?
int PUMP = 13;
int sensor = 8;
int val;

void setup() {
  pinMode(13,OUTPUT);
  pinMode(8,INPUT);
}

void loop() {
  val = digitalRead(8);
  if(val == HIGH)
  {
    digitalWrite(13,HIGH);
  }
  else
  {
    digitalWrite(13,LOW);
  }

  delay(0);
}

the digital input (pin8) has four basic states that you can be used to trigger an event (pin13)  ..... the four are low, rising edge, high and falling edge  ..... assume that the low and high states can be indefinitely long .... you have to decide which state triggers the 1 minute timer and whether some state re-triggers the 1 minute timer before it times out

Just add delay after you turn on pin 13. So it would be:
int PUMP = 13;
int sensor = 8;
int val;

void setup() {
  pinMode(13, OUTPUT);
  pinMode(8, INPUT);
}

void loop() {

  val = digitalRead(8);

  if (val == HIGH)
  {
    digitalWrite(13, HIGH);
    delay(60000); //60000ms is 1 minute
  }
  else
  {
    digitalWrite(13, LOW);
  }
}

I want to add to the answer of Ian:

If you later want to do something within that minute, you should not use delay. Instead use millis, see Blink without delay and use the same principle. It is considered bad practice to use delays, since it prevents from doing anything else in the mean time. For your small example it is not a problem though.
Also check what you really mean with requirement 'set pin 13 high if pin 8 is high' :

What if pin 13 stays high for 2 minutes, should pin 8 stay high 1 minute from the start that pin 13 got high (thus will be low when pin 13 is still high)
Or should pin 8 stay high 1 minute after pin 13 gets to low again. In this case you need to check for flanks instead of only the current state.

That's a poor way to do it, the uC is then sitting there for a minute unable to do anything else.
A better way is to capture the time of the input pin, then keep checking the time until 1 minute has elapsed.
void loop(){
   if ((digitalRead(8) == HIGH) && (timerRunning == 0)){
      startTime = millis(); // all time variables are type unsigned long
      digitalWrite (13, HIGH);
      timerRunning = 1;
   }
   if (timerRunning == 1){
      timeNow = millis();
      if ((timeNow - startTime)>= 60000UL){
         timerRunning = 0;
         digitalWrite (13, LOW);
      } //end time pass check
   } // end timer running check
   // now you can do other stuff while waiting for time to pass
} // end loop


text:
Timer0 overflow interrupt not working

I try to use the Timer0 of an Arduino Leonardo (ATmega32u) to trigger an interrupt at regular intervals, using plain avr-gcc (not the arduino library). I try to blink the built-in LED as test, but it does not light up.
If I place a PINC=0x80; in the main function, the LED turns up, but not if I do it from the interrupt.
What am I doing wrong?
EDIT : The LED turns on with TCCR0B = (1 << CS00);, (no prescaler) or TCCR0B = (1 << CS01) (prescaler /8), but it does not with TCCR0B = (1 << CS00) | (1 << CS02); (prescaler /1024, what I want). At 16MHz CPU frequency the resulting frequency should be more than 15kHz, so I should see it instantly.
Here is my code:
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdbool.h>

ISR(TIMER0_OVF_vect)
{
    PINC = 0x80;
}

int main()
{
    DDRC = 0b10000000;

    //Start Timer 0 @ 15625 Hz
    TCCR0A = 0;
    TCCR0B = (0b101 << CS00);
    TIMSK0 = (1 << TOIE0);
    sei();

    while(true); // Avoid return from main
}

what research have you done?

@jsotola I read the corresponding chapters of the processor datasheet and googled for a while, but I only found unrelated issues (e.g. using CTC mode or returning from main).

i misread .... deleting my comments .... you can delete yours

then you have to assume that the ISR is never called  .....maybe this may help  ....... http://www.instructables.com/id/Arduino-Timer-Interrupts/

Sidenote: 0b101 <<  CS00 looks like bad code. Personally; I’d use (1 <<  CS00) | (1 << CS02)

I just found the answer here : https://www.avrfreaks.net/forum/atmega32u4-arduino-leonardo-strange-timer-behavior
It seems that the USB connection generates higher-priority interrupts. I still don't know why the interrupts do work at higher frequency.
Solutions include powering the board from a USB charger or other power source rather than through the computer USB or adding the following code before the interrupt enable :
// Clear usb interrupt flags
USBINT = 0;
UDINT  = 0;
for (uint8_t i = 0; i < 6; i++)
{ // For each USB endpoint
    UENUM = i; // select the _i-th endpoint
    UEINTX = UEIENX = 0; // Clear interrupt flags for that endpoint
}

Thanks to those who helped me !

I think the interrupt handler is missing when the bootloader exits, so avr-gcc defaults to reset the board, which might result in higher frequency to switch on the led while at lower frequency the board is reset before the first interrupt.


text:
How to indicate an End of a stream on USB
I am making a Lora-USB passthrough device using arduino and somehow I want to indicate that a stream over some data has ended.
So far I have done:
void onLoRaReceive(int packetSize) {
  if (packetSize == 0) return;          // if there's no packet, return

  byte[packetSize] buffer=[];

  while (LoRa.available()) {
    site_t recievedData=LoRa.readBytes(buffer,packetSize);
    Serial.write(buffer,recievedData);
  }
}

So what I want to know is how the software reading from the serial interface will know that a packet has ended; One way I thought is by sending an EOF byte but I am afraid of "rogue" EOF values in packet data.
An another way is to send the packet size through the Serial interface as well but how I will make it understand that what I am sending now is the size and expect X size of data?

LoRa has a moderate data rate and typically substantial gaps between packets, so a simple thing you can do is send the data as printable ASCII hex with newlines or other terminators.
This will just short of double the amount of data you have to move, but do so in a very simple and deterministic way, and you can crank up the serial baud rate to handle it, especially as the baud rate only actually "exists" between two ATmega chips within the Uno.
Another plus is that the data becomes human readable, which is handy for debugging, especially if you might want to intermix advisory messages and data.

What you need is some form of protocol. Some system that both ends of the communication channel agree on.
Most serial protocols use certain characters to indicate certain things, and indeed the ASCII character set has certain characters earmarked for certain jobs in communication, so it makes sens to use those.
One you can use is EOT - End Of Transmission - character 0x04. Note: there is no such thing as an "end of file character 'EOF'". That's purely a DOS construct.
And yes, you may wonder about a rogue 0x04 in the data stream triggering the end, and you're not the first to think about that. That's why there's character 0x10 - DLE. That's Data Link Escape. Its purpose is to tell the receiving end "The next character I send is a data character. Don't interpret it as a control character.".
So for every 0x04 in the data stream you should send 0x10,0x04 instead.  Your receiver code then sees the 0x10 and makes a note that the next character should not be interpreted as a control character, but raw data.
Problem solved.
But what, you ask, about there being a rogue 0x10 in the data stream?  Isn't that going to cause the same problem?
Yes. And you deal with it in exactly the same way. Just prefix it with 0x10. Since the receiver should then know to always interpret the next character as data, regardless of what it is, it will see the next 0x10 as data.
So as an example, sending the following data stream:
0x06,0x31,0xc7,0x04,0x91,0x10,0x04,0x73

would be done as:
0x06,0x31,0xc7,[0x10],0x04,0x91,[0x10],0x10,[0x10],0x04,0x73

(Added 0x10s highlighted with brackets).
It can be good to use some of the other control bytes as well, such as SOH for Start Of Header, STX for Start of TeXt, ETX for End of TeXt, etc. You can then do such things as tell the receiver where the start of your packet is, and what the different bits of it are. Adding a header with the length and a checksum can also be worthwhile too, for increased reliability and data integrity.

I wonder also if FTDI devices also have in-protocol serial transmission handling and Arduino Serial interface offers these type of handlings out of the box.

Also in case of calues that are over a 7-bit ASCII range ( >128 ) should I escape it with 0x10 as well for example the 0xFF value?

Why would you want to? You only need to DLE the bytes that your protocol uses.


text:
Dim a led using a NPN transistor
I know there are a lot of questions about this topic, but I've tried everything and any possible guide online without success.
I want dim (increase and decrease the brightness) some leds (3.5 Watt each). To do that I'm using an Arduino Nano, a 10k potentiometer and an NPN transistor (TIP41).
I was able to drive the potentiometer as a switch: on/off. Now I want to control its brightness using the potentiometer. I don't get what I'm expecting because the led is always on except when the potentiometer is turned all the way on the right (where is connected Vcc).
This is the schematic:

This is my Arduino code:
int pinPotentiometer = 0;
int pinTransistor = 3;

void setup() {
  Serial.begin(9600);
  pinMode(pinTransistor, OUTPUT);
  pinMode(pinPotentiometer, INPUT);
}

void loop() {
  int potValue = analogRead(pinPotentiometer);
  int outValue = map(potValue, 0, 1023, 0 ,255);
  Serial.println(outValue);
  digitalWrite(pinTransistor, outValue);
  delay(100);
}

The potentiometer is working fine because I read from the serial values between 0 and 255.
Am I using the wrong transistor? Or maybe I'm using it in the wrong way?
NOTE: to test my circuit I'm using a small 5mm led and not the 3.5 Watt one so I don't have any external power source.
Many thanks!

Use analogWrite() instead of digitalWrite(). And make sure you're using a PWM-capable pin.

Try using analogWrite().
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite()) on the same pin. The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz.
Source: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

Considering using a protected MOSFET, it will run much cooler then the transistor.  Reason the transistor has a 0.7V collector emitter voltage drop, the MOFET will be less then 0.01 depending on choice. You are missing a resistor from the base to the Nano.  Use something in the 50 to 120 Ohm for the MOSFET to keep it ultra stable. Be sure to use a seperate power supply with the high wattage LEDs. Also connect the power supply grounds.

@Gil - The OP stated they were using a TIP41 transistor. Perhaps your comment would be useful if you added it to the question.

your transistor base should be connected to the PWM side of the Arduino and not the collector. put a 1kOhm resistor between that base and arduino too. collector to load, load to positive of battery or power source. emitter to ground.

You also need a resistor on the collector side, if the load is a LED. For 3W Led you need a fat resistor (some Watts)


text:
How to protect link/url form ESP-12E for controlling LED
I am using ESP8266 ESP-12E NodeMCU for controlling LEDs and Relay.
When ESP-12e power on it connect into my home wifi network and it gives IP address such as 192.168.0.104, and by that I can control my devices through Localhost.
I am using link or url to control my application such as
192.168.0.104/status1=1 (for starting LED 1 start)
192.168.0.104/status1=0 (for turn off LED)
but my point is how to secure 192.168.0.104/status1=1 or 192.168.0.104/status1=0.
Because it is open for all and however if some one do just for fun and turn off my Relays and LEDs it will be very risky for home application.
Here is my code, this code works very well:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "Asif Wifi";
const char* password = "asif0172";

ESP8266WebServer server(80);

const int output1 = D1;
const int output2 = D2;
const int output3 = D3;
const int output4 = D4;

boolean device1 = false;
boolean device2 = false;
boolean device3 = false;
boolean device4 = false;

void handleRoot() {
  //digitalWrite(led, 1);
  //server.send(200, "text/plain", "hello from esp8266!");
  //digitalWrite(led, 0);

  String cmd;
      cmd += "<!DOCTYPE HTML>\r\n";
      cmd += "\r\n";
      //cmd += "<title>ESP8266 Webserver</title>
\"ESP8266 Web Server Control\"
";
      cmd += "";
      cmd += "<meta http-equiv='refresh' content='3'/>";
      cmd += "";

      if(device1){
        cmd +=("
Device1  : ON");
      }
      else{
        cmd +=("
Device1  : OFF");
      }

      if(device2){
        cmd +=("
Device2  : ON");
      }
      else{
        cmd +=("
Device2  : OFF");
      }

       if(device3){
        cmd +=("
Device3  : ON");
      }
      else{
        cmd +=("
Device3  : OFF");
      }

      if(device4){
        cmd +=("
Device4  : ON");
      }
      else{
        cmd +=("
Device4  : OFF");
      }

      cmd += "\r\n";
      server.send(200, "text/html", cmd);
}

void handleNotFound(){
  //digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  //digitalWrite(led, 0);
}

void setup(void){
  pinMode(output1, OUTPUT);
  pinMode(output2, OUTPUT);
  pinMode(output3, OUTPUT);
  pinMode(output4, OUTPUT);

  digitalWrite(output1, LOW);
  digitalWrite(output2, LOW);
  digitalWrite(output3, LOW);
  digitalWrite(output4, LOW);

  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");

  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.on("/status1=1", [](){
    server.send(200, "text/plain", "device1 = ON");
    digitalWrite(output1, HIGH);
    device1 = true;
  });

  server.on("/status1=0", [](){
    server.send(200, "text/plain", "device1 = OFF");
    digitalWrite(output1, LOW);
    device1 = false;
  });

  server.on("/status2=1", [](){
    server.send(200, "text/plain", "device2 = ON");
    digitalWrite(output2, HIGH);
    device2 = true;
  });

  server.on("/status2=0", [](){
    server.send(200, "text/plain", "device2 = OFF");
    digitalWrite(output2, LOW);
    device2 = false;
  });

  server.on("/status3=1", [](){
    server.send(200, "text/plain", "device3 = ON");
    digitalWrite(output3, HIGH);
    device3 = true;
  });

  server.on("/status3=0", [](){
    server.send(200, "text/plain", "device3 = OFF");
    digitalWrite(output3, LOW);
    device3 = false;
  });

  server.on("/status4=1", [](){
    server.send(200, "text/plain", "device4 = ON");
    digitalWrite(output4, HIGH);
    device4 = true;
  });

  server.on("/status4=0", [](){
    server.send(200, "text/plain", "device4 = OFF");
    digitalWrite(output4, LOW);
    device4 = false;
  });

  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

Only need to know how to secure this system, that's it.
Thank you.
Dear Garben,
well I am trying in your way but I can not add variable and can not operate by operator..... Here is my code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "Asif Wifi";
const char* password = "asif0172";

const char* pwd = "dada123456";

ESP8266WebServer server(80);

const int output4 = D4;

boolean device4 = false;

void handleRoot() {
  //digitalWrite(led, 1);
  //server.send(200, "text/plain", "hello from esp8266!");
  //digitalWrite(led, 0);

  String cmd;
      cmd += "<!DOCTYPE HTML>\r\n";
      cmd += "\r\n";
      //cmd += "<title>ESP8266 Webserver</title>
\"ESP8266 Web Server Control\"
";
      cmd += "";
      cmd += "<meta http-equiv='refresh' content='3'/>";
      cmd += "";

      if(device4){
        cmd +=("
Device4  : ON");
      }
      else{
        cmd +=("
Device4  : OFF");
      }

      cmd += "\r\n";
      server.send(200, "text/html", cmd);
}

void handleNotFound(){
  //digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  //digitalWrite(led, 0);
}

void setup(void){

  pinMode(output4, OUTPUT);

  digitalWrite(output4, LOW);

  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");

  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.on("/status4=1&password=" + pwd, [](){
    server.send(200, "text/plain", "device4 = ON");
    digitalWrite(output4, HIGH);
    device4 = true;
  });

  server.on("/status4=0&password=" + pwd, [](){
    server.send(200, "text/plain", "device4 = OFF");
    digitalWrite(output4, LOW);
    device4 = false;
  });

  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

Use something like 192.168.0.104/status1=1&password=12345 for at least some very basic security.

Gerben: Ok sir I going to test it.

Dear Gerben please check question again I just update next problem.

You need to take a look at the HttpBasicAuth example that comes with the ESP8266's ESP8266WebServer library that you are using. It is simple enough.
Here it is pasted in for reference:
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <ESP8266WebServer.h>

const char* ssid = "........";
const char* password = "........";

ESP8266WebServer server(80);

const char* www_username = "admin";
const char* www_password = "esp8266";

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if(WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Connect Failed! Rebooting...");
    delay(1000);
    ESP.restart();
  }
  ArduinoOTA.begin();

  server.on("/", [](){
    if(!server.authenticate(www_username, www_password))
      return server.requestAuthentication();
    server.send(200, "text/plain", "Login OK");
  });
  server.begin();

  Serial.print("Open http://");
  Serial.print(WiFi.localIP());
  Serial.println("/ in your browser to see it working");
}

void loop() {
  ArduinoOTA.handle();
  server.handleClient();
}

The key part is this bit:
    if(!server.authenticate(www_username, www_password))
      return server.requestAuthentication();

Add that into your handler for your URL and it will ask for a username and password which you provide as www_username and www_password.
There's a more advanced example too if you want to delve deeper.

Ok..sir, Thank you. I will try it right now but I will tell you tomorrow.


text:
How to decrease adc accuracy?
I read in this atmega328p datasheet the following on page 308:
From sect. 28.4:

By default, the successive approximation circuitry requires an input
clock frequency between 50kHz and 200kHz to get maximum resolution. If
a lower resolution than 10 bits is needed, the input clock frequency
to the ADC can be higher than 200kHz to get a higher sample rate.
The
ADC module contains a prescaler, which generates an acceptable ADC
clock frequency from any CPU frequency above 100kHz. The prescaling is
selected by the ADC Prescaler Select bits in the ADC Control and
Status Register A (ADCSRA.ADPS). The prescaler starts counting from
the moment the ADC is switched on by writing the ADC Enable bit
ADCSRA.ADEN to '1'. The prescaler keeps running for as long as ADEN=1,
and is continuously reset when ADEN=0.
When initiating a single ended
conversion by writing a '1' to the ADC Start Conversion bit
(ADCSRA.ADSC), the conversion starts at the following rising edge of
the ADC clock cycle.
A normal conversion takes 13 ADC clock cycles.
The first conversion after the ADC is switched on (i.e., ADCSRA.ADEN
is written to '1') takes 25 ADC clock cycles in order to initialize
the analog circuitry.

By required bandwidth is 120 kHz, and 5 bit accuracy will suffice for my purpose. So, I understand that I can achieve this by changing the prescaler to a lower division number, thus increasing the clock frequency fed into the ADC (as per the diagram in the aforementioned document).
However, the document only specifies the min and max times required for ADC conversion for 50 kHz (12 to 280 microseconds at 50kHz bandwidth).
My question: Given my requirement of 120kHz bandwidth, what is the lowest prescaler division value I should use to guarantee ADC completion time to within 1/120kHz seconds (8.3us)?
EDIT: This is another question I have: Why does the accuracy change when using a lower divider value? Surely we are simply changing the clock frequency fed into the ADC converter, not the ADC algorithm itself; so why should the bit accuracy change?

From: http://forum.arduino.cc/index.php?topic=6549.0
The documentation states that 13 cycles are neccesary for ADC conversion. Thus, using the clk/13*8 divisor configuration, and 16 MHz system clock, the upper bound becomes 154KHz
The forum post in the above link continues to say that "ADC clock frequencies above 1MHz are uncharacterised", however this was quoting another document for which the link is dead. I could not find this statement in the most recent documentation.
Edit: Another forum post where a user successfully used an atmega328p to achieve 360000 samples/sec, so it is technically possible:
http://forum.arduino.cc/index.php?topic=8795.0

Nick Gammon did some tests with various prescaler values, and the data at prescaler = 8 shows errors as large as 17% of the full scale.


text:
3rd Libraries: fatal error: Something.h: File does not exist

I created this question because I find many questions with similar problems,
  so I wanted to provide a reference/ more generic question for these type of problems.

For my projects I have installed 3rd party libraries by cloning from the library's git repository into the folder that preferences.txt's sketchbook.path value exists into a folder named libraries. In other words if the sketchbook.path has the value /home/myuser/sketchbook I clone the repositories into the folder /home/myuser/sketchbook/libraries.
Then on the folder /home/myuser/sketchbook/myexample I store my code myexample.ino that needs a library with header files Something.h.
While I click on Arduino IDE the verify button I get the error:
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions
    -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD
    -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__
    -I/usr/share/arduino/hardware/arduino/cores/arduino
    -I/usr/share/arduino/hardware/arduino/variants/standard
    -I/usr/share/arduino/libraries/SPI
    /tmp/build6596169359663087897.tmp/LoRaSerialGateway.cpp -o
    /tmp/build6596169359663087897.tmp/LoRaSerialGateway.cpp.o
LoRaSerialGateway.ino:15:18: fatal error: Something.h:
compilation terminated.

So my guess is that I cannot make avr-gcc to compile using the 3rd party library. Do you know how to pass into avr-gcc the correct paths for the appropriate libraries?

The Arduino IDE will handle it, provided the libraries are actually installed via the IDE.

Assuming you have a working library system already, i.e., there are some libraries in .../libraries now and they compile properly or at least the compiler are successfully finds them; and you want to add another library, say "CrashAndBurn.h" and "CrashAndBurn.cpp", you need to put those two files into a folder named .../libraries/CrashAndBurn/. Then in your sketch, you add an include directive #include <CrashAndBurn.h>.
An alternative is to put the .h and .cpp files somewhere else, such as a folder under your project folder, and modify the include directive to point to them, as #include "libs/CrashAndBurn.h", where the libs folder is within the sketch folder. Or you could put them in any folder, anywhere, and write an absolute path to them: /home/some/place/else/CrashAndBurn.h

Sometimes you should modify a bit the library's file stricture in case of this library in order to make it avaialble I moved the code in folder ./src outside to the project's root folder.
Also an another problem is that you may use older version of the ide. Especially this can happen in GNU/Linux if you install the arduino ide from the distribution's repositories.

just rename the folder from zip to LoRa in libraries. no need to move files

I used the git method.

I create file system link from git folder to libraries folder, with the correct library name


text:
Arduino IDE Display Code Line Numbers
In the Arduino IDE: How can I get the line numbers shown in a sidebar of the editor?
It is hard to find which line my errors are referring to without them...
I am using Arduino IDE on a form of Windows.

@crabman84, how do you know that the the person who posted this question > 2 years ago was using Windows?

Go to File > Preferences. Under the Settings tab, click the checkbox for Display line numbers.

Keep in mind that this option is available in the latest version of the Arduino Integrated Development Environment (v1.6.6). In case you are using GNU/Linux distribution is recomended to use the one that is NOT in the distribution's repositories but the one that is offered in https://www.arduino.cc/en/Main/Software
If you are using a Linux OS this solution may not work. Look at the 'preferences.txt' where you can edit your preferences in a file without a GUI.It will display all possible options available for your current version of Arduino IDE on your OS. It is usually in the '.arduino' folder which may be in your 'home' folder.

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


text:
Arduino Uno programed from a Nvidia Jetson tx2
I'm trying to program my Arduino Uno with a Jetson tx2 and get the error
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

The serial port is set to /dev/ttyS0
dmesg when the Arduino is plugged in returns
[78222.855639] usb 1-1: USB disconnect, device number 60
[78224.468387] usb 1-1: new full-speed USB device number 61 using xhci-tegra
[78224.605794] usb 1-1: feature bit otg_vbus_off set
[78224.610575] usb 1-1: New USB device found, idVendor=2341, idProduct=0043
[78224.617365] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[78224.624750] usb 1-1: Manufacturer: Arduino (www.arduino.cc)
[78224.630502] usb 1-1: SerialNumber: 55739323237351306122
[78224.636529] usb 1-1: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[78224.646057] xhci-tegra 3530000.xhci: tegra_xhci_mbox_work mailbox command 6

lsusb returns
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 054: ID 413c:2107 Dell Computer Corp.
Bus 001 Device 065: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Did you notice that the log doesn't mention a device file?

I did not what does that mean I have to do

The version of the Arduino IDE contained in the Jetson repositories is buggy on the Jetson TX2 with Jetpack 3.2+ and the Arduino IDE in the repository is rather old.  Instead, try the beta related to Github Issue #7302.  This beta should work with the Jetson and other aarch64 platforms.  Many thanks to the wonderful people working to support this platform.
Steps
After downloading and unpackaging the build, perform the following steps:
#Install the OpenJDK Dependencies
sudo apt-get install openjdk-8-jre openjdk-8-jdk

#Remove the Packaged Java Folder
cd ${PATH}/arduino-PR-beta1.9-BUILD-69
sudo rm -r java

#Add armhf Architecture to Package Manager
sudo dpkg --add-architecture armhf
sudo apt-get update
sudo apt-get install libc6:armhf libstdc++6:armhf

#Install the Arduino IDE
sudo ./install.sh
sudo ./arduino-linux-setup.sh

#Reboot

Notes

The script arduino-linux-setup.sh handles the permissions for the IDE to talk to ttyACM0, updates the udev rules, and removes the pesky Modem Manger.
The armhf packages are necessay to prevent ctags from crashing.
If you are still having issues with CDC/ACM, install the module using the scripts from JetsonHacks

The device should be /dev/ttyACM0, not /dev/ttyS0.
Since it doesn't provide you with that device it rather looks like it doesn't have the CDC/ACM device drivers installed or loaded.
Depending on what distribution of Linux you're running on there you may need to install additional packages (you certainly do for OpenWRT, but I have no clue what that device is you're using or what it's running).

Jetson's run Ubuntu. I have found posts saying it should show up as /dev/ttyUSB0, but I don't know how to have it do so.

Maybe ask on a site where someone knows what one of these Jetson things is. CDC/ACM, which is what the Arudino uses, will be /dev/ttyACM0. It's only /dev/ttyUSB0 for FT232 or other similar custom UART interfaces (CH340G, etc).

When you built your Jenson kernel, did you enable the CDC/ACM driver using menuconfig?
From Arduino Playground:

If you configured your own kernel, the driver is either under "Device
  Drivers => USB Support => USB Serial Converter Support => USB FTDI
  Single Port Serial Driver" or "Device Drivers => USB Support => USB
  Modem (CDC ACM) support". Select [Y], to have it "built in" to the
  kernel or [M] to have it built as a module.

I'm not familiar with Arduino and whether it would show up as /dev/ttyUSB0 or /dev/ttyACM0 per @Majenko.


text:
Reading bitswise for 'FALSE'
In the sketch I'm working on, I'm storing several 1-bit values representing different boolean states in a single byte, trying to save precious RAM.
(example for 5 boolean states: dec10 = b00001010, the five states are 0, 1, 0, 1, 0)
I'm then using an if statement to determine if the relevant bit is TRUE or FALSE:
if ((options>>3) & 1 == 1)
The above will evaluate true when the relevant bit is 1, so if I want to carry out something in that case, great, no problem!
However, if I want my if statement to evaluate TRUE in the event that the relevant bit is 0, I can't work out what code I need.

I thought the problem might be that the other 'non-relevant' bits were interfering, so I tried bit shifting the LSB all the way to MSB position and then shifting back to LSB:
if ((options<<4>>7) & 1 == 0)
but this still isn't doing what I'm trying to achieve (and seems like a lot of work for the processor).
It also feels like I've tried just about every combination of ~&0, !&0, ==0, !=0, ~&1, !&1, ==1, !=1 there is, but I must have missed something...
Can anyone tell me how I get an if statement to evaluate true in the event that the bit is a zero?

Welcome to Arduino:SE. You might find this helpful: How to ask a good question for Arduino Stack Exchange

if ((options>>3) & 1 == 0) or if ((options>>3) & 1 != 1) - if neither of them work, you did something wrong

The simplest thing is just to mask an individual bit, not do any shifting:
if (options & 0x04) {
    // Do something if true
} else {
    // Do something if false
}

Or, to invert it:
if (!(options & 0x04)) {
    // Do something if false
} else {
    // Do something if true.
}

The thing with C is that 0 is false, and anything else is true.  So if your options variable contains 0b00001010 and you AND it with 0x04 (which is HEX for 0b00001000) you end up with 0b00001000.  That is 0x04, which is something other than 0, so it's true.
If options contains 0b00000010 and you AND it with 0x04, you get 0b00000000, which is 0. Since 0 is false the result is false.
You don't care what the actual number is - you only care if it's 0.

This is exactly what I needed, the exclamation mark goes to the left of the statement being evaluated, thanks @Majenko. You've also taught me a much better way of singling out the bit I'm interested in, perfect!

for readibility add a definition like #define myImportantOption  0x04 ..... then use if (options & myImportantOption) {  .......... put all the definitions at the beginning of your program, so that you can easily change them if you use a different arduino that may have status bits in a different location

@jsotola - good advice for code readability and portability. Would this make any difference to what the ATMEGA sees, or are differences such as this all compiled identically before upload?

There is an alternative to doing bit shifts, and that is to use the bit macro which is defined in Arduino.h (and thus is automatically available).
#define bit(b) (1UL << (b))

Now if you want to see if the second bit is set (which as a mask would be 0x04, being 1 shifted left 2 times) you can do this:
if (options & bit (2))
   {
   // bit number 2 is set
   }
else
   {
   // bit number 2 is clear
   }

This is easier to read than:
if (options & (1 << 2))

or:
if (options & 0x04)

And to invert it:
if (!(options & bit (2)))
   {
   // bit number 2 is clear
   }

Or:
if ((options & bit (2)) == 0)
   {
   // bit number 2 is clear
   }

Also, the various processor bits are given as bit numbers in the Atmega include files (rather than bit masks).

So, for example, to set some processor bits you can do this:
WDTCSR |= bit (WDCE) | bit (WDE);

That is easier to read than:
WDTCSR |= (1 << WDCE) |  (1 << WDE);

And much easier than turning them into hex numbers:
WDTCSR |= 0x10 | 0x08;

And in case you are wondering how to clear a bit, you and in the 1s complement:
WDTCSR &= ~bit (WDCE);

What’s wrong with the _BV() macro that’s already included?

@Nick - bit is new to me, makes things very easy to read, thank you

@Gerben Because identifiers starting with an underscore and followed by an uppercase letter are reserved and should not be used. For example Identifiers (C++). Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers.

@Gerben As I pointed out the bit() macro is also already included. I quoted the file it is in (Arduino.h) which will be present in all attempts to compile with the IDE.

(I should have read better.) I didn’t know _BV was none standard. But since it’s replaced by the pre-processor the compiler will never see it q-; . So I will switch to using bit. It’s also easier to type, which is a bonus. Thanks.

@Gerben - the compiler may never "see" it, but let's assume that one day the compiler-writers decide to use _BV for some internal construct (as they are permitted to do, as it is reserved), and the macro form of _BV in Arduino.h overrides that. The compiler will see the difference and not work correctly.


text:
Small Baseball Scoreboard using 2 to 3 breadboards
I'm helping my son start an Arduino small baseball scoreboard (roughly 2 or 3 breadboards in size). Im thinking to use qty 2, 2 digit 7 segment LED's (score of each team), an LCD 1602 module (inning tracker), using a serial monitor. Last is 3 individual LED's (controlled with a switch or remote).
My question is: can one arduino drive all of this? What would be a recommended configuration?
Thank you,Dave

which arduino? there's many models to choose from

Codewise that shouldn’t be a problem. But you might run out of pins to connect them. I’d suggest getting the seven segment displays on a breakout with a driver chip on it. Those will make them easier to use, and require less pins.

Actually, you can very easily verify this yourself:

Per item (1602LCD, 7 segment LCD and LEDs check how many pins you need and what type, like e.g. I2C or SPI for the 1602 LCD). The 7 segment displays can have many or less pins, depending on the 'controller', See the reaction of CrossRoads below.
Count them together. If it fits on the Arduino you want to use OK. The Uno is cheapest, so if it fits on it, you use that, otherwise you can go to the Mega.
As alternative, and you need 'generic pins, called GPIOs' (not SPI/I2C) for some, you can use multiplexers like 74HC595 to reduce the number of GPIOs needed, at the cost of some speed (not critical for your project), and some more programming work.
In some cases you can use a MAX7219 driver IC, see (again) the remark of Crossroads below.

Do the 2-digit displays have seperate pins for all the segments? The parts witll have 16 or 18 pins. If they have common segment pins, the parts will have 10 pins; 1 for each segment, and a common anode or common cathode for each digit. The 2nd type will need multiplexing: display data for 1 digit for a short time (like 3-5 milliseconds) with one anode/cathode pin, then display data for the 2nd digit with the other anode/cathode pin.  If the 2 displays are the same, then both units can have their segment pins in parallel, and 4 unique common anode/cathode pins are used to multiplex the digits.

@CrossRoads Thanks for the valuable remark, I refered to your remark in my answer.

If the 7-segment displays are common cathode, you can easily use a MAX7219 to drive them, just write the data to be displayed to 4 registers and it takes care of the multiplexing.  Common anode is also possible,  but you have to do a little data mapping.

@CrossRoads thanks for improving my answer again (updated the answer).


text:
USB reset fails on arduino due because of 5v on digital pins
I have the signal channels of four 5v magnetic encoders connected directly to the digital pins of the arduino due. I am aware that this is not allowed according to the specification which says that digital pins should only sink 3.3v but I have not encountered many problems with this setup until now and the encoders only sink 20mA.
This is the setup of one of the encoders, I only encounter the following problem only if I connect more than 2 encoders in this formation

The Due resets fine when I press the reset button, but when I reconnect USB, the Due crashes and is not able to run any code (tested a blink sketch).
I cannot change any of the circuitry because it is already in multiple PCBs. Does anybody have an idea why the 5v on the 3.3v tolerant pins is causing the reset over usb to fail and how I could fix this in software? It must be fixable in software as the arduino IDE manages to upload sketches while the encoders are connected. I tried to reset over USB by connecting with 1200 baud and setting DTR but that didnt work.
Thanks so much in advance, I hope my question was clear.
edit: I am aware I am doing things wrong here and that that is whats causing the issue. The problem is we soldered 20+ of those PCBs and I cannot simply make modifications, even simple ones. I am looking for ideas on how to hotfix something in software that I messed up in hardware.
edit edit: Honestly kinda disappointed with the hostility on here, am I being downvoted simply because I made mistake with the specification and am trying to find a workaround? I dont see how that makes it a bad question.

Your wondering why something isn't working right, when you know you are connecting 5v to a board that should only ever use 3.3v logic..........?

You're over-stressing the MCU and causing all sorts of horrible things to happen with the power rails. Of course nasty things are going to happen.
The only way to fix it is to change the circuitry.  Something as simple as adding a 1kΩ resistor in series with each of the input connections could be enough to sort it out.

Adding a resistor in series can be done by scraping away some of the soldermask, cutting the trace, and bridging the cut with a SMD resistor.


text:
How long does it take for a servo to change rotation?
I have an Arduino Uno and a Micro Servo 9g A0090 servo.
Given that Servo.read() simply returns the last value written to the servo I guess there is no way to query a servo's actual position.
If I can't query the servo, how do I know that the servo rotated to the position of my last write() call?
Rotating from 0 to 180 will take longer than rotating from 0 to 10. How do people normally handle this scenario? Perhaps I just time how long it takes to go from 0 to 180 and then always call delay() afterward to give the servo time to complete its rotation?

Normal servos don't provide any feedback. Their speed depends on the servo's specs and the load.
You could measure the time it takes to rotate a certain angle and use that to calculate the time, then add some safety margin. But if the load isn't constant, the times will be off.
You could change the position slowly, but that still doesn't guarantee that the servo will do what you told it to.
If you want to know servos's position, you need a servo that outputs it. There are servos that expose the signal from their internal potentiometer.

Adafruit sells them and has a useful guide about them.
You can also modify a normal servo yourself, by attaching a feedback wire to the potentiometer's wiper pin.

I can imagine several ways how to do it:

You can wait some specific time. How long it takes to rotate from 0 to 180. But it'll wait for much longer for small angles than it's necessary.
Better aproach would be to compute delay based on angle (maybe even on servo power supply voltage)
Another way would be measuring servo's power supply current.
You can use some rotary encoder. But some extra gears might be needed to be able to detect position fine enough.
You can "hack" into the servo's electronic and get the position - it's usually voltage divider (potentiometer). But it might introduce some extra interferences and servo might be fuzzy or unstable...

For 9g servo .10 sec for 60 degree rotation.
For mg995 .18 to .19 sec for 60 degree rotation.
For servo 3003 0.19 to 0.20 or 60 degree rotation.
You can check specification for other servos. I gave for common servos above.
Hope this help.