Problems with running multiple ESC I've written a program which allows me to use my Arduino Uno to send a PWM to an Electronic Speed Controller. 5 seconds after startup the ESC is sent a config via PWM to signal the low to high PWM range to be used by the ESC. Then I can type into the Serial Monitor a single digit 0-9 to pick the PWM I want to send to my ESC. (n*2 = pwm)
This works great when running code for one ESC, but adding code for a second ESC causes significant issues (I only have one ESC plugged in). When I send a serial command to specify PWM rate, my ESC only receives the PWM change sometimes. About 2/3 times it ignores the PWM change and keeps spinning at the same rate it was already at.
What's going on here?
Code
WorkingESCSoftware (main file of .eno)
#include <SoftwareServo.h>
#include "TestClass.h"

int val;    // variable to read the value from the analog pin
int stage = 0;

TestClass t, t2;

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

  t = TestClass();
  t.setPin(3);
  t2 = TestClass();
  t2.setPin(5);
}

void loop()
{
  t.loop();
  t2.loop();
}

TestClass.h
class TestClass {
  private:
    SoftwareServo servo;
    bool _initialized = false;

    int PWM_MAX = 180;
    int PWM_HIGH = 170;
    int PWM_MEDIUM = 80;
    int PWM_LOW = 40;
    int PWM_OFF = 25; // has to be between esc config off (stop) and low (slow spin)
  public:
    TestClass();
    void setPin(int);
    void loop();
};

TestClass::TestClass() {
  Serial.println("cycle lipo power to esc");
}

void TestClass::setPin(int pin) {
  this->servo.attach(pin);
}

void TestClass::loop() {
  //  Serial.println("loop");

  // 5 seconds after power, send PWM range to ESC
  if(millis() > 5000 && this->_initialized == false) {
    this->_initialized = true;

    Serial.println("esc setup");
    this->servo.write(PWM_MAX);
    delay(5);
    this->servo.write(PWM_OFF);
    delay(5);
    Serial.println("esc ready");
  }

  char r = Serial.read();
  String inStr = String(r);
  if(r > -1) {
    Serial.print("serial in: ");
    Serial.println(inStr);
  }

  use h, m, l, o, or 0-9 to control PWM of ESC
  if(r <= -1) {
    // void
  } else if(inStr == "h") { // high
    Serial.print("HIGH: ");
    Serial.println(PWM_HIGH);
    this->servo.write(PWM_HIGH); // highest spinning (same as 160?)
  } else if(inStr == "m") { // medium
    Serial.print("MED: ");
    Serial.println(PWM_MEDIUM);
    this->servo.write(PWM_MEDIUM);
  } else if (inStr == "l") { // low
    Serial.print("LOW: ");
    Serial.println(PWM_LOW);
    this->servo.write(PWM_LOW);
  } else if (inStr == "o") {
    Serial.println("OFF");
    this->servo.write(PWM_OFF);
  } else if (inStr.toInt() >= 0 && inStr.toInt() <= 9) {
    int val = inStr.toInt() * 20;
    Serial.println(val);
    this->servo.write(val);
  }

//  SoftwareServo::refresh();
  this->servo.refresh();
}

You have two copies of your program sharing one physical resource, the serial port input to the Arduino.  It is by chance which of the two copies will receive and process the input data.  So this approach will not work dependably.

Semiphoras are often used when sharing hardware among several programs.  However you are not only sharing hardware, but also the data being sent to the Arduino.  And the data will only be sent once.

In this case, you need to handle the data once in code that is separate from the 2 instantiations of the ESP class.  That is, you need to process the received data once and pass that processed data to the appropriate instantiation of the ESP class.


"variable does not name a type Hey guys I'm getting an error that is im pretty sure to do with how i am initializing my variables. It is:
exit status 1
'threshold' does not name a type

Here's my code:

//Global Variables for moving max:

int analogValues[100];
int ir=0;
int maxA0=0;
int threshold = 0;
//Global variables for moving max ^^

//Global Variables for moving average ECG:
const int no_averages = 2;

unsigned long time = 0, peak1 = 0, peak2 = 0;
int binaryrange, bpm, i=0; //not sure what i does tbh
int readings[no_averages]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average which we will display as ECG

void setup() {
// initialize serial communication with computer:
Serial.begin(115200);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < no_averages; thisReading++) {
readings[thisReading] = 0;
}

//set moving max shit to zero
  for (int is = 0; is < 100; is++) {
analogValues[is]=0;
  }
}

void loop() {
  //int maxA0=0; //Whether I intitate the variables here or globally, same error
  //int threshold = 0;
time = millis();

average=0;
readings[readIndex] = analogRead(A0);
readIndex++;
for (int ir=0; ir < no_averages; ir++) {
  average = average + readings[ir];
}
if (readIndex >= no_averages) {    // ...wrap around to the beginning of array if it has hit the end:
readIndex = 0;
}
average = average/no_averages;
if (average>1000) {
  average = 600;
}
Serial.print(average);

analogValues[ir]=average;
ir++;
if (ir>=100) {
  ir=0; } //This is to roll back to the start of the array if it surpasses the 100th array spot
for (int is = 0; is < 100; is++) {
 if (analogValues[is]>analogValues[is-1])
 analogValues[is]=maxA0;
  }
}

//**************************

//This line with error:

threshold=maxA0-40;

//**************************

if (average<threshold){
  binaryrange=0; }
if (average>threshold && binaryrange==0){
  peak1=peak2;
  peak2=time;
  bpm=60000/(peak2-peak1);
  binaryrange=1;
  }
   Serial.print(" ");
  Serial.println(bpm);
//BPM code ^^

delay(8); // delay in between reads for stability
i++;
}

THANKS!

"The line with the error" falls outside of any functions. In C and C++ we write executable code inside functions. You placed your

threshold=maxA0-40;

(and everything that follows) outside of any functions. Hence the error.

Errors like this are typically cased by improper placement of { and } braces. But this is something you have learn to check for yourself. Most C or C++ oriented code editors can usually help you with this. And proper code formatting can help you with this too. What you have now is such a mess, that a simple error is virtually impossible to see.


Can I control relays through an Arduino while using USB joystick? I was curious if i could control maximum of 9-10 relays with an arduino while using USB joystick?
Id also want to connect a camera to see what my robot is doing, so i had few ideas.
1. Try and do it all through arduino and a small HDMI monitor.
2. Have a camera and joystick connected to a laptop, and laptop connected to arduino which controls the relays?

And bare in mind that im not really a programing nerd, id make simple electric connections with homemade joystick, but id like for this project to be more precise and more 'high tech'. Also im not rich so i cant buy alot of arduinos and 'test it out' or 'start from smaller projects'
Tho id love to hear your advices

Afaik USB on an Arduino is not really easy to accomplish. The USB is normally only usable for uploading a sketch and trace (RS232) data. Not to be used as a specific USB device. There are people who upload special firmware to have the Arduino used as USB device but this is not something for a beginner.

A camera with an Arduino is quite impossible, especially if you want to process the data from that camera on a microcontroller. You might take a look at a Raspberry Pi instead, afaik it also has a HDMI output.


the use of the Arduino's EEPROM I want to know the purpose of using the EEPROM because I can't get it,
I mean I know that it can store values for a long time, but I just can't get the goal here

#include<EEPROM.h>
void setup()
{
  Serial.begin(9600);
  EEPROM.write(0,4);
  int s=EEPROM.read(0);
  int f=10;
  Serial.print(s);
  Serial.print(" ");
  Serial.print(10);
}

void loop()  {}

For example, I'm using EEPROM to see the difference if I print a value inside variable s to the serial moniter using EEPROM and a normal value inside the variable f.
But I couldn't find the difference between both because when unplugging the power and turn it on again, both of them are printed.
Hope you got the idea and I hope to see some feedback.
Thank you..

the LED program

then I made this program that will compare the EEPROM value to num.4 and compares the F variable to num.4
known that both F and the EEPROM values are 4.
and then I changed both of the values to 3.
shouldn't the GREEN LED of the EEPROM still on because it has already stored num.4??

#include<EEPROM.h>
void setup()
{
  pinMode(12,OUTPUT);
  pinMode(11,OUTPUT);
}

void loop()
{

  EEPROM.write(0,4);                 //GREEN LED
  int f=4;                           //RED LED

  if(EEPROM.read(0)==4) digitalWrite(12,HIGH);
  if(f==4) digitalWrite(11,HIGH);
}

In short:
Once you shutdown an Arduino, every variables on it, which have been calculated by the sketch, are lost. That is because they are stored in RAM, which is not able to store things without power. That is not the problem of EEPROM: values stored there will be available on reboot, and won't need to be calculated again.

This can prove useful is your device is allowing a user to store presets: so a configuration of the program. If this configuration, which can be for instance variables affecting the program behavior, is stored in RAM, it will be lost on next reboot. On the other hand, a value stored in EEPROM during the first execution (entered by user for instance) will still be available on next reboot, if you took the time to write it (on the first run) and to read it (on the second run). Just like saving and then recalling a preset.

Beware that EEPROM does not like to be written too many times and wear out, so you should keep that to a minimum (values that really need to be restored on reboot, and cannot be calculated at this time).


Can I use a HC-05 and a GPS without a breadboard on a Arduino Uno? I was wondering if I can use a GPS (in my case a U-BLOX) and a hc-05 at the same time connected to a arduino uno without a breadboard? I have tried my GPS on the arduino uno alone and it works very good. Now my question is, can I add a hc-05 on the board directly and put the VCC on the empty 5v?

I put together a schematic of what I had in mind below:

Would this schematic work or would I need a breadboard?

I don't see why not. The breadboard is just something to help you prototype yuproect, in the end, your project should always be on a perfboard or a custom PCB.

Note that some male-female header might get handy.

I'm not sure that the HC05 can handle 5V though. You migh want to check.


ATmega 32A and 2560 R3 register to pin mapping? I've been doing research for the last few hours trying to determine the mapping of physical pins to memory-mapped I/O registers for the Arduino Mega board (which is an ATmega 2560 R3).

My code is on GitHub in a pull request, but hasn't been merged yet because I'm not finished yet.
This is the upstream example I'm working from, which was written for an ATmega 32A.
Here is Arduino's 2560 pin mapping which doesn't tell which registers are mapped to which pins.
Here is avr/iomxx0_1.h which defines the ports with simple numbers that I can't make heads or tails of.
Here is a collection of links relevant to my research.
I broke down and cross-referenced all of the uses of memory-mapped I/O registers in the upstream example.

Some of the registers used include CS11, DDB4, DDRA, DDRB, GICR, INT0, INT1, ISC00, ISC10, MCUCR, PA0, PB5, PB7, PD2, PD3, PIND, PORTA, PORTD, SPCR, SPDR, SPIF, SPSR, TCCR1B, and TCNT1. I can't figure out which pins these are and/or what they do.

Here is a diagram provided by the upstream example:

Unfortunately, I'm not very good at reading these diagrams so I'm doing my best.

How can I determine the mapping of these registers to physical ports on both the ATmega 32A, which is the board the example was originally written for, and the ATmega 2560 R3, which is the board I'm currently working with?

What is ATmega2560 R3? There is ATmega2560 MCU or Arduino Mega R3. do you want the mapping of pins of Arduino Mega or the pins of the ATmega2560 MCU.

The mapping of pins of the ATmega 2560 chip is in the datasheet.

The mapping of the Arduino Mega pins to ATmega2560 pins and registers is in the schema of the board or in the Arduino AVR boards package variants mega folder.

The link "Arduino's 2560 pin mapping" in your question shows the mapping too. Registers are PA, PB,... and every register covers to 8 pins with the 8 bits of the register. For example PB3 is pin 50 of the board.


Connecting Web Server in GoDaddy Hosting I have a domain. It is hosted by GoDaddy. I need to connect that server and receive some data by executing PHP files.
I am not sure about the components.
Tutorials on internet describes how to control esp8266 from web server which is i do not want.
Also i found arduino uno wifi board/wifi shield but in arduino store, it says: this product is 'retired'.
So do you recommend any component for this task or should i go with arduino uno wifi?

I have a domain.

Congratulations.

It is hosted by GoDaddy.

You have my deepest sympathies.

I need to connect that server and receive some data by executing PHP files.
I am not sure about the components.
Tutorials on internet describes how to control esp8266 from web server which is i do not want.

"Controlling" an ESP8266 from a web server is nothing more than making a request to a web server and responding to something the web server sends back.
If you don't want to respond to what is sent back you don't have to. You just have to make the request. That request can contain whatever you want in the way of data and sensor values.

Also i found arduino uno wifi board/wifi shield but in arduino store, it says: this product is 'retired'.

Yes. It's been replaced with the Arduino WiFi Rev 2, which is a more modern AVR MCU coupled with an ESP32 based WiFi interface.
It's pretty wasteful really, since the WiFi interface is considerably more powerful than the AVR that it's connected to.

So do you recommend any component for this task or should i go with arduino uno wifi?

I'd recommend an ESP32 based board. They're cheap, have direct connection to WiFi, very very powerful, plenty of inbuilt peripherals (unlike the ESP8266), and above all have great software support, examples and tutorials.


Why is Arduino Pro Mini not powering this LED? First off, I'm very new to Arduinos and electronics in general, so feel free to explain like I'm 5.

As a bit of background to this question, the project is simply using a Pro Mini to run a servo, with a button to turn it on and off, and an led to indicate when it's on. To make sure I was getting the button right, I built the circuit on a breadboard with just the button and LED. The button was supposed to switch the LED on and off. It did not.

I removed the button from the equation and just tried to power the LED with the Mini. No go.

It's a blue LED, so the resistor (100) was chosen assuming a forward voltage of 3.3V and current of .02A. I've tested the resistor and LED combo with JUST the battery pack, and it lights up bright like it should.

I have a 9V battery running into RAW (I've also tried a 6V pack). I had pin 2 as an output with digitalWrite(HIGH), running into the resistor, then into the LED (+, long end), and then back to a ground pin. I've tried other ground pins on the board to make sure it's not that. I've switched pin 2 to analogWrite(255), still nothing. I have tried connecting it to VCC instead. Nothing.

However, writing HIGH to the onboard LED works fine, so I can see that the sketch is indeed running.

I've verified the LED polarity. I have tried a different Pro Mini. Nothing. It's a Pro Mini 328P according to the stamp on the back, which Google says runs at 5V and 16 MHz.

Please tell me what stupid mistake I am making so I can stop wanting to rip my hair out. Thank you.

This was my mistake. I had attached the Arduino to the breadboard by pushing in the provided pin strips, and then putting the mini on top of those, assuming that since the pin was through the hole and looked to be touching, a connection was made. It wasn't.

Rather than continue to mess around with fiddly connections, I just took the plunge and soldered the entire thing to a circuit board. The LED and the button work perfectly as expected, and now I just need to attach the servo.


Code problem w/ Uno+GPS+GPRS? I've got an Arduino Uno, SIM900 GPRS, and the Adafruit Breakout GPS.

Can this code be optimized?

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <Ubidots_Arduino_GPRS.h>
//Serial Relay - Arduino will patch a
//serial link between the computer and the GPRS Shield
//at 19200 bps 8-N-1
//Computer is connected to Hardware UART
//GPRS Shield is connected to the Software UART
#define APN "myapn"
#define USER ""  // If your apn doesnt have username just put ""
#define PASS ""  // If your apn doesnt have password just put ""
#define TOKEN "ubidotsToken"  // Replace it with your Ubidots token
#define ID "Your_id_here" // Replace it with your Ubidots' variable ID
// You can send 1 to 10 variable at the same time
#define ID1 "idHere" // Replace it with your variable ID
//#define ID2 "" // Replace it with your variable ID
//#define ID3 "Your_id_here" // Replace it with your variable ID

TinyGPSPlus gps; // The TinyGPS++ object for interfacing with the GPS
//Declare indexes, and strings
char latitude[12];
char longitude[12];
float value_1 = 1;
char var[18] = "Lat: ";
char var2[18] = "Long: ";
Ubidots client(TOKEN);
SoftwareSerial ss(2,3);
void setup() {

// the Serial port of Arduino baud rate.
  Serial.begin(9600);

  client.powerUpOrDown();
  client.setApn(APN,USER,PASS);
//.endC is for _client.end() in Ubidots_GPRS.cpp
  client.endC();
  ss.begin(9600);
}

void loop() {

  //handling GPS data parsing
  while (ss.available() > 0) {
    gps.encode(ss.read());}
  //Once a valid location comes up it updates Lat/Long variables
   if (gps.location.isUpdated())
{
    strcpy(var, "Lat: ");
    strcpy(var2,"Long: ");

    dtostrf(gps.location.lat(),10,6,latitude);
    strcat(var, latitude);

    dtostrf(gps.location.lng(),10,6,longitude);
    strcat(var2, longitude);
  //Added ss.flush();
    ss.flush();
    ss.end();
    Serial.flush()
  //Added client.beginC() for _client.begin(9600) is Ubidots_GPRS.cpp
    client.beginC();
    client.add(ID1, value_1, var, var2);
    client.sendAll();
    client.endC();
    ss.begin(9600);
  }
 Serial.println(var);
 Serial.println(var2);
}

From this link, I moved the println from inside .isUpdated() to outside the if statement. I was able to get GPS data sent from the unit to my Ubidots account while driving around town. Afterwards I was able to input the data into Google Maps and the route produced was accurate. Do I need flush()?

It seems you're using the same hardware Serial port for both your PC and the GPS module. This will result in the GPS module receiving everything you send to the PC with Serial.print() and this may be the cause of your problem, as it could confuse the module and either make it send an endless stream of gibberish and/or making isValid() to always be false. You should instead create a SoftwareSerial instance attached to any 2 digital pins (maybe 2 and 3) like this:

SoftwareSerial ss(2, 3);

and in setup():

ss.begin(9600);  // use your module baud rate

Then at the top of loop(), use this instead:

while (ss.available() > 0)
    gps.encode(ss.read());

Get rid of the recursive call of loop() within loop() since it will cause your stack to rapidly overflow.

If you want data to only be sent when the location values are updated based on recent received data (but not necessarily changed, since you may still be at the same location), you should use if (gps.location.isUpdated()) instead.

Your call of dtostrf() is also wrong. The second argument should be the length of the string to be created (including decimal point) and the 3rd argument should be the number of digits after the decimal point. Something like this should be okay:

dtostrf(gps.location.lat(), 10, 6, latitude);

You can also put this at the end of loop() to check if data is actually being received from the module and processed by the library:

if (millis() > 5000 && gps.charsProcessed() < 10)
  Serial.println(F("WARNING: No GPS data.  Check wiring."));
  while (1){ // infinite loop
    if (ss.available())
      Serial.print(ss.read());
  }
}

This site may provide additional details.


Arduino: put string through variable in array I have a problem and I can't fix it.
I'm busy with an java to arduino project.
Java writes a string using writeString();
Arduino reads the serial monitor and put the incoming string into a function.
then I want to put the string into a variable and the variable into a char arr[];
The problem is: When I put the string directly in the arr[]; it works, but when I put first the incoming string in a variable and then the variable in the arr[]; it gives me the next error:

string-parser:44: error: array must be initialized with a brace-enclosed initializer
exit status 1
initializer fails to determine size of 'arr'

this is the code that doesnt work:
input = "2,5>2,6>2,7>4,8";

String splitStringIntoCoordinates(String input){
  char arr[] = input; // Place incoming route in char array
}

This is the code that does work:
String splitStringIntoCoordinates(String input){
  char arr[] = "2,5>2,6>2,7>4,8"; // Place incoming route in char array
}

I hope anyone can help me.
Thanks!

A String isn't a char array. You can't assign one to the other.

You shouldn't be using String, it's too heavyweight, and how you are passing your String object is wrong, it wastes huge amounts of memory making clones.

You should read this.

The only time you should ever consider using a String object is if you are using a third party library that requires a String object - and even then you should consider other methods.

Regardless of that, you need to copy the content of your string, not the string itself.  This code should work, but it doesn't address the underlying String issues:

String splitStringIntoCoordinates(String &input){
  char arr[input.length() + 1]; // Create a char array big enough including the terminating NULL
  strcpy(arr, input.c_str()); // Place incoming route in char array
  // ... etc ...
  // return a string
}

If you just want to reference the String as a C string you can just use the function input.c_str() to get the internal char * array pointer.


ESP8266 not working with MPU 6050 over wire library and I2C I'm trying to use this version of ESP8266 to access MPU 6050. However, it's not working.

https://www.amazon.com/gp/product/B07HF44GBT/ref=ppx_yo_dt_b_asin_title_o07_s00?ie=UTF8&psc=1 i.e. NodeMCU CP2102 ESP-12E

The code worked with nano very fine. However, when I tried to scan the I2C device, it's said I2C device not found.

I have tried

  Wire.begin(D2, D1);

and

  Wire.begin(4, 5);

i.e. to change the pin to GIOP 4 5 in case if the default was not working.
I have also tried to put a large capacitor between the power lines, still not working.

Why ESP8266 does not work with MPU 6050?(Serial and wire together)

Updates:
Sometimes it does say device found, but after two updates, it turned to be not found again.

Updates 2:
I watched the video and did what G6EJD suggested, i.e. restarted the IDE and everything. Now it's reading data. However, the data reading was somehow incorrect by a large factor.
For example, at flat the device is reading

42.63/-38.37/7.82

for angle x,angle y,and angular speed z with complementary filter applied and steady at flat surface. It worked for nano but not for ESP 8266.

Also, I tried to adjust the circuit like the spectrum dandavis suggested. I tried resistor range from 4.7 k to 10, even directly connect to the power source. The attempts also included 100 $\mu$F capacitor and power board to stabilize the noise. Both pull up and pull down has been attempted as well as changing boards. However, none of those were working and the issue persisted. The pull up resistor did not seem to be response to what the device was reading.

Update 3:
The power consumption has been ruled out and a pair of 100k resistor was also attempted. Not working.

I've been struggling with getting anything with the MPU6050's to work with either a D1 Mini or an older NodeMCU v1. I'm using D1/D2.
I've used the i2cdevlib MPU6050 library as well as the Electronic Cats' version.
I've used an assortment of sketches and even tried code which uses just Wire (no MPU6050 specific libs).

The best I've been able to get is the Electronic Cats MPU6050 library, without DMP, where at least it thinks the MPU6050 has been connected to, but it just puts out 0's as raw values.
The second "best", maybe, was some code that just used plain Wire, but except for Wire.endTransmission() returning success (and I had to slow loop() down for that), its numbers are gibberish (either 0's, or Z will just increment.  Nothing is affected by the movement of the board itself).

The DMP versions always fail to initialize the DMP.
I've tried 8.2k and 4.1k pullups on D1 and D2.
It works fine on an atmega32u4-based Pro Micro 16.


What does []() argument in function mean? I am working in ESP8266 AsyncWebserver library and have been using this [](parameter) as an argument to some functions as shown below but does not really know what it means. Being a neophyte I am curious to know what does this convention means, its functionalities and how to use it. Hopefully experts here would help me with this.

server.on("/page",HTTP_GET,[](AsyncWebServerRequest * request){
    some code....;
    request->getParam("Param1")->value();
});

That is called a lambda expression and it's a way of including the content of a function as a parameter anonymously instead of writing an actual function and using the name of it.

It's shorthand for:

void myCallback(AsyncWebServerRequest * request) {
    // some code....;
    request->getParam("Param1")->value();
}

// ...

server.on("/page", HTTP_GET, myCallback);

It does have a few benefits over traditional functions at the expense of readability, such as the ability to "capture" local variables from the surrounding scope.


What happens when code is uploaded using the bootloader? When I upload a new sketch to my Arduino Uno using the Optiboot bootloader, what really happens?

What is sent to the Arduino?
How does it respond?
What does "not in sync mean"?
What is "in sync" anyway?

Note: This is intended as a "reference question".

When you reset a Uno running the Optiboot loader, the bootloader first flashes pin 13 three times.

Top line (gray) is sent to the Arduino, middle line (orange) is sent from the Arduino.

While that is happening, the program avrdude running on your computer is sending a query to the device:

STK_GET_SYNC / CRC_EOP  (0x30/0x20)

The Arduino doesn't notice the first "get sync" because it is busy flashing pin 13. Once it is done it notices the "get sync" (it would be buffered by the serial hardware) and replies:

STK_INSYNC / STK_OK (0x14/0x10)

It looks like avrdude got a bit impatient, and timed out, because it tries again with the "get sync" query. This time Optiboot responds immediately.

The rest of the uploading is described in the next image. Example produced uploading the stock "Blink" program.

(Click on the image above for a larger version)

The steps are:

Query: Get Sync? Reply: In Sync.
Query: Get parameter? (major version) Reply: version 4.
Query: Get parameter? (minor version) Reply: version 4.
Set device parameters. The following device parameters are sent to the chip:

0x42  // STK_SET_DEVICE
0x86  // device code
0x00  // revision
0x00  // progtype: “0” – Both Parallel/High-voltage and Serial mode
0x01  // parmode: “1” – Full parallel interface
0x01  // polling: “1” – Polling may be used
0x01  // selftimed: “1” – Self timed
0x01  // lockbytes: Number of Lock bytes.
0x03  // fusebytes: Number of Fuse bytes
0xFF  // flashpollval1
0xFF  // flashpollval2
0xFF  // eeprompollval1
0xFF  // eeprompollval2
0x00  // pagesizehigh
0x80  // pagesizelow
0x04  // eepromsizehigh
0x00  // eepromsizelow
0x00  // flashsize4
0x00  // flashsize3
0x80  // flashsize2
0x00  // flashsize1
0x20  // Sync_CRC_EOP

Optiboot ignores all those and replies with In Sync/OK. :)
Set extended device parameters:

0x45  // STK_SET_DEVICE_EXT
0x05  // commandsize: how many bytes follow
0x04  // eeprompagesize: EEPROM page size in bytes.
0xD7  // signalpagel:
0xC2  // signalbs2:
0x00  // ResetDisable: Defines whether a part has RSTDSBL Fuse
0x20  // Sync_CRC_EOP

Optiboot ignores all those as well and replies with In Sync/OK.
Enter program mode. Reply: In Sync/OK.
Read signature. Optiboot replies with 0x1E 0x95 0x0F without actually reading the signature.
Write fuses (four times). Optiboot does not write the fuse but just replies In Sync/OK.
Load address (initially 0x0000). The address is in words (ie. a word is two bytes). This sets the address for where the next page of data will be written.
Program page (up to 128 bytes are sent). Optiboot replies "In Sync" immediately. Then there is a pause of about 4 ms while it actually programs the page. Then it replies "OK".
Load address (now 0x0040). This is address 64 in decimal, ie. 128 bytes from the start of program memory.
Another page is written. This sequence continues until all the pages are written.
Load address (back to 0x0000). This is for verifying the write.
Read page (up to 128 bytes are read). This is for verifying. Note that even if the verify fails, the bad data has already been written to the chip.
Leave programming mode.

What does "not in sync" mean?

As you can see from the above, every step through the programming sequence the Arduino is expected to reply with "In Sync" (0x14), possibly followed by some data, followed by "OK" (0x10).

If it is "not in sync" that means that avrdude did not get the "in sync" response. Possible reasons could be:

Wrong baud rate used
Wrong serial port selected in IDE
Wrong board type selected in IDE
No bootloader installed
Wrong bootloader installed
Board not configured to use the bootloader (in the fuses)
Some device plugged into pins D0 and D1 on the Arduino, interfering with serial commications
The USB interface chip (ATmega16U2) not working properly
Wrong clock for the board
Wrong fuse settings on the Atmega328P (eg. "divide clock by 8")
Board/chip damaged
Faulty USB cable (some USB cables provide power only, and are not for data, eg. cheap cables for USB fans)

What is "in sync"?

As mentioned above, the response "In sync" means that the Arduino (bootloader) is synchronised with the uploading program.

What protocol is being used?

The protocol is the STK500 protocol as documented by Atmel. See the references below.

References

Optiboot source code - GitHub
AVR061: STK500 Communication Protocol
AVR068: STK500 Communication Protocol version 2
Have I bricked my Arduino Uno? Problems with uploading to board
AVR Downloader/UploaDEr - avrdude

Note: STK500 Version 2 is not used in Optiboot, but it is included for information in case you are using boards like the Mega2560.

STK500 constants

/* STK500 constants list, from AVRDUDE */
#define STK_OK              0x10
#define STK_FAILED          0x11  // Not used
#define STK_UNKNOWN         0x12  // Not used
#define STK_NODEVICE        0x13  // Not used
#define STK_INSYNC          0x14  // ' '
#define STK_NOSYNC          0x15  // Not used
#define ADC_CHANNEL_ERROR   0x16  // Not used
#define ADC_MEASURE_OK      0x17  // Not used
#define PWM_CHANNEL_ERROR   0x18  // Not used
#define PWM_ADJUST_OK       0x19  // Not used
#define CRC_EOP             0x20  // 'SPACE'
#define STK_GET_SYNC        0x30  // '0'
#define STK_GET_SIGN_ON     0x31  // '1'
#define STK_SET_PARAMETER   0x40  // '@'
#define STK_GET_PARAMETER   0x41  // 'A'
#define STK_SET_DEVICE      0x42  // 'B'
#define STK_SET_DEVICE_EXT  0x45  // 'E'
#define STK_ENTER_PROGMODE  0x50  // 'P'
#define STK_LEAVE_PROGMODE  0x51  // 'Q'
#define STK_CHIP_ERASE      0x52  // 'R'
#define STK_CHECK_AUTOINC   0x53  // 'S'
#define STK_LOAD_ADDRESS    0x55  // 'U'
#define STK_UNIVERSAL       0x56  // 'V'
#define STK_PROG_FLASH      0x60  // '`'
#define STK_PROG_DATA       0x61  // 'a'
#define STK_PROG_FUSE       0x62  // 'b'
#define STK_PROG_LOCK       0x63  // 'c'
#define STK_PROG_PAGE       0x64  // 'd'
#define STK_PROG_FUSE_EXT   0x65  // 'e'
#define STK_READ_FLASH      0x70  // 'p'
#define STK_READ_DATA       0x71  // 'q'
#define STK_READ_FUSE       0x72  // 'r'
#define STK_READ_LOCK       0x73  // 's'
#define STK_READ_PAGE       0x74  // 't'
#define STK_READ_SIGN       0x75  // 'u'
#define STK_READ_OSCCAL     0x76  // 'v'
#define STK_READ_FUSE_EXT   0x77  // 'w'
#define STK_READ_OSCCAL_EXT 0x78  // 'x'


Will the arduino power autoselection logic short the regulated 5V and the USB 5V? From the reference design of the Arduino UNO r3, I find that USBVCC will be connected to +5V via mosfet T1 if Vin is below 6.6V.
Doesn't this short the two sources if Vin is just below 6.6V?
The datasheet for regulator U1 (NCP1117) mentions input range as low as 6.5V for the 5V version.

This question came to mind when researching if I can simultaneously power the arduino with USB and the 5V-pin. There are many warnings not to do so, and some say its ok anyway. I realise that this will short the USB 5V with my external 5V if Vin/PWRIN is not connected or less than 6.6V/~7.3V, but how bad is that considering that this may happen anyway by design (if the theory above is correct)?

If you connect a power supply directly to 5V pin on gpio it bypasses voltage regulator hence your board may be damaged if the power supply generates  spikes. But you can power it using 5V supply directly to 5V pin provided you are using a good quality power supply. If you are supplying the power via Vin or power jack there is additional voltage regulator in path giving extra security. Thus you need more 6.5v so as the output of the regulator is 5v. If you supply 5v to Vin the output is nearly 4v thus the board doesn't get enough power.


How detect I2C errors with requestFrom() I am going to use MCP23017 chips, and some of them will be cabled with a 1 meter max unshielded cable. I am expecting that certain transmissions may toss errors. So I want to tackle this problems by using the built in error detection of I2C, polling the inputs frequently (every 20ms or so) and by debouncing the received data in code by comparing the previous state to the current state of every input pin.
If you write bytes to an I2C slave with the Wire library. You can use the return value of Wire.endTransmission(); to test if the slave has acknowledged the message.
How does this work when you are requesting bytes using Wire.requestFrom( address, 3 ); for example. This function does return the amount of received bytes. Can we check this value with the value of the amount of bytes we requested?
I have read the TI document over how I2C works

The master will continue sending out the clockpulses, but will release the SDA line, so that the slave can transmit data. At the end of every byte of data, the master will send an ACK to the slave, letting the slave know that it is ready for more data. Once the master has received the number of bytes it is expecting, it will send a NACK, signaling to the slave to halt communications and release the bus. The master will follow this up with a STOP condition

So the master either ACKs or NACKs a read-in byte. Does the Wire library automatically make several attempts with reading? Oris there something in the Wire library which we can use to detect a failed read operation?
Is it perhaps so that the requestFrom() function may return a different amount of bytes than you requested with which would indicate that atleast 1 read operation failed?
So could I attempt something like
doItAllAgain:

for(int i = 0 ; i < 5 ; i ++ )
{
    Wire.beginTransmission( address ) ;
    Wire.write( register ) ;
    if( !Wire.endTransmission() ) break ; // if no error, break out of for loop
    Serial.println(F("write operation failed");
}

Serial.println(F("write operation succes");

byte requestedBytes = 3 ;
byte returnedBytes = Wire.requestFrom( address, requestedBytes ) ;

if( requestedBytes != returnedBytes )
{
    Serial.println(F("read operation failed");
    goto doItAllAgain ;
}
else
{
    Serial.println(F("read operation also succes");
    byte byte1 = Wire.read() ;
    byte byte2 = Wire.read() ;
    byte byte3 = Wire.read() ;
}

The Wire library does not give you any possibility to get error states, when requesting bytes from a slave. Basically you are stuck with the number of bytes being read.
Though you can read some information from that. If the number of bytes is zero, the slave didn't answer (either because its not there, or because it cannot send any byte currently). This equals a NACK by the slave after the address byte.
Other than that the I2C protocol doesn't give any more information. On requesting the slave is sending data and the master is acknowledging it. That means, that the slave cannot generate a NACK in this process. In fact that also means, that the returned number of bytes can only be zero (on NACK on address) or equal to the number of requested bytes, since after the address ACK from the slave the master will continue to generate clock pulses, until it has read all bytes, that it wanted. If the slave doesn't have any more data to send before that, it cannot stop the transmission. It would just stop driving the data line, resulting in all high data bytes (0xFF).
Also I doubt, that it would be really useful in your case. I2C is made for small distances, mostly on the same PCB. It can be used for longer distances, but your mileage may vary. If your setup really can corrupt the communication on the I2C lines, your biggest problem will be a stuck bus. The I2C protocol is generally not prepared for noisy environments and it incorporates states, where the devices on the bus can wait infinitely. This is also reflected in the Wire library. That means, that big noise on the lines will often lead to the bus being stuck in the middle of a transaction, needing you to reset the devices (not only the slaves, but also the master) to get the bus free again. I would go so far to say, that is it more likely to get the bus stuck, than to get corrupted data. So any information about errors is not really helping you here, since you won't get out of requestFrom() in the first place. Your code can very well get stuck there.
I suggest, that you test your setup thoroughly with the wanted run times. If the bus gets stuck too often for you, then you should make your setup more robust (shielded cables, or using an extra MCU with the I2C slave and using a more robust communication interface between main MCU and extra MCU).


How to read serial data without any blocking using ESP8266 I'am deconding one electronic device serial protocol and using ESP8266 for this task. Device is sending 202 byte data constantly and I figured out begining and the end.

Whole packet looks like:

71 c8 01 10 56 55 62 49 00 05 00 00 00 00 00 00 00 00 00 00 19 15 11 55 16 5e 55 05 09 00 00 00 00 00 00 00 00 00 80 8f 80 8a b2 71 71 97 99 00 00 00 00 00 00 00 00 00 00 00 80 85 15 8a 85 85 d0 7b 78 1f 7e 1f 1f 79 79 8d 8d 9e 96 71 8f b7 a3 7b 8f 8e 85 80 8f 8a 94 9e 8a 8a 94 9e 82 90 8b 05 65 78 c1 0b 00 00 00 00 00 00 00 00 55 56 55 21 53 15 5a 05 12 12 19 00 00 00 00 00 00 00 00 e2 ce 0d 71 81 72 ce 0c 92 81 b0 00 aa 7c ab b0 32 32 9c b6 32 32 32 80 b7 af cd 9a ac 79 80 77 80 ff 91 01 29 59 00 00 3b 0b 1c 51 59 01 36 79 01 01 c3 02 00 dd 02 00 05 00 00 01 00 00 06 01 01 01 01 01 0a 14 00 00 00 77

Here start "header" is 0x71 and 0xc8   and the last 202 byte is a Checksum value of hole 201 bytes.

Goal is to get valid 202 byte data by checking if start contains 0x71 and 0xc8

My readserial looks like, how it to improve in best way?

void readSerial()
{
  if (Serial.available() > 0) {
    data_length = Serial.readBytes(data, 202);
       while (Serial.available()) {
      delay(2);
      Serial.read();
    }
  }
  else data_length = 0;
}

First, I think the protocol is slightly different probably. The first byte is 71. The next byte seems to be the number of bytes that follow (C8 hex is 200). The last byte is the checksum.

So you need to check for 71, when that is received you can read the next byte (number of bytes), the data, and the checksum.

So the code should be something like:

void readSerial()
{
   if (Serial.available() > 0)
   {
      uint8_t readByte = Serial.read(); // uint8_t = 8 bit unsigned integer
      if (readByte == 71)
      {
         // Read message
         data_length = Serial.read();
         data_length = Serial.readBytes(data, data_length);
         checksum = Serial.read();
         // Check checksum
      }
      else
      {
         data_length = 0;
      }
   }
}

(note: code is untested)

About blocking prevention, you will have to read them one by one and doing other tasks meanwhile.

Update

Assuming reading starts while sender is already sending possibly, and assuming a message always starts with 71 C8.

Create an enumeration that shows how many 'start bytes' have passed (71 C8 are start bytes).

enum EStartByte
{
   WaitForMessage,
   FirstStartBytePassed,
   ReadMessage
};

enum EStartByte startByte = WaitForMessage;

void readSerial()
{
   while (Serial.available())
   {
      switch (startByte)
      {
      case WaitForMessage:
          // Expect first start byte
          if (Serial.readByte() == 0x71)
          {
               startByte = FirstStartBytePassed;
          }
          break;

      case FirstStartBytePassed:
          // Expect second start byte
          if (Serial.readByte() == 0xC8)
          {
               startByte = ReadMessage; // Start reading
          }
          else
          {
               startByte = WaitForMessage;
          }
          break;

      case ReadMessage:
          // Read data
          data_length = Serial.readBytes(data, 200);
          checksum = Serial.read();
          // Check checksum

          startByte = WaitForMessage; // Start over
          break;
      }
   }
}


A/C doesn't detect IR codes sent from Arduino I have an IR receiver and an IR LED I got from a kit (I don't have the datasheets for them).
I uploaded an Arduino sketch to record my A/Cs IR codes. Those were NEC encoded 32bit integers.
After recording the codes, I tried retransmitting them. The A/C unit failed to detect the signals.
Troubleshooting a bit, I sent the code from the Arduino the receiver sketch from the previous step - it received them successfully.

All the above steps used the IRRemote Arduino library

The question is, what could explain this behavior?
A few possibilities I had in mind:

IR frequency. Could it be that the detection circuit worked with the default settings but transmitting wouldn't?
IR wavelength. Any chance the A/C side doesn't detect my IR pulses at all?
Decoding/Encoding of the NEC protocol in IRRemote. If there is no standard for the NEC protocol, the Arduino and A/C implementation might be a little different.

Hi i have done the same thing. I was using this to get the AC codes for the GREE AC. I find it with two weeks struggle and a forum called AnalysIR. If you find any issue in this code below or method let me know.

AC codes are usually long and those doesn't come right with the code which you used above so i am giving you the sample code to run in the Arduino sketch so that you can test.

   #define LEDPIN 13
  //you may increase this value on Arduinos with greater than 2k SRAM
  #define maxLen 800

       volatile  unsigned int irBuffer[maxLen];
       //stores timings - volatile because changed by ISR
       volatile unsigned int x = 0;
       //Pointer thru irBuffer - volatile because changed by ISR

     void setup() {
     Serial.begin(115200); //change BAUD rate as required
     attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);
    //set up ISR for receiving IR signal
     }

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

   Serial.println(F("Press the button on the remote now - once only"));
    delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
digitalWrite(LEDPIN, HIGH);//visual indicator that signal received
Serial.println();
Serial.print(F("Raw: (")); //dump raw header format - for library
Serial.print((x - 1));
Serial.print(F(") "));
detachInterrupt(0);//stop interrupts & capture until finshed here

for (int i = 1; i < x; i++) { //now dump the times
  if (!(i & 0x1)) Serial.print(F("-"));
  Serial.print(irBuffer[i] - irBuffer[i - 1]);
  Serial.print(F(", "));
                     }

   x = 0;
   Serial.println();
   Serial.println();
   digitalWrite(LEDPIN, LOW);//end of visual indicator, for this time
   attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for            receiving IR signal
        }

      }

  void rxIR_Interrupt_Handler() {
    if (x > maxLen) return; //ignore if irBuffer is already full
     irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

    }

Once this is done you will get the right code to send it to the AC.

A little Tricky part

once you will receive the codes of raw values you will have to little modify it for example i got the raw values and i converted it into the array.

What i received for example
Raw (16): -27750, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628

To Convert the above raw values into array remove first value which is -27750 and put 3800 instead of that. Below is the array sample.**

unsigned int data[] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628,
};

Now sending these values to the IR transmitter use this code below.

      #include<IRremote.h>
       IRsend irsend;
       int KHz = 38;                    // default frequency

      unsigned int data[] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628,
        };

    void setup()
   {
     Serial.begin(9600);
     irsend.enableIROut(38);
   }

    void loop()
   {

    for (int i=0; i<1 ; i++){
    irsend.sendRaw(data, sizeof(data) / sizeof(int),38 );
    delay(40);
          }

 }


Arduino Nano For Home Automation My question is about the arduino Nano or Micro and the smallest and cheapest way to control a bigger power source. I would wire it with a socket so that I could send a command from the board and a light would turn on for example.

A relay is a common way to allow a smaller power source to safely control a larger one. A relay is like a switch.

Here's some reference material about using a relay with a microcontroller. You shouldn't have much trouble finding more material now that you know what you're looking for.


Problem with 16x2 LCD using Arduino I've connected the circuit as shown in
https://www.arduino.cc/en/Tutorial/HelloWorld?from=Tutorial.LiquidCrystal
and I ran the program, but I can't fix this problem:

the LCD seems not to respond correctly: the first row is black and for what concerns the elements of the second, they all have three top lines of pixel high and the others low..

I checked over and over if I made some mistake connecting wires but I haven't found any error..

Is the LCD broken according to you? How can I fix?

Here the photos of the circuit:
https://drive.google.com/open?id=0B2h2zzEgtaqydElrRDVUNGVuWDA

I looked the images you have on Google Drive. On the image called IMG_20170822_233722.jpg, I see you are using a 50k ohm potentiometer to control the display contrast. Normally you would use a 10k ohm potentiometer. Using the 50k will make the adjustment very sensitive and hard to adjust. If you are careful and adjust it slowly, it might work for you.

The other image, IMG_20170822_234242.jpg, clearly shows "poor solder joint" connections on the display. D4 - D6 (especially D5 to D6) look like they could be "shorted" together. I think you could fix them by using Desoldering braid or if you don't have any, you could heat up each connection with your soldering iron then quickly "flick" the display to remove the solder. After you have removed the excess solder from each connection, I strongly recommend applying soldering paste to the connections next. The soldering paste really helps the solder to flow into the connection. Now try re-soldering each connection. I'm not sure what kind of solder or iron you are using but I can tell you what works for me. 25 watt pencil tip soldering iron with 22 gauge / 0.71mm rosin core solder.

I can't tell for sure from the pictures if any of the display pins are shorted together and I don't know if shorting them together will damage the display, Arduino or both.


Unable to use DHT11 with NodeMCU(esp8266) I am trying to use a NodeMCU like an arduino,trying to read Temperature and Humidity using a DHT11,but when ever I check the serial monitor the it outputs : nan, Can anyone help me find the problem.(The data pin is D4 on NodeMCU)

    #include "DHT.h"

DHT dht2(2,DHT11);

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

    }

void loop()
{

    Serial.println("Temperature: ");
    Serial.println((dht2.readTemperature( )));
    Serial.println("Humidity");
    Serial.println((dht2.readHumidity( )));
    delay(5000);

}

The esp8266 boot configuration pins 0, 2, 15 require a pull-up/pull-down  to ensure the required state at boot. The board (NodeMCU in this case) has pull-up resistor on io0 and io2 and a pull-down resistor on pin 15. The MCU pins io0, io2 and io16 are the NodeMCU pin D3, D4 and D8. You can use this pins in the sketch, but only to attach devices which are not in conflict with the required boot state and are not disturbed by the pull-up/pull-down.

NodeMCU and "Wemos D1 R2 and Mini" esp8266 pins and io overview

Serial

RX io1 RX0

TX io3 TX0

boot config pins with pullup or pulldown on board

D3 io0 PULLUP (LOW for boot to flashing mode)

D4 io2 TX1 PULLUP (Serial1 TX. no RX for Serial1)

D8 io15 PULLDOWN (SS pin if esp8266 is SPI slave)

untroubled GPIOs with optional function for I2C or SPI bus:

D1 io5 default pin for I2C SCL

D2 io4 default pin for I2C SCA

D5 io14 SPI CLK

D6 io12 SPI MISO

D7 io13 SPI MOSI

RTC pin for timed deep sleep wake-up (if connected to reset pin)

D0 io16 - optional internal pulldown, internal pullup not available

not useable: Sx pins io 6 to io 11 connect QIO SPI flash memory (in DIO flash mode the 2 QIO pins can be used as gpio) (in a very special setup the SPI bus can be used with other SPI device)

note: most digital IO start as INPUT_PULLUP


Unexpected behaviour of blinking LED code I'm new to Arduino so this may be a really silly doubt but I'm not finding an explanation for it anywhere online. I first uploaded this code (to blink 5 LEDs) on my Arduino Uno :

 void setup(){
 pinMode(12, OUTPUT);
 pinMode(11, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(9, OUTPUT);
 pinMode(8, OUTPUT);
}

void loop(){
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
delay(1000);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
delay(1000);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(1000);
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(1000);
digitalWrite(8, HIGH);
delay(1000);
digitalWrite(8, LOW);
delay(1000);
}

The 5 LEDs glowed brightly. But when I uploaded the following code (using an if statement to reduce the size of the previous one), the LEDs glowed dimly.

int LEDpin = 13;
void setup(){
pinMode(LEDpin, OUTPUT);
}

void loop(){
digitalWrite(LEDpin, HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
delay(1000);
if(LEDpin >= 8){
LEDpin--;
} else {
  LEDpin = 8;
  }
}

Also, when I just typed the if statement without the else part, nothing happened after the LED at pin 8 had glowed on and off. Can someone please tell me why the LEDs glowed dimly in the second one and why nothing glowed after LED 8 when I skipped the else part?

As Abhishek mentioned in his answer is correct, but the better way is to use for loops while dealing with many led's.

Let's say you have led's connected from pin 2 to 8.

int pin = 2;
void setup()
{
   for (Pin = 2; Pin < 8; Pin++)
   {
     pinMode(Pin, OUTPUT);
   }
}
void loop()
{
   for (int Pin = 2; Pin < 8; Pin++)
   {
     digitalWrite(Pin, HIGH);
     delay(1000);
     digitalWrite(Pin, LOW);
     delay(1000);
    }
}


Sending Analog Input Data from Serial Port to Google Sheets So I'm trying to make use of my Arduino Uno while I purchase the components for my next project.

I've made use of the Digital Hourglass project from the Starter Kit to make sure I get up and move around every 20 minutes while I'm at home. A temperature sensor was included in the Starter Kit as well, so I figured I might as well make use of it since I have extra I/O pins.

I wrote the code for in the Arduino IDE to display the temperature and the current time. I'm using: #include (Time.h) to also show the current time. I have two questions.

End Goal:

A Google spreadsheet (Cloud) that I can access anywhere that can show me the temperature of my apartment throughout the day. I can track how the trend changes over time through the day, week, or month.

What is the best way to output the current time; as seconds since 1970 (Unix time) or date and time format? I guess it's a preference.
How do I output the data from the Arduino serial port directly to Google Sheets? That may be difficult, so the other option is to energize the Arduino in the morning and remove power at the end of the day, output the Serial port to a .txt file, and then import into Google sheets. How do I do this?

Use Google's time stamp format: MM-dd-yyyy hh:mm:ss, see Google Sheets API v4 - Date and Number Formats.
There are a few ways. For example:

A PC connected to the Internet with software on it that listens for data form the Arduino. It would get the Arduino data over serial then send that via the Internet to Google.
A Wi-Fi, or network, shield connected to the Internet. You could then use Google's API to send the data directly from the Arduino, see Google Sheets API v4 - Writing.
Or - as you mentioned - physically get the SD card and manually upload.


SIM800L - AT Commands not doing anything on Arduino Serial Monitor I am trying to send AT commands to SIM800L through Arduino's Serial Monitor. However when I type any command in the serial monitor nothing happens. I'm using an Arduino MEGA 2560 and the TX/RX of the SIM800L is connected to 9 and 10 respectively. Here is the code:

#include <SoftwareSerial.h>

SoftwareSerial GPRS(9, 10);
boolean state, lastState;

void setup()
{
  pinMode(2, INPUT_PULLUP);
  state = digitalRead(2);
  lastState = state;

  GPRS.begin(9600);
  Serial.begin(9600);

  GPRS.println("AT+CMGF=1");

  delay(1000);
}

void loop()
{
  while(GPRS.available()) {
    Serial.write(GPRS.read());
  }

  lastState = state;
  state = digitalRead(2);

  if ( state != lastState ) {
    sendSMS();
  }

  delay(500);
}

void sendSMS() {
  Serial.print("Switch was turned ");
  Serial.println(state ? "on" : "off");

  GPRS.println("AT+CMGS=\"+64XXXXXXXXX\"");

  delay(500);

  GPRS.print("Switch was turned ");
  GPRS.println(state ? "on" : "off");
  GPRS.write( 0x1a ); // ctrl+Z character

  delay(500);
}

Any help would be much appreciated!

EDIT2: I forgot to mention but I am able to send, receive, and call from the GSM Module (with a different code). However I am not able to read the the received messages, since I only get a +CMT "SM",  message and I can't exactly use AT+CMGR or CMGL commands because the serial monitor does nothing with them. here's the code for that:

#include <SoftwareSerial.h>
SoftwareSerial sim(9,10);
int _timeout;
String _buffer;
String number = "+639XXXXXXXXX"; //-> change with your number
void setup() {
  delay(1000); //delay for 7 seconds to make sure the modules get the signal
  Serial.begin(9600);
  _buffer.reserve(50);
  Serial.println("Lets go!");
  sim.begin(9600);
  delay(1000);
  Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
}
void loop() {
  if (Serial.available() > 0)
    switch (Serial.read())
    {
      case 's':
        SendMessage();
        break;
      case 'r':
        RecieveMessage();
        break;
      case 'c':
        callNumber();
        break;
    }
  if (sim.available() > 0)
    Serial.write(sim.read());
}
void SendMessage()
{
  Serial.println ("Sending Message");
  sim.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  Serial.println ("Set SMS Number");
  sim.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "Wala kang jowa!";
  sim.println(SMS);
  delay(100);
  sim.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}
void RecieveMessage()
{
  Serial.println ("SIM800L Read an SMS");
  delay (1000);
  sim.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
  Serial.write ("Unread Message done");
}
String _readSerial() {
  _timeout = 0;
  while  (!sim.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (sim.available()) {
    return sim.readString();
  }
}
void callNumber() {
  sim.print (F("ATD"));
  sim.print (number);
  sim.print (F(";\r\n"));
  _buffer = _readSerial();
  Serial.println(_buffer);
}

Do not use SoftwareSerial on a Mega2560 unless you absolutely know what you are doing.

SoftwareSerial does not work on many of the pins of the Mega2560, and since there are other hardware serial ports available there is seldom any reason to resort to using SoftwareSerial anyway.

Connect your SIM800L to the TX1/RX1 pins of the Mega2560 then communicate using the pre-defined Serial1 object.


error: ‘sleep’ was not declared in this scope I am trying to use the sleep function in lieu of delay(), but when I include sleep(), I get Sweep.cpp:60:10: error: ‘sleep’ was not declared in this scope

I read some place, about #include <avr/sleep.h> but that is a fail.

#include <avr/sleep.h>
void setup() {
}

void loop() {
  digitalWrite(13, HIGH);   // set the LED on
  sleep(1);              // wait for a second
  digitalWrite(13, LOW);    // set the LED off
  sleep(1000);              // wait for a second
}

I was able to locate sleep.h:

$ locate sleep.h | grep avr
/usr/lib/avr/include/avr/sleep.h

So then I started reading avr/sleep.h, and it seems like I'm doing it right, according to the examples. So, why might this be failing?

"sleep()" is not a function on arduino. The sleep.h file contains functions for the hardware sleep functionality used to reduce power consumption when processing isn't necessary. "delay()" is the right thing to use.

AVR only has one thread, and so there is no meaning to pausing execution by deferring to another thread. Hardware interrupts will always interrupt the current code no matter what it is doing, they are not equivalent to threads (although they can introduce similar bugs).

If you want to wait and still do other calculations you will need to write code that can wait for a time without blocking. This can be done many ways, one way being to use the arduino library function "millis()" to repeatedly check if it is time to do a certain action, and doing something else for a while if not.

Also, vanilla arduino should be using its own packaged avr lib, for example:

arduino/hardware/tools/avr/avr/include/avr/sleep.h

instead of the one located in your usr/lib directory.


Control DC Motor with Arduino Uno WiFi Rev2 Html Slider Code I would like to control my dc motor using the Arduino Uno WiFi Rev2 using an html range slider. Now I can control the motors speed and direction using push buttons just fine. My code is posted below of what I've done so far.

client.println("");
client.println("<input type=\"range\" class=\"class-name\" orient=\"vertical\" id=\"range\" min=\"0\" max=\"255\" step=\"0\" onchange=\"motor1(this.value)\" value=\"0\">");

This code below is the current button code. I need the below code to be used by the slider code above:

if (currentLine.endsWith("GET /MONFWD")) {
digitalWrite(MOTOR_A_ONE, HIGH);  // Establishes forward direction of Channel A
digitalWrite(MOTOR_A_TWO, HIGH);  // ENGAGE BRAKE
delay(1000);                      // DELAY BEFORE RELEASING BRAKE
digitalWrite(MOTOR_A_TWO, LOW);   // Disengage the Brake for Channel A
analogWrite(MOTOR_A_ENGAGE, 255); // Spins the motor forward on Channel A at full speed

Here's an example of slider that changes a Servo speed,
In html page code you have to add this:

  <input type="range" min="0" max="1023" value="512" class="slider" id="myRange">

Value:

In arduino you have to define handler like this:

void handle_pwm() {
 String  pwm_val = server.arg("PWMval"); // reading from slider on html pagae

 Serial.print("slider val: ");
 Serial.println(pwm_val);
int pwm_value = map(pwm_val.toInt(), 0, 1023, 0, 180);
Servo.write(pwm_value);

server.send(200,"text/plane","0"); // handling the webpage update

}

And define servo and handler in Setup() section:

void setup(void){
....
Servo.attach(MotorPin,1000,2000);
server.on("/setPWM", handle_pwm);
....
 }


Sim800L's library can not compile on Arduino Due Sim800L's library can not compile on Arduino Due. Is there any way to create a library for Arduino Due?

#include <Sim800l.h>
#include <SoftwareSerial.h>

Sim800l Sim800l;
char* text;
char* number;
bool error;

void setup(){
    Sim800l.begin();
    text = "Testing Sms";
    number = "2926451386";
    error = Sim800l.sendSms(number,text);
    // OR
    //Sim800l.sendSms("+540111111111","the text go here")
}

void loop(){
    //do nothing
}

I guess that the problem is the software serial library, too. However, I don't know how to replace this library for Arduino Due.

Any help appreciated.

First we must delete the SoftwareSerial and SIM800L libraries, then define Sim800l and assign it to Serial 3 on pins 14 and 15. In setup, call Sim800l.begin() and the rest of the code is unchanged.

#define SIM800l Serial3

void setup () {
  Serial.begin (9600);
  SIM800l.begin (9600);
  while(!Serial);
  SIM800l.write ("AT+CMGF=1\r\n");
  delay (1000);
  SIM800l.write("AT+CMGS=\"5432154552"\"\r\n");
  delay(1000);
  Serial.println("send SMS");
  SIM800l.write ("test send SMS");
  delay (1000);
  SIM800l.write ((char)26);
  delay(1000);
}

void loop (){}


Can I run arduino on Windows Embedded Compact 2013? I'm actually working on a robotic project for which I'm planning to use arduino to drive the wheels.For this, I want to send signals from my Onboard embedded computer (which has Windows Embedded Compact 2013 OS) to arduino. Is this possible? If not possible, what are the other alternatives?

What OS is running on two different devices exchanging messages/signals, does not matter. What matters is the protocol.

You can use a lot of different ones:

Wireless:

IR (infrared)
RF (radio), like 433 MHz, 2.4 GHz
WIFI (internet)
Bluetooth

Wired

SPI
'simple wires' / Wire library
Serial
USB (not on most Arduinos)

This list is not complete, just some examples.

Arduino supports all above (except USB fully), I don't know what Windows Embedded Compact OS supports.


Do I have to wire up my WS2812 LED strip in "series", if I want to address each LED individually? Let's assume I want to make an asterisk (*) out of LED strips. I want to control each leg individually, while still being connected to only one GPIO pin. The layout I had in mind, looks like this:

Since it's an LED strip with individually addressable LEDs, I can't just supply 5V, GND, and DATA to the middle and expect it to work (I highly assume).

If I want to do this, I assume I need to keep running them in "series", basically meaning I hook up one of the strips to the Arduino, then at the end of the strip I run a long wire to the start of one of the others and then repeat. Something like this:

but only for the data wire, as I can simply power all of them in the middle. If not, how can I do this? What happens if I hook up 5 strips' DATA to a single GPIO pin on the Arduino? Are all 5 strips shared then, so each strip's first LED is also the first I would turn on?

The LEDs are "addressed" in series; if you address the first LED then you address all connected first LEDs. So yes, you must connect the Data Out of the previous LED/strip to the Data In of the next in order to address all of them individually.


How to use an external clock with the Due timer? I want to use an external clock signal as an interrupt for the Due timer. How do I do that? I could not find any info on this on the net.

Everything you need to know is in the SAM3X datasheet:

http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf

However, as Atmel's datasheets are some of the most cryptic ones around, you'll need to spend quite some time deciphering it.

There's an entire section just on the timers.  It tells you all about how they work, however, relating that to which registers you need to set to get it to do that is not clear (as is normal for Atmel) since the registers are listed elsewhere in that section with no real relationship between them.


SoftwareSerial too slow for MIDI? I tried to use the SoftwareSerial library for MIDI (by 47 effects), but it seems I get regularly corrupted/unexpected messages.

The circuit I'm using works perfectly when I connect it with the HardwareSerial solution (so the problem must lay in software).

What I see is:

When I press notes and release notes, LED 13 goes on and off correctly.
When I use Serial.print for debugging I get correct messages. However, in the example below I removed the print statements to have a minimal example).
When I use SoftwareSerial, LED 13 goes on and off for every note correctly. However, when I send many messages (for example by aftertouch/pitch bend which send a lot of messages in a short time), I noticed Note On/Off commands with 'random' values are sent.

Some sources say SoftwareSerial should work for MIDI, however, so far it is far from perfect. Do I make some mistake?

(btw, the baudrate of MIDI is 31.250 bps, when I use pitchband several hundreds of bytes per second are sent, so far within the MIDI spec).

The sketch I use is:

#include <MIDI.h>  // Add Midi Library
#include <SoftwareSerial.h>

SoftwareSerial swSerial(2, 11); // RX, TX

MIDI_CREATE_INSTANCE(SoftwareSerial, swSerial, midiSw1);

#define LED 13    // Arduino Board LED is on Pin 13

void setup()
{
  pinMode (LED, OUTPUT); // Set Arduino board pin 13 to output

  midiSw1.begin(MIDI_CHANNEL_OMNI);
  midiSw1.setHandleNoteOn(MyHandleNoteOn);
  midiSw1.setHandleNoteOff(MyHandleNoteOff);
}

void loop()
{
  midiSw1.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
  digitalWrite(LED, HIGH); //Turn LED on
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity)
{
  digitalWrite(LED, LOW); //Turn LED off
}

The problem with SoftwareSerial is that while it is receiving a packet the Arduino is unable to do anything else - that includes reading bytes from the RX buffer, so it will easily overflow if you send things too rapidly. With HardwareSerial you are able to read from the buffer while it's receiving data, so overflowing is less of a problem.

As soon as the START bit of a packet is received it enters an ISR and reads each of the remaining 9 bits of data (including the stop bit) in a tight loop. That ISR doesn't exit until the whole packet has been received and stored in the RX buffer. If another byte is sent straight away there is little time between the ISR finishing and it being triggered again. The rest of the code, including the MIDI parsing routines which read data from the RX buffer, are then starved of CPU cycles and can't run properly. Send too many bytes together and the limited RX buffer (64 bytes) fills up and overflows, and you lose data.

Another issue with SoftwareSerial is that it has to capture the START bit at the moment it arrives. Any delay in capturing that edge will result in a drift in the bit sampling timing. If there is anything else that is using interrupts at the same time (such as the millis() timer) will delay the triggering of the PCINT interrupt used for the START bit detection. Even the SoftwareSerial interrupt itself has a certain amount of time after it has finished receiving the packet where it stores it in the RX buffer and returns from the interrupt routine. If the next packet arrives before the ISR is ready to service it there will be a delay - and any delay is bad.

Personally I am of the opinion that SoftwareSerial should never be used for anything, ever. If you need more serial ports then you either need a more powerful chip or you need more than one chip and get them communicating together through another higher speed hardware channel (SPI or I2C, for instance).

SoftwareSerial is only suitable for sending short bursts of data (since it blocks completely while sending) or receiving very short messages sent infrequently.


Arduino Serial Output Gone Wild! I'm having a slight problem that I'm unable to work out. I am using an arduino Uno to print an incremental, but predefined wheel circumference. This is all working beautifully except it gives a negative reading during execution, and then runs into the positive etc. Without being exact, the output is something like the following:

1.85, 3.71, 5.56, 7.41, 9.27, 11.15....

When this multiple reaches 32.00 or greater, it then counts negatively back down to zero, then positively up to 32.00 again.

I can't quite work out why this would be, so hoping that one of you guys would be able to shed some light. The code is as follows:

#include <Arduino.h>

int InterruptPin = 2;
int circ = 1854; //mtrs
int km = 0;

void calculate(){
    km = km + circ;
    //float temp = km / 1000;
    float temp = (float)km / (float)1000;
    Serial.println(temp);
}

void setup(){
    pinMode(InterruptPin, INPUT);
    attachInterrupt(digitalPinToInterrupt(2), calculate, RISING);
    Serial.begin(9600);
}

void loop(){

}

km is never reset but continously incremented.

km = km + circ;

This leads to an overflow of the value after some time.

When you declare int km;, then int  on an Arduino Uno is int16_t, it thus has a maximum positive value of 2^15 - 1 = 32767. Since circ is constant 1854, after executing the ISR a total of CEIL(32767 / 1854) = 18 times, km becomes greater than that maximum positive value. Thus an integer overflow occurs which takes you back to the maximum negative value of the int16_t. (See https://en.wikipedia.org/wiki/Integer_overflow)

You might want to use uint32_t or similiar from stdint.h if you want to cover a greater value range. I think however your underlying algorithm is flawed, since even then km will  overflow after some later time. You must reset it at some point or only store the number of revolutions, which is a much smaller number. If you want to get the traveled distance then, you take the number of revolutions and multiply it by the circumference.

Also you should not not use any Serial printing within in interrupt service routine! And you should also declare your used interrupt variables as volatile. Read this article for more info.


Arduino Servo with Serial I have an interesting problem. I want to control ESC and servo with Arduino. I'm using HC-12 to communicate with 2 Arduino and I'm using SoftwareSerial on the nano.

#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial mySerial(2, 3); // RX, TX
Servo esc,servo1;

String okunan;
int escval;

void setup() {
  okunan="";
  esc.attach(9);
  servo1.attach(10);
  mySerial.begin(2400);
  Serial.begin(9600);
}

void loop() {
   while (mySerial.available()) {
    delay(3);  //delay to allow buffer to fill
      char c = mySerial.read();  //gets one byte from serial buffer
      okunan += c; //makes the string readString
   }

  if(okunan.length()>0)
  {
    Serial.println(okunan);
    //escval= map(okunan.substring(0,okunan.indexOf(',')).toInt(),0,1023,,2000);

    servo1.writeMicroseconds(map(okunan.toInt(),0,179,1000,2000));

    okunan="";

mySerial.flush();
  }
  delay(20);
  }

When I use a potentiometer, It works successfully. But When I use with serial and if three digit value(between 0-179, for example, 120) comes from serial(HC-12), motor works and stops continuous and irregular. If the value is under three digit there is no problem.

Also, if I delete the ESC variable(servo) or add a new servo to code, it always starts and stops interestingly(Using or not it doesn't matter. If I add Servo servo2 etc., it is going crazy.

I've tried on Uno. That is the same.

Thanks in advance...

Like Mikael Patel said, SoftwareSerial disables interrupts for the entire character receive time.  Bad juju.

This answer lists the alternatives:

HardwareSerial is always the best.  Simply connect the device to pins 0 & 1 and use the pre-defined Serial variable.  On some Arduinos, there are extra HardwareSerial ports, called Serial1, Serial2, etc.  The UNO only has Serial.  Serial would not interfere with the Servo.
AltSoftSerial is the best of the software serial libraries.  Only one instance is allowed, and it is must be used on the Input Capture pins (pins 8 & 9 for a Nano).  It would not interfere with the Servo.
My NeoSWSerial is next best.  It works on any two pins, but only at baud rates 9600, 19200 and 38400.  Receiving characters does not disable interrupts, but transmitting does (i.e., TX would interfere with the Servo).
SoftwareSerial is the worst choice.  It works on any two pins, but it is very inefficient.  It disables interrupts for the entire time that a character is being sent OR received, and it cannot transmit and receive at the same time (unlike all other choices).  This can interfere with other parts of your sketch, other device communications, or with libraries (e.g., Servo).

In your case, I would suggest connecting the HC-12 to pins 0/1 and use Serial.  No software serial library required, but you will have to disconnect pin 0 to upload new sketches over USB.  Some people put a switch in that wire so it's easy to upload a new sketch.

If you need debug prints, I would suggest using AltSoftSerial and an extra TTL Serial-to-USB adapter (aka FTDI module) to your PC.  Then print your debug messages to the AltSoftSerial variable:

#include <AltSoftSerial.h>
AltSoftSerial debugPort; // always pins 8 & 9

   ...

void loop()
{
  if (something) {
    debugPort.println( F("something happened!") );

Or, if the HC-12 connection is receive only, don't connect pin 1 (TX).  Then your debug prints won't go to the HC-12.

BTW, don't use delay and don't use String.  They will get you into trouble sooner or later.


Arduino based Fan controller for PC My fellow programmers,

I'm planning on creating a fan controller for my PC using an Arduino Duemilanove and a generic motor sheild. (Fan controllers are not exactly cheap here and i'd rather spend my money on an SSD than on a fan controller =)

On a normal scenario, I want my fans to spin slowly, just to keep some air flowing but not enough to make too much noise. Obviously, they should turn on at full speed (or so) during a demanding scenario, like playing a game.

My idea is to use a usb port to communicate with Windows, so that my arduino knows when a demanding application was started. Is there an easy way to do this or should I buy myself some cheap temperature sensors, place them on the more important parts and control my fans with these temperature readings?

I'd also like to have an option to turn of the communication between the arduino and whatever informs it about the computer usage, so that I can program it in order to test a different algorithm.

Thanks for any help!

Yes you can. One of the options is using Visual Studio if you are Windows user (using built in library is enough to meet your 'option to turn off' needs). There so many examples of serial communication using either C# or C++ with Arduino, so you can do communication between Laptop - Arduino via serial cable or even built in bluetooth in laptop (with extra bluetooth module for Arduino).

The most simple setup is your laptop act as master and arduino as slave. Arduino does not need any information about what program is running, instead just waiting command from Laptop wether to turn off or turn down the fan

You can read  information from your PC (for Windows), such as temperature or battery level


Make an LED less bright As an exercise to learn rather then the most efficient way to accomplish a goal.... (i'm a hands on hardware guy, but I need to get my Sh!T together and learn some coding)
I would like to make an LED less bright within a project.  I have a nano set up to control a relay to control a dc load when a momentary switch is pressed (this is kinda needlessly complicated solely to allow me to use a particular momentary switch I wanted to use for a bunch of not that great reasons ;-)
Anyway... the code i'm using is this:
int pbuttonPin = 2;// connect output to push button
int relayPin = 10;// Connected to relay (LED)

int val = 0; // push value from pin 2
int lightON = 0;//light status
int pushed = 0;//push status

void setup() {
  // Robojax.com code and video tutorial for push button ON and OFF
  Serial.begin(9600);
  pinMode(pbuttonPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
 digitalWrite(relayPin, HIGH);// keep the load OFF at the begining. If you wanted to be ON, change the HIGH to LOW
}

void loop() {
// Robojax.com code and video tutorial for push button ON and OFF
  val = digitalRead(pbuttonPin);// read the push button value

  if(val == HIGH && lightON == LOW){

    pushed = 1-pushed;
    delay(100);
  }

  lightON = val;

      if(pushed == HIGH){
        Serial.println("Light ON");
        digitalWrite(relayPin, LOW);

      }else{
        Serial.println("Light OFF");
        digitalWrite(relayPin, HIGH);

      }

// Robojax.com code and video tutorial for push button ON and OFF

  delay(100);

The above code is straight up cut and paste... i'm clueless
I have a LED cathode on pin 10, (so i know the relay is on more easily from a distance).  however the application is on a boat, and at night it is too bright and distracting.  So i want to make the LED dimmer... I know I could add a larger value resistor, but i want to expand my understanding and would like suggestions on other ways PWM maybe....
cheers:

There are two methods of dimming a LED : by PWM or by a limiting current resistor.

PWM code
 `//Initializing LED Pin
 int led_pin = 10;
 void setup() {
 //Declaring LED pin as output
         pinMode(led_pin, OUTPUT);
 }
 void loop() {
         analogWrite(led_pin, 127); // half intensity
         delay(5);
 }`

Hardware. Use following schematic


WiFi connection times out if credentials retrieved via serial terminal I've implemented a small WiFi connection procedure into my ESP32 project.
The available networks get printed with index, then I'm entering the index and retrieve the network name from it. The password is entered via serial in clear text.

Before connecting, I'm printing the credentials and thus could confirm they are read into const char * strings properly.

Unfortunately when using this procedure the connection to my AP times out. I've also tried to override the strings with hardcoded values and then the connection works as expected.

while (!Serial.available()) {
    // (timeout is implemented here)
}
String index_s = Serial.readStringUntil('\n');
long index = index_s.toInt();

// { same while as above }
String passw = Serial.readStringUntil('\n');

const char *ssid = WiFi.SSID(index).c_str();
const char *pass = passw.c_str();

// with this it works:
// ssid = "my_network";
// pass = "my_password";

Serial.printf("connecting to %s using %s", ssid, pass);
WiFi.begin(ssid, pass);

The answer was quite simple but of the kind you need some time get find out. The issue was a hiding carriage return.

passw.trim();

Did the trick. String.trim() removes the \r and thus the password gets accepted.


Read analog signal over the SPI bus using MCP3201 ADC and Arduino Uno It is possible to use the SPI bus when the Vref of MCP3201 ADC is 2.5V?
On the setup i just finished, I used two linear regulators: 5V -> 3.3V to power the MCP602 op-amps and MCP3201 ADC, and another one 5v -> 2.5V for the Vref.
Everyone recommends to connect the Vref from MCP3201 to Arduino's 5V but this does not apply in my case.

The green connector is connected to GND and ADC's Dout where the measured voltage fluctuates from 0.180V when i touch the sensor and his shield, to 0.6V when i'm not touching those parts.
I have no ideea if this is a normal behaviour but everything looks fine to me.
Voltage measured at the output of A4 ( MCP3201 +IN ) is 0.85V and the current Iref is 1mA(through the yellow jumper) as they recommend.

Sorry if these details are a bit off-topic but i think they are relevant to the ADC role in this setup.

It is possible to use the SPI bus when the Vref of MCP3201 ADC is 2.5V?

Of course it is. VREF is purely a reference voltage for taking measurements. It has no other role.

If you look at the functional block diagram from the datasheet:

You can plainly see that VREF is only connected to the DAC that is used as part of the SAR feedback loop. Everything else is fed from VDD


Standard Practice for including custom library in examples folder I have created my custom library with examples folder in them. The main header file is ABC_Node.h. I am referring the structure of Adafruit libraries for Arduino and in some repos under the examples folder I found a conflict for the inclusion of their header files.

Example

in some repos. they use double quotes ("") for including their header files e.g. #include "Adafruit_SHT31.h"
SHT31test.ino

on the contrary, in their BNO055 Arduino library they use brackets (<>) #include <Adafruit_BNO055.h> BNO055 Bunny sketch

I locally tested my library on the IDE and I have examples in which my library is in #include "ABC_Node.h" and it compiles without a problem.

Soon I wish to make the repository public and want to know if there is a standard practice for including header files for examples.

You can use either. There is no "standard".

When using a raw C compiler there is a difference between the two as regards the order in which directories are searched for files to include, but with the Arduino that is completely irrelevant, so either can be used.

Personally I use <...> for libraries and "..." for header files that form part of the sketch.  It makes for easier identification of which is which, and conforms to the C standard of <...> for system-installed headers, and "..." for local headers.


2.8 Touchscreen does not work with Proto Screw Shield I am using the Arduino Mega and the 2.8 touch screen by Adafruit, and I can't get the screen to work on my Proto R3 Screw Shield

Here are the tools I am using:

2.8 inch touch screen
Proto R3 Screw Shield

When I put the touch screen onto the Arduino Mega, no wiring needed, and run the graphic test provided by the Adafruit_ILI9341, everything works perfectly. The touch screen runs the animation, and my serial monitor outputs the information of my touch screen.

However, when I put the touch screen on the screw shield, which I place on the Arduino Mega, the touch screen stays white, no matter if I press either reset button, unplug and replug the Arduino, restart the IDE, take off and put everything back on.

I explicitly followed the instructions by Adafruit here that say how to get the screw shield working.

There is no contact between each soldered pin, and I cut and soldered the ICSP and MEGA jumpers on the bottom of the touch screen accordingly, as shown in the picture on the bottom right:

I tried using an SD card as a test to see if the proto R3 screw shield was not working at all, and reading an image off of the SD card. I got proper, working results, so everything worked fine with the screw shield then. This means that the screw shield still works with it's 5V pin.

What could be the cause of the touchscreen staying white? Thanks in advance!

You are set to use the ICSP header for communication with the screen. That is good, when you are directly connected to a Mega.

However that is bad when you are going via a shield that doesn't have an ICSP header.

The ICSP header is the 6-pin (3x2) header in the right of your picture. It has SPI signals that the screen needs. Your screw shield lacks those pins.

You need to pass those signals through. The simplest way would be to add a 3x2 stackable header (or two 3x1 stackable headers) upside down through the correct holes to line up with the ICSP header.


Unable to compile c++11 libraries despite having added -std=c++11 in platform.txt I want to use c++ data structures such as vectors, arrays, map... in my Arduino sketch. I made sure to add -std=c++11 and -std=gnu++11 in platform.txt, I am still getting the following error message:

fatal error: unordered_map: No such file or directory
#include <unordered_map> compilation terminated. exit status 1 unordered_map: No such file or directory

Here's a snapshot from ~/arduino-nightly/hardware/arduino/avr/platform.txt:

Versions:

Arduino ide: 1.8.14
g++: 5.4.0
avr-g++: 4.9.2

What else should I set up?

The AVR-based Arduinos don't come with anything close to a full C++ standard library implementation.  They have avr-libc which is fairly complete to at least the C99 standard, that is the C standard from 1999, not C++.  What you're doing with -std=c++11 is influencing the standard used by the compiler to interpret the C++ language itself.  This does work fine on AVR based Arduinos, but is not going to give you the sort of C++ containers you may be used to on a desktop or larger embedded system, like an ESP8266.
Much of the C++ standard library would be completely out of place on an AVR based Arduino, particularly those parts that make use of dynamic allocation like unordered_map in your error message.
There are some parts of the C++ library implemented via Arduino STL.  Whether or not you should be using containers from it is another question.
If you do try to use Arduino STL, I'd encourage you to use more conservative parts of it.  Something like an unordered_map, but with less (or no) dynamic allocation could be implemented by using Arduino STL's std::array and functions from its <algorithm> header, like their std::find or std::lower_bound, etc.  Trying to use a C++ map or vector container or something of that sort is kind of asking for trouble, more so on the more common AVR-based Arduinos with only roughly 2 Kbyte of RAM.


RF24Mesh master-base node communication delay I'm trying to build a mesh network using 4 nRF24L01 modules directly connected with Arduino Uno where 1 module is master node and the rest are base nodes.

The workflow is exactly as follows

I'm sending a command in the Arduino IDE serial monitor. The master node receives this command and send it to other base nodes. There's no problem receiving the command on the base node side (from master node) as well as sending the command on the master node side (to base nodes). Upon receiving the command from the master node, base nodes successfully able to read the command and send the response. No problem at all.

But when the master node receives the response status from the base node(s), there's the problem. Master node is not receiving the data immediately. I have to send the command from the Arduino serial monitor repeatedly and on the 10th time, the master node is able to read the response status from the base node(s). Exactly on the 10th times every time.

Here's the source.

master node

// global variables
int dat2;
String temp1 = "";
boolean actualDataSent = false;

// get input from arduino serial monitor

 while (Serial.available() > 0) {
      // my command
      String temp1 = Serial.readString();
}

// write block
if (actualDataSent == false && temp1 != "") {

    // send this data to the base node one by one char
    for (int j = 0; j < mesh.addrListTop; j++)
    {
      for (int k = 0; k < temp1.length(); k++) {
        char ch = (char)temp1.charAt(k);
        Serial.print("NodeID: ");
        Serial.print(mesh.addrList[j].nodeID);
        Serial.print(" RF24Network Address: 0");
        Serial.println(mesh.addrList[j].address, OCT);
        RF24NetworkHeader header(mesh.addrList[j].address, OCT);
        Serial.println( network.write(header, &ch, sizeof(ch)) == 1 ? F("Send OK") : F("Send Fail"));
      }
      actualDataSent = true;
    }
    temp1 = "";
  }

// read block
else if (network.available() && actualDataSent == true) {
    RF24NetworkHeader header;
    network.peek(header);

    switch (header.type) {
      case 'M':
        network.read(header, &dat2, sizeof(dat2));
        Serial.print("Got: ");
        Serial.print(dat2);
        Serial.print(" from RF24Network address 0");
        Serial.println(header.from_node, OCT);
        actualDataSent = false;
        break;
      default: network.read(header, 0, 0); Serial.print("Not M case"); Serial.println(header.type); actualDataSent = false; break;
    }
  }

base node:

//global variables

String mypayload = "";
int res1;

// receive command from master
while (network.available()) {
    RF24NetworkHeader header;
    network.read(header, &payload, sizeof(payload));
    mypayload.concat(payload);
  }
  if (mypayload != "")
  {
    Serial.print("Received data: ");
    Serial.println(mypayload);
    if ((mypayload == "100%"))
    {
      res1 = 1;
      Serial.println("Turn ON");
      if (!mesh.write(&res1, 'M', sizeof(res1))) {
      if ( ! mesh.checkConnection() ) {
        Serial.println("Renewing Address");
        mesh.renewAddress();
      } else {
        Serial.println("Send fail, Test OK");
      }
    } else {
      Serial.print("Send OK: "); Serial.println(res1);
    }
    }
    else if (mypayload == "0%")
    {
      res1 = '1';
      Serial.println("Turn OFF");
      if (!mesh.write(&res1, 'M', sizeof(res1))) {
      if ( ! mesh.checkConnection() ) {
        Serial.println("Renewing Address");
        mesh.renewAddress();
      } else {
        Serial.println("Send fail, Test OK");
      }
    } else {
      Serial.print("Send OK: "); Serial.println(res1);
    }
    }
    mypayload = "";
  }

The nRF24L01 "ACK_PAYLOAD" feature allows for two-way data transfer in a single radio transaction.  This is more complicated to set up but plenty of tutorials can be found online, on arduino stackexchange and of course another very helpful source is the nRF24L01 data sheet.  This should solve your problem by ensuring the master/slave radio messages are sent in the same, rather than independent, radio transactions.


Adapt Dynamixel library to different shields I have been playing around with this shield for a couple of days now and I have to agree with some statements made in the comments that the "library" lacks many functions.

However I have discovered the following library which was built for the Dynamixel shield: https://github.com/zcshiner/Dynamixel_Serial

I wanted to know since I am using an Arduino Uno, which parameters I would have to change to make it work.

Sorry I am not very fluent in C++. I have tried just changing the direction pin to 10 but it's obviously not sufficient.

Shield to be dealt with: https://dfrobot.com/index.php?route=product/product&product_id=958

The following code should work afterwards:

#include <dynamixel_serial.h> // Library needed to control Dynamixel servo

#define SERVO_ID 0x01 // ID which we will set Dynamixel to
#define SERVO_ControlPin 0x0A // Control pin of buffer chip, NOTE: this does not matter because we are not using a half to full control buffer.
#define SERVO_SET_Baudrate 57600 // Baud rate speed which the Dynamixel will be set to (57600)
#define CW_LIMIT_ANGLE 0x001 // lowest clockwise angle is 1, as when set to 0 it sets servo to wheel mode
#define CCW_LIMIT_ANGLE 0xFFF // Highest anti-clockwise angle is 0XFFF, as when set to 0 it sets servo to wheel mode

void setup() {
  delay(1000); // Give time for Dynamixel to start on power-up
  Dynamixel.begin(SERVO_SET_Baudrate); // We now need to set Arduino to the new baud rate speed
  Dynamixel.setDirectionPin(SERVO_ControlPin); // Optional. Set direction control pin
  Dynamixel.setMode(SERVO_ID, SERVO, CW_LIMIT_ANGLE, CCW_LIMIT_ANGLE); // set mode to SERVO and set angle limits
  Serial.begin(115200);
  Serial.println("Setup Done!");
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  Dynamixel.servo(SERVO_ID,0x001,0x100); // Move servo to angle 1(0.088 degree) at speed 100
  delay(4000);
  Dynamixel.servo(SERVO_ID,0xFFF,0x3FF); // Move servo to max angle at max speed (1023)
  delay(4000);
}

You are setting the baudrate to 57.6K however, you need to communicate with the Dynamixel at the baudrate it is set to. I believe the Dynamixel comes with a preset baudrate of 1Mbs. The first thing thing I would do is to change your 57.6K to 1Mbs and try that. This is assuming the ID is actually 1 (also a default)

Here are two links for info on Arduino baud rates and Dynamixel serial communications.

Controlling AX-12 Servos

How high of a baud rate can I go (without errors)?


Arduino Nano not showing up in /dev When I plug in my nanoatmega328 to my computer, nothing shows up in /dev as I expect it to. If I plug in my Uno, /dev/ttyACM0 shows up. I have tried several Nanos.

Linux Mint 17.2.

dmesg should be the tool to help you.

Run:

$ dmesg -w

Then hit return a few times (to get some blank lines).

Next plug in your Nano.  Some text should appear on the screen, which will give you a clue as to what is going on.  I don't have a Nano to try with, but a typical working device would look something like:

[29125.599800] usb 9-1.4.1: new full-speed USB device number 13 using ehci-pci
[29125.694742] usb 9-1.4.1: New USB device found, idVendor=04d8, idProduct=0208
[29125.694747] usb 9-1.4.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[29125.694749] usb 9-1.4.1: Product: Lenny
[29125.694751] usb 9-1.4.1: Manufacturer: chipKIT
[29125.694753] usb 9-1.4.1: SerialNumber: CK1660A05353C5
[29125.695213] cdc_acm 9-1.4.1:1.0: This device cannot do calls on its own. It is not a modem.
[29125.695240] cdc_acm 9-1.4.1:1.0: ttyACM0: USB ACM device
[29125.695768] cdc_acm 9-1.4.1:1.2: This device cannot do calls on its own. It is not a modem.
[29125.695791] cdc_acm 9-1.4.1:1.2: ttyACM1: USB ACM device
[29125.697772] input: chipKIT Lenny as /devices/pci0000:00/0000:00:1a.7/usb9/9-1/9-1.4/9-1.4.1/9-1.4.1:1.4/0003:04D8:0208.0004/input/input19
[29125.698394] hid-generic 0003:04D8:0208.0004: input,hidraw2: USB HID v1.11 Mouse [chipKIT Lenny] on usb-0000:00:1a.7-1.4.1/input4

If it doesn't know what the device is it will give you a fraction of the information, and probably tell you it can't attach a driver.

If the device is faulty and not recognisable you will get messages similar to:

[29125.698394] usb 2-2.1: device not accepting address 5, error -71

If you get absolutely nothing displayed then it can't even recognise that anything has been attached to your computer.  Try different USB sockets and different USB cables to see if that helps.

Note: some cheap USB cables used purely for charging small batteries don't have any data wires in them - just power. Using one of these will fail for sure.


Arduino won't send serial data if connected with external power supply I am trying to make a connection between 2 Arduino's with the APC220 rf modules.

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

void loop() {
   int value = 5;
   Serial.println(value);
   delay(1000);
}

I uploaded this code to my Arduino Nano and Uno. I disconnected the rf modules for uploading the code.

I tried to run this program with an external power source (lipo 11.1V 2200mAh).
The Arduino is powered on(power led is on) BUT the tx led doesn't blink.

The only way to make it work is by using the usb and opening the serial monitor on my pc.

I tried to use a 10k resistor between tx and rx (or rx to ground) but the code won't run...

Can someone help me?

Solution : the arduino worked perfect. When you connect the arduino with an exernal power supply the tx and rx lights won't light up, Even when they are transmitting or receiving.

Solution : The Arduino worked perfectly. When you connect the Arduino with an external power supply the Tx and Rx lights won't light up, Even when they are transmitting or receiving.

I'm adding this as the solution to stop this being re-added as an unsolved problem.

That is correct. The Tx and Rx LEDs are connected to the Atmega16U2 processor, and thus only flash if there is serial comms via USB.