Using tinyGPS++ with millis errors Hi I am trying to make search GPS (using tinGPSplus) every x time. The problem is when I do compile the code:

void loop()
{
    read=BP_mnger.pressedButton();
    navigateMenus(read);
    dealWithUsedEvents(getmenuUsed());
    setmenuUsed(0);

    if (isStarted && (GPSSearchPeriod<=millis()-oldMillisVallue)) {

        oldMillisVallue=millis();// if i comment this line it works
        Serial.print(F("oldMillisVallue: "));
        Serial.println(oldMillisVallue);
        while (ss.available() > 0){
            if (gps.encode(ss.read()))
                if (gps.location.isUpdated() || gps.date.isUpdated() || gps.time.isUpdated() || gps.altitude.isUpdated() || gps.satellites.isUpdated() || gps.hdop.isUpdated())
                    GPSSentence=makeGPSSentence( );
        }

    }

I get this:

oldMillisVallue: 22355
oldMillisVallue: 24356
oldMillisVallue: 26357
oldMillisVallue: 28358
oldMillisVallue: 30359

When I comment out:

oldMillisVallue=millis();// if i comment this line it works

I get this :

oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
2000,0,0,4294967295,15,43,3,36,5,41,4.066298,48.269157,77,0.12,90,380,98,2,1,3
2000,0,0,4294967295,15,43,3,39,5,43,4.066298,48.269157,79,0.122200,92,380,98,2,1,3
------------------------
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0

oldMillisVallue: 0
oldMillisVallue: 0
2000,0,0,4294967295,15,43,4,39,5,43,4.066265,48.269126,80,0.12,94,380,101,3,2,5
2000,0,0,4294967295,15,43,4,41,5,45,4.066265,48.269127,82,0.121900,94,380,103,3,2,5
------------------------
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0

You're only reading from the serial port every GPSSearchPeriod milliseconds. That gives plenty of time for the small serial read buffer to overflow and lose the data.

Instead you should be reading all the time regardless of your desire to only do things periodically. Sure, report the data periodically, but you must read all the time as well.


Why it's not possible to manipulate the TWSR directly? I think I forgot the reason for this SFR manipulation in microcontrollers; like, checking the TWSR in twi.

The technique for checking the values of the TWSR is by masking it with another variable or a value.

So, why not checking the TWSR directly in; for example, switch function for checking the values of TWSR?

Like, switch (TWSR)

instead of

uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status)

Or, substitute it in any function; like, Serial.println(TWSR); or digitalRead(TWSR);. DO I have to mask it? If so then why?

Why it's not possible to manipulate the TWSR directly?
  i2c c switch

Because your premise is wrong: it is routinely done to manipulate twsr directly.

As to the use of masks, well, because sometimes you only care about certain bits but not others. So you mask away those that you don't want.

Just that simple.


Is it better to use c_str or toCharArray? When reading/trying a recent answer, I was surprised to see that Arduino's String class supports the c_str() method, just like the C++ std::string class. As expected, it appears to get a pointer to the string's contents as a null-terminated char array (i.e. C-style string).

However, (as far as I can see) that method is not mentioned in the official Arduino documentation. Additionally, in all example code I've seen using String, a different approach seems to be used. A secondary char buffer is setup, and then the contents of the string are copied to it using String::toCharArray(). This obviously requires double the memory, plus an O(n) copy operation.

It seems like c_str() should be the preferred approach. Is there some reason why toCharArray() is more commonly used?

It seems like c_str() should be the preferred approach. Is there some reason why toCharArray() is more commonly used?

basically, I'd say it's a lack of knowledge from the people doing the codes you've seen. Definitely c_str() is better. Though, what I see even more often is the use of character arrays char* strings instead of String (and I plead guilty of that as well in my own codes).

And that's because the Arduino library has been built upon a messy set of C and C++ libraries and coding style. Trying to make things easier actually messed them up and complicated them more.

That's actually why we have new projects like xpcc trying to make a real and smart use of the C++ abilities in the embedded world.


Why does the reading on the ESP32 read max, when the reading on UNO read accurately? I have a 'Capacitive Soil Moisture Sensor' hooked up to my Uno.
Very simple code. AnalogRead(MoistureSensorPin);
This will return a differing value that I can work with.

When applying the same code to an ESP32 with a similar set-up. It always returns '4095' which I understand is the maximum value an analog input can return. But I cannot understand why it does this.

Any help will be much appreciated.

The ESP is a 3.3v device. If your Uno is a 5v device, its A/D converter can measure and report voltages from 0 to 4.9878v (5v minus 1 LSB). If the same signal is presented to the ESP, any value above 3.29919 volts (3.3v - 1 LSB) will read as 4095, i.e., out of range.

(If this isn't your issue, adding wiring diagrams of each system to your question will help us understand it better.)

Update:

  Perhaps a different ESP unit would be the ideal solution?

As far as I know, all of the ESP's are 3.3v devices. So the solutions I see are:

Power your sensor with 3.3v (is this an option?) so its output will be within the input range of the ESP's built-in A/D.
Scale the sensor output from it's 0-5v range to the 0-3.3v range the ESP can accept. Whether you can use a simple divider network or would need an op-amp may depend on the sensor, but if, as I suspect, it is a simple resistance device, a voltage divider should work.
Use an external 5v A/D converter. This will require a 5v power supply (which I presume you are using already, to power the sensor) and voltage level conversion between the A/D and input pin(s) of the ESP. The conversion could be a purchased level-converter board or a simple resistor-divider network.


How do you use the plastic cover/case that came with Arduino? They have holes for screw on, on top of the holes on the Arduino itself. Where can I find parts that are compatible with this case/cover? What was the intended use of this case/cover? Thanks.

The cover was developed for Arduinos with on-board Ethernet with POE and similar cover has the Ethernet shield with POE. POE - power over Ethernet is 48 V, so it is better to not to touch a soldering point with this voltage.

The arduino.org boards were sold with this cover. Some of them had on-board esp8266 and soldering points leading to esp8266 sensitive pins. Again, better not to touch.

I used the cover to attach the Arduino to a DIN rail over a DIN rail clip.


Button and switch to turn on and off LED and changing after time I have system connected to an Arduino Uno where I want to read whether the switch is open or closed.

Based on if the switch is open/closed, I want an LED light to turn on/off.  When the switch is open, the LED turns on and pushing the button turns it off and stays off for 24 hours then turns back on if the switch is still open and I can again turn off the light with one push of the button.  However, if the switch is closed within the 24 hours, the light doesn't turn on and pushing the button does not do anything.

I don't know how to change the state of the LED back on after the 24 hours.  Should I use a button counter, if statements, or while statements?  I'm really new to coding and took on a large project I'm not sure how to complete. This is obviously a very small portion of the project.  Any help is much appreciated.

This is as far as I've gotten.  When the switch is open the LED turns on, but when I push the button, the light just dims.  I also have to hold the button down to keep the light "off" and it turns right back on when I release the button.

if (digitalRead(switch) == LOW) {
digitalWrite(Light, HIGH );

if (digitalRead(Button) == LOW) {
    digitalWrite(Light, LOW);
}

else if (digitalRead(switch) == HIGH) {
  digitalWrite(Light, LOW );

}
}

I have to make an answer, since I cannot use items/links easily in a comment.

Instead of creating the application for you, I suggest you do the following:

Read/try and experiment with the default Arduino examples for a switch (see Switch
In the above example also is shown how to debounce the signal, this is needed since you want to use it as a 'toggle'.
Use a timer for millis() and check for 24 hrs (which is 1,440,000) millis, so it should fit in a long.
Small thing: Always align brackets to make it easier for yourself and others.


make EEPROM.h use custom eeprom partition I created the below partition table for an esp32 and replaced the 'default_8MB.csv' with it.

# Name,   Type, SubType, Offset,  Size, Flags
nvs,      data, nvs,     0x9000,  0x5000,
otadata,  data, ota,     0xe000,  0x2000,
app0,     app,  ota_0,   0x10000, 0x330000,
app1,     app,  ota_1,   0x340000,0x330000,
eeprom,   data, 0x99,    0x670000,0x1000,
spiffs,   data, spiffs,  0x671000,0x18f000,

After uploading a sketch, I confirmed that the partition table was correctly uploaded to the flash at address 0x8000, using esptool.py --port /dev/ttyACM1 read_flash 0x8000 0x300 partition_table.bin && gen_esp32part.py partition_table.bin && cat partition_table.bin.

Now my question is: what do I have to do so that the EEPROM.h library maps the eeprom emulation to the address that I have specified in the partition table? I naively assumed that EEPROM.h would automatically use the partition named "eeprom", which doesn't seem to be the case.

I uploaded the following test sketch to analyse the situation:

#include <Arduino.h>
#include <EEPROM.h>

String s="this is a unique string";

void setup(){
  EEPROM.begin(1024);

  for (uint32_t i=0;i<s.length();i++){
    EEPROM.write(i,s[i]);
  }
  EEPROM.commit();
  Serial.println("EEPROM stored");
}

void loop() {
  delay(10000);
}

After the sketch has stored my unique string I read the flash memory using esptool and expected to find the string at an offset of 0x670000, but that wasn't the case. Instead it must be stored somewhere else because I can retrieve the string in a different sketch.

One thing that is confusing me: I'm pretty sure that I once ordered ESP-WROOM32s with 4MB flash, but the esptool's auto-flash-detection states that my board has 8MB. Can this flash-detection be trusted or does it simply fail because I try to flash 8MB to a 4MB ESP32? What is supposed to happen if I created a partition table that exceeds the flash memory size? When I put a partition table at an offset of 10M the build process still doesn't fail (is that what should happen?).

My main question: which additional steps do I have to take to get my ESP running with a custom_partion_table.csv (beside creating the table) and when using "EEPROM.h"?

EEPROM on the ESP32 doesn't work like you would expect.  It uses the SDK's "Non-Volatile Ram" storage system to store the data within the nvs partition.  This works through a system of "Key / Value" pairs, and the data is stored as a "BLOB" (Binary Large OBject) for the key eeprom in the namespace eeprom.

Quite what the internal layout of the data within the partition itself is I have no clue (the SDK is closed source), but it won't just have your string located at the start of the partition - it will be at the start of the BLOB, wherever that happens to be in the partition.

The eeprom partition is no longer used. It's just wasted space.

  Can this flash-detection be trusted or does it simply fail because I try to flash 8MB to a 4MB ESP32?

I can't comment on that I'm afraid. I would have thought it would look at the chip's JEDEC data, but it may just look at the partition table information instead.

  What is supposed to happen if I created a partition table that exceeds the flash memory size?

Probably not a lot, since much of the partition table refers to data storage, or a (presently) unused OTA partition.

When you compile your code you're only compiling it for the partition in which it will reside (app0 for example). When you upload the code you are only uploading to that partition.  Anything outside that range is irrelevant to the compilation / uploading.

  When I put a partition table at an offset of 10M the build process still doesn't fail (is that what should happen?).

As I mentioned, it won't care. The partition will not be accessible, since it doesn't actually exist, but it's just an entry in a table. The compiler doesn't know or care what it is.


Arduino wrap or subclass print() to work with multiple Serial I am writing an Arduino program that uses Bluetooth on Serial1 to print text to a Bluetooth terninal on an Android phone and also normal Serial to print text to the serial monitor on a laptop. I would like to wrap the Serial.print() and Serial.println() functions so that they work with either or both Serial and Serial1. For example the code below works fine depending on the values of the global variables. But this only works for single chars, but print() and println() can take a very wide variety of datatypes. If I also define overloading functions for int and String types it works fine, but that is a very verbose and maybe fragile solution, it also ignores the optional inputs to the underlying functions. What is the proper way to do this ?

void print(char x) {
  if (g_use_Serial)
    Serial.print(x);
  if (g_use_Serial1)
    Serial1.print(x);
}

void println(char x) {
  if (g_use_Serial)
    Serial.println(x);
  if (g_use_Serial1)
    Serial1.println(x);
}

I have implemented the solution suggested and it works nearly perfectly. There seems to be a problem with the new line characters on the bluetooth (Serial1) connection.

The code is:

class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

void setup()  {
  Serial.begin(9600);
  Serial1.begin(9600);
  delay(1000);
}

void loop() {

  out.use_Serial = true;
  out.print("Printed to USB only.\n");
  out.use_Serial1 = true;
  out.print("Printed to both USB and BT.\n");
  out.use_Serial = false;
  out.print("Printed to BT only.\n");
  out.use_Serial1 = false;

  delay(3000);
}

The output on the USB Serial monitor is as expected:

Printed to USB only.
Printed to both USB and BT.
Printed to USB only.
Printed to both USB and BT.

The output on the Bluetooth terminal is not as expected, the new lines are not in the right position:

Printed to both USB and BT.Pri
nted to BT only.
Printed to both USB and BT.Pr
inted to BT only.
Printed to both USB and BT.Pr
inted to BT only.
Printed to both USB and BT.Pr
inted to BT only.

Any suggestions on how to fix this. Are there other function members that need to be re-implemented to make this work properly?

Many thanks for high quality answers so far.

You can create a class derived from Print that forwards its output to
either or both Serial and Serial1. The only method you need to
implement for this to work is write(uint8_t):

class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

You would use it like this:

out.use_Serial = true;
out.println("Printed to Serial only");
out.use_Serial1 = true;
out.println("Printed to both Serial and Serial1");
out.use_Serial = false;
out.println("Printed to Serial1 only");

Note that with this approach, unlike yours, printing number will format
them as text only once, and the underlying Serial and Serial1 will
only handle the resulting characters.

Edit: To answer the question in OP's comment, the construct

class ClassName
{
    ...definition...
} classInstace;

is a shotcut for

class ClassName
{
    ...definition...
};
ClassName classInstace;

A very similar construct exists in plain C:

struct struct_name {
    ...the struct fields...
} struct_instance;


Connecting Arduino Arduino to MOSFET I want to use my Arduino Nano to control a 12V peristaltic pump via a BDX33c N-Channel MOSFET. The pump has a maximum current draw of 1,4 A. The Arduino (via VIN) and the pump are powered by a 12V supply. I connected the parts like shown in the schematic diagram.

When I plugged the supply in, the Arduino voltage regulator and the Mosfet got really hot (I could not touch it longer than 1-2 seconds) and the RX-LED was on continously, even after turning it off and on again. The Arduino isn't recognized by my Computer anymore, so I assume it is dead.
What did I do wrong with my wiring?

That little blue wire on your breadboard is shorting out the motor. You have most likely now blown the transistor and maybe your power supply. The 12V may also now have made its way into the Arduino through the dead transistor and nuked the rest of it.

Alternatively, the massive base currents imposed by the shorted ground connection may have burned out parts of the Arduino.


Right PIN to activate a wireless relay with ESP8266 ESP-01 I'm trying to program an ESP8266 ESP-01 module to let it connect to my personal wifi network and activate a wireless relay that I've bought.

No problems with Wifi connection so I've omitted the code about it, my problem is to find what is the right PIN to set to LOW/HIGH to control my relay.
Setting relayPin to 1 as shown in this code works and with it I can see the embedded LED turning on and off.

const int relayPin = 1;

void setup() {
    pinMode(relayPin, OUTPUT);
}

void loop() {
    Serial.println("Close Relay for 100 ms and then Open");
    digitalWrite(relayPin, LOW);
    delay(100);
    digitalWrite(relayPin, HIGH);
    delay(200);
}

Surfing the web I've found the following diagram about the ESP8266 ESP-01 module:

I've tried to set relayPin to 0 or to 2 but the relay doesn't activate/deactivate.

So, what is the right PIN number to set in my relayPin constant to control the GPIO0 port?

The relay works succesfully if I give him +3.3V on GPIO0 with an external power.

Thanks in advance

Looking at better pictures of the PCB on ALIExpress it looks like GPIO0 is used to switch the relay.

What that pin maps to, though, depends on what board you have selected in the IDE.


Repeatedly checking multiple "if" statements This code is part of a long code for a robot that is both obstacle-avoiding and remote control. I am trying to get the code to check both "if" statements when the code number FF807F is received from an IR remote. When the code number is received
the program checks both "if" statements and carries out the one that is true. I want the program, once it has finished carrying out the true "if statement, to check both "if" statements again.

void loop () {
if (My_Decoder.value==0xFF807F){
 if (cm<6)
 {
  motor_stop();
  digitalWrite(backlights, HIGH);
  delay(2000);
  motor_backward();
  digitalWrite(backlights, HIGH);
  Serial.println("backward");
  delay(2000);
  motor_stop();
  digitalWrite(backlights, HIGH);
  delay(900);
  motor_right();
  digitalWrite(backlights, LOW);
  Serial.println("right");
  delay(1000);
}
if (cm>6)
 {
  motor_forward();
  digitalWrite(backlights, LOW);
  Serial.println("forward");
}
}
}

I am going to assume you don't want to include cm == 6 which is why you have both cases. I would consider using a while loop instead of a singular 'if' statement in order to continuously check if those buttons are being pressed or not (while (cm<6){do this stuff}). Otherwise, it will check once and never check again.

Instead it will jump down to the next 'if' statement, it will fail and then jump to the top of the loop where it will check for the code 0xFF807F. Let me know how it goes!


I want to print onto serial monitor when it's detected the value change This code is measuring distance from object by using the Ultrasonic Sensor and print onto serial monitor.

However, serial monitor constantly output values.
I want to print only one time if detected value not change.
and serial monitor print again only when detected value change.
and The above condition keeps repeating.

How can i change the code?

int distance ;
int trig = 3;
int echo = 2;

void setup()
{
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
}

void loop()
{
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  distance = pulseIn(echo, HIGH) / 58;
  Serial.println(distance);
}

int distance;
int last_distance; // <== To hold the value from the previous pass
int trig = 3;
int echo = 2;

void setup()
{
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
}

void loop()
{
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  distance = pulseIn(echo, HIGH) / 58;
  if (distance != last_distance) {  // <== Check if new distance is different
    Serial.println(distance);       //     Print only if the values are different
  }
  last_distance = distance;         // <== Store this loop's distance for next round
}


Reading Multiple switch inputs I am trying to setup 20 input switches that can be pressed with hand. I am trying to get the output based on the pattern in which the input switches are pressed with the hand. Based on the pressure and the area of the hand pressing the input switches, there can be multiple switches that can be pressed to display the output pattern at the same time. How can I use Arduino Uno inputs to support these multiple pin reads at the same time?

You could use a MCP23017 or similar.  Its an IC that provides 16 IO ports via I2C, I think you can have 4 of them so that should be enough for both hands.

Or you could use resistors.  All the buttons are connected to a single analogue port.  The resistors are chosen so that when you press any combination of buttons you will get a unique reading at the port. So if you press button one and get a reading of 100, press 2 and get 150, press 3 and get 200, etc.  So buttons 1+2 give you 250, 2+3 gives you 350 and 1+2+3 gives you 450.  The problem with this is the maths get out of hand very quickly and the IC is < $1.


Arduino: Hardware SPI hangs, bit-bang does not I'm using FastLED with a custom board built around the ATMega32u4. When I set it to use Software SPI, everything works fine, but when I use hardware SPI it just hangs whenever it tries to write out the data (FastLED.show()).

I originally mocked this up on an Arduino Pro Micro and it worked fine there. That makes me think that it's a hardware issue but, as I mentioned, SPI output does work, but only when bit-banged. Which really doesn't make much sense.

I tested this by also just using the built in SPI classes and I get the same thing. No luck with hardware SPI.

Anyone else ever see something like this?

The schematic of my circuit is below.

According to ATmega32u4 datasheet, section 17.2.1 (SPI / SS Pin Functionality / Master Mode:

  If SS is configured as an input, it must be held high to ensure Master SPI operation.

In your circuit, SS pin (#8 on package), also labeled as "(SS/PCINT0) PB0", is left unconnected.

Is it possible that PB0 is also configured as input somewhere in your program or libraries? In this case, it should be connected to Vcc.


Is DS18B20 temperature sensor makes Arduino processing slow? I recently run into a problem that causing my whole code processing slow down, for example i had a millis timer set for one minute but it took 1:30m to finish, pressing buttons was laggy etc.

After hours of digging and commenting out codes piece by piece i finally found out what is causing the slow down!

my DS18B20 temperature sensor DATA pin is connected to pin A0 when i remove the library and related codes to the sensor processing became MUCH faster more snappier/responsive...

After googling a bit i realized that everyone connected the sensor to pin 2 of Arduino!

So is the processing slow because DS18B20 is on pin A0 instead of pin 2 or there's something wrong with the sensor itself or it is because of This library?

Indirectly it's the library.

That library uses the OneWire.h library.  The OneWire protocol requires some reasonably precise timing, and because of the the OneWire.h library turns off interrupts while it communicates.

While interrupts are disabled nothing else can happen. That means that the timer interrupt that drives millis() can't "tick" - so the millis count doesn't increase while you communicate with the temperature sensor.


Send an multidimensional array of values from one arduino to another through serial port I have connected two arduinos using pins: RX and TX and managed to send a string as an array of values:

//sender

char mystr[6] = "hello";

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

void loop() {
  Serial.write(mystr);
  delay(1000);
}

And receive it:

//receiver

char mystr[6];

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

void loop() {
  Serial.readBytes(mystr,5);

  if(mystr[0] == 'h' && mystr[1] == 'e' && mystr[2] == 'l'){

    for(int i = 0;i < sizeof(mystr);i++){

      Serial.print(mystr[i]);

      if(i == sizeof(mystr) - 1){
        Serial.print("\r\n");
      }
    }
  }
  delay(1000);
}

That worked fine! But I need to send and receive something like this:

int a[3][4] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

How can I do that?

Use two for loops to send the multidimensional array, and two for loops to receive the multidimensional array.

Sending:

int a[3][4] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      Serial.print(a[x][y]);
   }
}

Receiving

for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      a[x][y] = Serial.read(); // Not sure about the exact prototype
   }
}

If the sizes are fixed (like in your case 3 and 4), than you don't have to send the dimensions, just sent the values in order: 0, 1, 2, 3, 4, ... like above.

And when receiving them you know the first four values belong to row 0, next four values to row 1 etc.

If you need dynamic sizes, first send the number of rows and columns and than the values.

In that case instead of 3 and 4 define two constants and use them:

#define NR_ROWS 3
#define NR_COLUMNS 4

int a[NR_ROWS][NR_COLUMNS] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < NR_ROWS; x++)
{
   for (int y = 0; y < NR_COLUMNS; y++)
   {
      Serial.print(a[x][y]);
   }
}


Is it problematic to 'check an input pin' or 'set an output pin' each step? I am using an Arduino in an automation project which will be using a state machine to conduct a one-hour scenario.  Currently, the Arduino reads each input pin, runs its state update script, then sets each update pin.  99.99% of the time, each output pin will be set to the same state that it had in the last step.  Although it is better (in my opinion) to only set the pin when a setting changes, I was wondering if constantly checking and setting pins would have a big negative impact on the hardware?

Would checking a pin's current state (digitalRead or other method) before setting the pin improve anything?

It does not hurt the Arduino to set an output pin to high if it was already set to high.  If you are concerned about performance, it is more efficient to just set the output pin compared to reading the pin and then setting it only if it's different


OSEPP 16x2 LCD Display Turns On But Does not Display any White Boxes Circuit Wiring
This is my first ever post on here and it is due to a recent personal project i started on a Mega 2560 board. (I was attempting to build a temp and humidity sensor for which i would need to display the values on a LCD display). At first, i built the circuit according to a reference project and i noticed the LCD screen would light up only the first half of the screen (it would be lit up white boxes) img1
Then, assuming my LCD display is not working, i took everything apart and built an initialization LCD circuit.. in which i have read that it should display boxes on the top row. But, when i wire it up very basically, it just lights up but nothing happens. Can anyone tell me whether my LCD might be broken? (I have purchased 3 up till now and would hate to return to the store for ANOTHER broken LCD)
Kindly provide any advice or insight you may have to offer ( I am a complete beginner in Arduino)
I have attached all the pictures of my circuit wiring and of the LCD display.
EDIT 1: I rewired the circuit to include a resistor for contrast (V0; did not use a potentiometer because when i did use it.. it did not make any difference when changing the resistance) I also placed a 100ohm resistor for the backlight (pin A).
The code I used:

#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {   // set up the LCD's number of columns and rows:
lcd.begin(16, 2);   // Print a message to the LCD.   lcd.print("hello,
world!"); }
void loop() {   // set the cursor to column 0, line 1   // (note: line
1 is the second row, since counting begins with 0):   lcd.setCursor(0,
1);   // print the number of seconds since reset:   lcd.print(millis()
/ 1000); }

Also, i have uploaded a close up picture of my LCD and there seems to be a faint 'Dark' spot towards the middle of the display.. does that imply it is damaged?

It is normal that these displays start up with some lines displaying as all white (and others all dark). That's just how they look before they were initialized.
However, as mentioned above, you forgot to wire the data lines. Pins 7-14 from the display need to be wired to the Arduino, typically pins 4-11. But that depends on the configuration in your sketch. It may also work with only 4 lines, then you would connect pins 11-14 from the display to the Arduino pins 4-7 and configure the display to use 4-bit mode in your sketch.
That said, there are more wiring errors in your picture. The lower pin of your potentiometer is unused, and so like this it has no use (and you cannot control the contrast of the display, also making the text, if there is any, hard to read). The bottom pin of the potentiometer must go to pin 3 of the display (remove the line that is already there).


Arduino Leonardo timing Inconsistency I've got a question regarding the use of Millis() on a Leonardo Arduino. I'm currently using it to time 4 seconds elapsed while sending a serial message every second. These messages play a sound. On the fourth message the sound is different to signify that the Arduino has started an event.

I'm running into an issue where the sounds are occasionally being played sporadically without a consistent 1 second between them. I'm wondering if there is a better way of doing what I'm doing? During the timing the Arduino is doing nothing else, and the receiving computer is also generally not doing anything taxing. Is this even an issue from the Arduino side? My receiving program is written in C# using System.IO.Ports.SerialPort.

The reason this is done through Arduino is because the event started by the Arduino needs to correspond exactly to the sounds, though if this remains unresolved I will need to rework this.

Edit: Code as requested.

void setup()
{
    //Setup Code
}

void loop()
{
    //Code that handles other serial messages and various states
    if (isSpecificState == true)
        onSpecificState();
}

void onSpecificState()
{
    //Setup to handle state

    long holdStart = millis();
    long holdDuration = 0;

    boolean print1 = false;
    boolean print2 = false;
    boolean print3 = false;
    boolean print4 = false;

    while(holdDuration <= 4000)
    {
        if (holdDuration >= 4000 && !print4)
        {
            Serial.println("tt_sound:2");
            print4 = true;
        }
        else if (holdDuration >= 3000 && !print3)
        {
            Serial.println("tt_sound:1");
            print3 = true;
        }
        else if (holdDuration >= 2000 && !print2)
        {
            Serial.println("tt_sound:1");
            print2 = true;
        }
        else if (holdDuration >= 1000 && !print1)
        {
            Serial.println("tt_sound:1");
            print1 = true;
        }
        holdDuration = millis() - holdStart;
    }

    //Handle state
}

As I mentioned in the comments, the Arduino is doing nothing else while the timing is happening.

There is only a very slight chance that you meet the holdDuration >= 4000 condition in the while loop. Only when holdDuration will be exactly 4000 the while loop will be executed AND the subsequent test in the if statement will pass.

The serial print commands can easily take long enough to have millis() jump from a number less than 4000 to a number higher than 4000 in a single pass of the while loop.

To prove this assumption, increase the while test to holdDuration <= 4100 and see if the intermittent effect goes away.


Arduino write/handle long programs I'm writing a "sketch" in the Arduino IDE which has at this very moment 1500 lines and is going to become much longer. I splitted it in several tabs, but that's not very comfortable to use (I need to find the "precompiler" file in a temporary folder in order to have my program in a printable version, in the tabs bar I can't see all tabs, ...).

Are there any better alernatives to the Arduino IDE? Someone suggested me PlatformIO, is that a good IDE? (please note that I have a mac running OS X 10.12.1; I also have a (virtual) Windows 10 machine if absolutly needed, but I'd like to install the IDE on MAC OS X)

What are the best ways to create a long program? In general, for C++, what are the best practices? And is for Arduino the same?

Have you tried Atmel Studio? Right now, it only supports Windows but is a great alternative to Arduino IDE.

If you're not comfortable using Windows virtual machine, I suggest you have a look at this: http://playground.arduino.cc/code/eclipse


Understanding the variation of Arduino's current consumption with respect to the voltage supply Even though this is already a well-debated topic, I couldn't find an extensive discussion about what really is drawing so much power in Arduino's board.

Here is the preamble: I have an Arduino Mega 2560, I measured its power consumption in a steady state with just a red LED turned on with a 560Ohm series resistor.
The power supply (Vcc) was given to Arduino from the Vin pin and the measurement were as follows (below the schematic set-up):

30mA @Vcc = 5.2V;
65mA @Vcc = 8.3V.

What I would like to understand is:

From a hardware perspective, I don't see what is drawing all of this current in Arduino's board;
Why the current drawn from the power supply changes so much with the power supply's value (i.e. what part of the board changes its consumption with the power supply value);
It also seems that turning on an LED through a digital output of Arduino draws a higher current with a higher power supply (Vcc). Why is that?

Note that, by looking at the datasheet of the ATmega2560, the uC mounted on my Arduino, I saw that the current Icc drawn from the power supply is max 14mA (I suppose when no output is sourcing current, I couldn't find the test conditions, unfortunately). I thought the microcontroller was the major cause of power consumption, but it doesn't seem to be so!

Another thing I considered is the onboard LDO, but the input voltage should change the power dissipated by the LDO, not the current drawn from its output.

It's even more strange if you think that regardless of the Vin, all the electronics after the LDO is working at the same voltage.

EDIT1

After Majenko pointed out a big flaw in my set-up with his answer, I re-measured with Vcc = 12.1V and I measured approximately the same Icc observed at Vcc = 8.1V.
I completely agree with Majenko's answer and I would just like to go a bit more in details about what happens while the board is working under voltage.

Here is my analysis:

The minimum operating condition when supplied from Vin is 7V, and that's the "knee" point in Majenko's answer.

However, the maximum quiescent current of the LDO is 10mA, and the Icc of the ATmega2560 is 15mA, so even if we suppose they don't draw any current at Vcc=5.2V, and then draw 25mA together at the minimum operating voltage at 7V, this doesn't add up to the actual increase of 40 or 50 mA that Majenko calculated I observed from 5.2 to 8.3 (which should be the same as from 5.2 to 7V).

And we're not even taking into account that at 5.2V the micro is perfectly able to turn on and keep on the LED, so it's somewhat working and already drawing some current.

Other things that we can take into account, but don't change the facts, are:

a second LDO (LP2985) to generate the 3V3, whose quiescent current should be around 100uA since the circuit is not drawing any current from the 3V3.
a second microcontroller related to the USB programming, whose Icc may be up to 20mA but this one is OFF when supplying from Vin.  -->  Edgar Bonet correctly pointed out that this is not true!
Some voltage dividers and comparators.

So what is the cause of this increase in current consumption from 5 to 7V?

There is a basic error in your methodology which leads to incorrect conclusions.

You cannot determine what is going on from just two data points. Instead you need far more.

Here is a voltage sweep from 5V to 12V with a 0.05V resolution (overkill, but the default setting for the script I use) connected to a Mega:

As you can see the current steadily climes in a pretty linear fashion up to a certain point, then it flattens out.

Everything up to the point where it flattens is below the minimum input voltage for the board. During this time the voltage regulator isn't getting enough voltage, so can't regulate its output voltage to 5V. So the board is running under voltage at this point.  Once it reaches that "knee" point the voltage regulator can regulate the voltage properly - so most of the components on the board start seeing a steady 5V and their current consumption flattens out.

There are a handful of components on the high-voltage side of the regulator - most notably the voltage divider for detecting the input voltage and feeding it to the comparator that drives the P-channel FET to turn the USB power on and off - which will consume slightly more current when the voltage increases, but that is only very small amounts.

So, in short, by comparing a voltage that is below the minimum input voltage for the board with one that is above the minimum input voltage, you are comparing an invalid result with a valid result and inferring that everything in between is valid.


Ethernet.begin() conflicts with build-in LED on Arduino Nano I have Arduino Nano "clone" which I would like to use with Ethernet ENC28J60 shield. I have noticed that when I include/use UIPEthernet.h library, build-in LED does not work properly. I have written the following sketch which I have uploaded to Arduino and run both with and without Ethernet shield with the same result: LED is not blinking. Once I comment out the line Ethernet.begin(mac), LED starts blinking just fine.

Is there any way to overcome this conflict?

#include <UIPEthernet.h>

EthernetClient ethClient;

uint8_t mac[6] = { 0x90, 0xA2, 0xDA, 0x0D, 0xE2, 0xCD };

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

  // If this line is commented, LED starts blinking:
  Ethernet.begin(mac);

  pinMode(LED_BUILTIN, OUTPUT);

  Serial.println(F("setup() done."));
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
}

No, you can't.

The LED is on pin 13. Pin 13 is the clock pin for SPI. The ENC28J60 is an SPI device.

You either have control over pin 13, or you have SPI. You can't have both.


Will the Uno bootloader work in the Duemilanove? I had an old duemilanove lying around (Which was not working because i accidentially busted the atmega) and I recently bought some atmegas pre-flashed with the UNO bootloader. So I tried to put one of those in it, and it seems to work fine except that I have to select the UNO board in the arduino IDE.

My question is: Is there anything problematic to be aware of when using the UNO bootloader in an duemilanove?

So I researched it a bit, and there does not seem to be any problems with running the UNO bootloader on a Duemilanove board.

The biggest difference between the two seems to be the USB interface:

USB interface

Duemilanove uses FTDI, UNO uses another microcontroller (ATmega8u2).

Since the USB to serial is transparent for me as an end user for the most parts, it doesn't really matter to me.

Leaner bootloader

The UNO bootloader is smaller than the duemilanove.


Turn LEDs on in binary sequence Could I have some help getting the following code work?

My purpose is to turn on 4(or N) LEDs in a binary sequence with 4 (or N) bits, A,B,C,D. When bit=1, LED on, otherwise LED off,...

I will have 16 combinations, 2^4=16, so:

0000 => All leds off
0001 => All leds off except the one on the right
...

Here's the code I came up with:

int LEDblu=4;
int LEDgiallo=2;
int LEDrosso=5;
int LEDverde=7;
int num_led;
String numeri="";
String output;
int i=0;
int p;

void setup() {
    // put your setup code here, to run once:
    pinMode(LEDblu,OUTPUT);
    pinMode(LEDgiallo,OUTPUT);
    pinMode(LEDrosso,OUTPUT);
    pinMode(LEDverde,OUTPUT);

    Serial.begin(9600);

    if(Serial.available())                //Dimmi numero LED
    {
        num_led=Serial.readString().toInt();
        Serial.print(num_led);
    }
}

void loop() {
    // put your main code here, to run repeatedly:
    int vect[num_led];
    for(int i=num_led-1, c=0; i>=0; i--, c++)
    {
        int num=2^i;
        vect[c]=num;
    }

    output="";

    if(i<2^num_led)
    {
        p=i;

        for(int c=0; c<num_led; c++)     //Convert binary to decimal
        {
            if(p>=vect[c])
            {
                output+="1";
                int d=vect[c];
                p-=d;
            }
            else
                output+="0";
        }

        Serial.println(output);

        if(output[0]=="1")
            digitalWrite(LEDrosso,HIGH);
        else
            digitalWrite(LEDrosso,LOW);

        if(output[1]=="1")
            digitalWrite(LEDverde,HIGH);
        else
            digitalWrite(LEDverde,LOW);

        if(output[2]=="1")
            digitalWrite(LEDgiallo,HIGH);
        else
            digitalWrite(LEDgiallo,LOW);

        if(output[3]=="1")
            digitalWrite(LEDblu,HIGH);
        else
            digitalWrite(LEDblu,LOW);
    }

    delay(1000);
    i++;
}

Note that this is one of those situations where direct port access
just makes things easier. You did not specify what board you are using,
and I will assume you have some AVR-based board. On those boards, I/O
pins come in groups called ports, with up to eight pins per port. You
can update all the pins of a port at once by writing a number to the
port output register. And guess what? The number you write comes out the
pins in binary, jut like everything works in binary inside the
microcontroller.

For example, on an Arduino Uno, you could wire your LEDs to the first
four pins of port B: i.e. pins 8 (lest significant bit) through 11 (most
significant bit). Then you can output a number to the LEDs just by
writing PORTB = number, and your loop would become:

void loop()
{
    static uint8_t number;
    PORTB = number;              // output to pins 8..11
    Serial.println(number, 2);   // print the value in binary
    number = (number + 1) % 16;  // increment modulo 16
    delay(1000);
}


ATMEGA328P-U vs ATMEGA328-PU On my Arduino UNO the chip part number is ATMEGA328P-U, i recently bought a ATMEGA328-PU to make a standalone Arduino. realized the part number differences after receiving the package...

I noticed that some arduino UNOs have the chip with part number of ATMEGA328P-PU! I'm totally confused!

Those chip are the same? can i use the one that i bought for an standalone Arduino?

If no what are the differences?

The main difference is the bit before the -. That is, the 328 vs the 328P.  The "P" there denotes "Picopower" which allows the chip to run at very low power consumptions.

Basically the P version is a more modern version of the non-P chip.  There are probably other internal differences too but you will have to check the datasheets thoroughly for those.

Everything after the - is to do with the packaging and environmental grading of the chip.  For example PU is a -40C to +85C grade DIP chip. ANR is a -40C to +105C grade TQFP chip, etc.

If you see 328P-U then that's probably a fake chip. There's no such thing as single U suffix.


How to use Aiduino module to connect to computer network? I have 4 usb Hard Drives and I just want to connect them to computer network directly without a traditional computer. Is there an any module with 4 usb ports and one RJ45 port. The module should able to connect drives to network as NAS (Network Area Storage) or other mounting possibility.

An Arduino is completely incapable of doing such a difficult task. It's literally impossible because the processor isn't strong enough, it has no built in network capabilities that support NAS, it has no USB software built in, and so on and so on.

But you can use a Raspberry Pi. They are cheap for their capabilities, they do require quite some programming to get it to work but there's a huge community that has guides for everything. Best of luck :)


How to logically tell than an UNO is being, or about to be programmed I have an MIDI application that uses the RX and TX serial interface.  When I program the UNO there is a collision between the on board programmer and the MIDI application RX serial port.  The MIDI shield provides a jumper to disconnect to prevent the collision during programming.

I would like to add a FET switch to open and close if I am programming, but it's not clear to me that there is a signal I can tap into on the UNO that indicates programming is about to start or that it has just finished.

I was thinking about using a pull up on a digital pin on the UNO that drives low when the program starts up. That might be the way to go, but I assumed that this must be a common issue with a common solution that I am just not finding on stack exchange.
Is there a standard logical way to tell that UNO is about to be programmed via the onboard USB port?

Your proposed solution is the normal method. A GPIO pin which is an "Activate Device" signal. It's pulled in one direction, the "inactive" direction, and you actively drive it in the other "active" direction in your program.


How can I2C be made to work through a level shifter? I am attempting to use a bi-directional level shifter for an IMU to shift the SDA and SCL lines in an I2C implementation, however cannot get the level shifter working with the Arduino at all. It feels like the bi-directionality is confusing the master<>slave relationship and pulling the high and low levels to some average, preventing communications.

At idle, with no connection, the SDA and SCL lines on the Adruino are are 5 V, however when connected to two channels of the level shifter, the voltages drop to 2.5 V on the high side and 1.7 V on the low side of the shifter. The low side of the shifter is completely open so shouldn't be controlling the voltage at all, I've even tried a 10 kOhm and 1.5 kOhm pullup resistor between the low and high sides and their respective voltages, 3.3 and 5 V, but that hasn't worked either.

The level shifter works fine interfacing the MEGA to an SD card over the SPI pins, so I don't understand quite why the level shifting would stop working with the I2C.

The fault manifests as the Arduino hanging on a Wire.endTransmission(); call, which would seem to suggest the MEGA is failing to oscillate its SDA and SCL pins as it wishes. The problem occurs when either of the SDA or SCL pins are connected to the shifter high-side.

I also know that the Sparkfun datasheet for the IMU states that for I2C a level shifter is not necessary, but in debugging another problem, this is being attempted as a solution.

Level shifter: Adafruit 8-channel Bi-directional Logic Level Converter

IMU: Sparkfun LSM9DS1 breakout

Arduino: MEGA 2560 v3

For I2C you need a special kind of logic translator. This one isn't suitable.

  This device can only translate push-pull CMOS logic outputs. If for open-drain signal translation, please refer to TI TXS010X products.

Personally I use the PCA9306DCUR since it is specifically designed for I2C operation.


SD Library function doesnt work while using second SPI port with ESP32 i work on a group project with an ESP32. We have a lcd display and a sd card connected via the two SPI ports of the ESP32.

The card gets initialized with no problem using this code:

 bool EKG_recording::initialisation_sd() {

  SPIClass * hspi = new SPIClass(HSPI);

  if (!SD.begin(CS_Pin, *hspi))
  {
    Serial.println("No valid SD card!");
    return 0;
  }

  else if (SD.begin(CS_Pin, *hspi))
  {
    Serial.println("SD card initialized!");
    return 1;
  }
  else return 0;
}

One function i have a problem with is used to count every file on the SD card, simple enough right?

unsigned short EKG_recording::count_files_from_SD(File dir) {
  while (true)
  {
    File entry = dir.openNextFile();
    if (!entry)
    {
      // Serial.println("Anzahl der Daten");
      return counter;
    }
    counter++;
    entry.close();
  }
}

It once worked without a problem, then we integrated the two SPI ports and now i cant figure out why its not working.
This part:
File entry = dir.openNextFile();
returns false on the first call even though i am 100% sure there are 3 files on the SD card.

I call the function like this :

File root = SD.open("/");
EKG_recording_1.count_files_from_SD(root);

But why? Any help is very appreciated.

This is the begin function of the display. Since i didnt write it, i know next to nothing about it.

    void EKG_display_control::begin()
{
  // Backgroundlight off
  pinMode(TFT_LED, OUTPUT);
  disable_display_backlight();

  // Initialise Display
  tft.begin(40000000);
  touch.begin();
  tft.setRotation(ROTATION);

  layout_start_screen();
}

Ok i found the solution. It was not too complicated. I just assumed the problem was in the code. This works well enough (dont ask me about the counter--)

  unsigned short EKG_recording::count_files_from_SD() {

  root = SD.open("/");
  root.rewindDirectory(); //Sets to beginning of directory

  while (true)
  {
    File entry = root.openNextFile();

    if(!entry){
      Serial.println("Anzahl der Daten");
      counter--;
      return counter;
    }
    counter++;
    entry.close();
  }
}

It was just because i used SD.open() always inside the class-functions, so every file root was bound to the class.


Relay to Mains lightswitch So I purchased a 4 channel Relay which handles AC250V 10A ; DC30V 10A.
But am I able to connect this to replace a light switch so I can automate it?  My bedroom runs on 15 amps.

http://amazon.com/gp/product/B00VHVIBAM?psc=1&redirect=true&ref_=oh_aui_detailpage_o00_s00

All mains electrical work should be performed by a fully qualified electrician.

Yes, this relay board will easily switch a light bulb.

A note on current: A single 100 Watt incandescent globe will only draw 0.83 Amps at 120V AC (0.416 Amps at 240V AC). The equation I used: I=P/V. You would start coming close to the maximum rating after 10 globes (although I advise staying well below the maximum).

You mention that your bedroom runs on 15 Amps, which I assume means that the mains runs through a 15 Amp circuit breaker (or fuse). This circuit breaker will trip if the total current to all devices after it exceeds 15 Amps.

A similar question was asked by Matthieu Napoli over on the Electrical Engineering Stack Exchange site. There are a number of high quality answers there that would be helpful for you. Worthiest to mention is Cybergibbons answer where he recommends using the PowerSwitch Tail as a very safe way of switching mains voltage. You don't need an electrician when using the PowerSwitch Tail providing the light you are controlling has the matching plugs.


Arduino to Raspberry Pi wired communication I am new to Raspberry Pi (just brought mine before writing this post), and I am looking to see what is the most ideal way for two way communication between an Arduino and a Raspberry Pi (USB, SPI or I2C).

The reason I am asking is because I need to build a small, semi-autonomous robot and plan on using both the Arduino and Pi to control it, using the pins of the Arduino for the motor control and sensors and the Pi for video processing and autonomous part. Both will be on the robot itself. I am pretty good with the Arduino but never used a Raspberry Pi before.

So my biggest question is what would be the best form of communication for the two boards taking into account speed and safety (there is a voltage difference between the Pi and the Arduino).

Hands down, I can rule out the I2C. This post sums it all up:

  SPI is faster.
  I2C is more complex and not as easy to use if your microcontroller doesn't have an I2C   controller.
  I2C only requires 2 lines.

Since speed is your first priority, either do USB or SPI. I'd personally go with USB, just for the reason that it's simple. Nearly any programming language can inference with COM ports, but that's not the case with SPI. Also, for SPI, you would have to either use a level shifter, or do a voltage divider for the Arduino to RPi wires (for RPi to Arduino wires, Arduino can still sense 3.3V as HIGH.)

Also, serial can be pretty fast. Technically, the Arduino can go up to 2 Mbps (not very fast compared to a lot of things, but fast enough for what the Arduino can even handle). One thing to note, the writer of the post stated that this is the highest you can practically achieve with the poorly optimized libraries:

Serial.begin(500000);


How to use RS-232 sheild as software serial port? I would like to be able to use a USB port at the same time as an RS-232 port with my Arduino Uno board. I unwittingly bought a shield that (I think?) overrides the USB port when it is mounted to the Arduino board:

http://www.dfrobot.com/wiki/index.php/RS232_Shield

Would anyone be able to give me any advice on how to connect the hardware so that I can have two serial ports accessible from my Arduino Uno? The format I was thinking was (Arduino => RS-232 Sheild):

GND => GND
5V => 5V
Digital Pin 2 => 232RXD
Digital Pin 3 => 232TXD

The accompanying code for initializing the serial port which I've written:

const int rxpin = 2; // pin used to receive
const int txpin = 3; // pin used to send
SoftwareSerial Serial_rs232(rxpin, txpin); // new serial port

Any ideas as to why this may or may not be a good method of using the hardware I have available for the purpose I had in mind?

GND => GND 5V => 5V Digital Pin 2 => 232RXD Digital Pin 3 => 232TXD

A better choice of board would be the Leonardo, since you could connect such a shield and use the USB port right out of the box. However, since you have the Uno, there is a solution.

From Arduino:

  The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

It then goes on to reccomend the library AltSoftSerial.

Here is some example code from the link above:

#include <AltSoftSerial.h>

AltSoftSerial altSerial;

void setup() {
  Serial.begin(9600);
  Serial.println("AltSoftSerial Test Begin");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() {
  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}

It acts like a standard serial port, only you declare the connection as a variable first. This code is written for a board with an additional serial port, like you have.

All is good, except for one problem:

The problem is the shield is wired to connect to pins 0 and 1: the ones used by the USB adapter. The AltSoftSerial library uses pins 8 for TX and 9 for RX. (Note: You cannot use PWM on pin 10 on the Uno... it should still work as a digital pin.) In that case you would not attach the shield by plugging it into the Arduino, and you would wire it like this:

  GND => GND | 5V => 5V | Digital Pin 8 => 232RXD pin 0 on the shield headers | Digital Pin 9 => 232TXD 1 on the shield headers

So then, you would be manually wiring the shield to the Arduino with jumpers. As long as it doesn't connect to any other Arduino pins I'm not aware of (it shouldn't besides maybe 13 for a LED or something like that), it should function like it would stacked and using pins 0 and 1.

Note: (Obviously) You cannot connect anything to the headers on the shield (You cannot connect to pin 5 and get a signal).


Not output on serial monitor, sending string on serial.print I get two 10-bit values from analog pins. These two values in a string, ";" combine with.
for ex:  515; 510
I am sending it to another arduino via Serial.print. I cannot display this string expression on other arduino's serial monitor. But when I press the reset button of Coordinator arduino, there are a few values. Can you help me?
My Coordinator Code:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
int deger3;
int deger4;
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);

void setup() {
  //Serial.begin(9600);
  xBeeSerial.begin(38400);
  }void loop() {

    deger3 = analogRead(A0);
    deger4 = analogRead(A2);

    String deger5 = " " + (String)deger3 + ";" + (String)deger4 ;

    Serial.println("string ifade: " + deger5);

    xBeeSerial.print(deger5);
  }

My Receiver Code:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
String d1;

void setup() {
  xBeeSerial.begin(38400);
  Serial.begin(38400);
}
void loop() {
  if(xBeeSerial.available()){
    d1=xBeeSerial.readString();
    Serial.print(d1);
  }
}

There is a fundamental problem with your communication strategy, and that is you have nothing to tell the receiver "This is the end of a message".
You are sending a constant stream of
 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510.....

and the receiver really doesn't know what to make of that.
This is because you are using the function .readString() at the receiver. This will blindly receive characters and store them in the target string up until the point those characters stop arriving. And that happens only after a break of at least 1 second in transmission. That never comes. So never ends. That is, until you reset the sender and it sees that break in transmission.
It's a very crude function and I'd never recommend anyone ever using it for anything.
Instead you need to break your transmission up into separate lines with .println() or appending \n to the string.  Then you can use .readStringUntil('\n') to get each line in turn and display it.
Also, on a side note, you really shouldn't be appending all your data to a string then sending the string, that's completely redundant. Just send each individual part of the data as separate prints. All you're achieving with all that String manipulation is to fragment your heap and cause your code to be unstable.


Why are Tone.cpp and IPAddress.cpp getting built for my project? I'm using avr-size to see the size of library objects to free up some FLASH. Why are Tone.cpp and IPAddress.cpp getting built? e.g.

$ cd /var/folders/3j/6wp3hvrj34n0xg3xzq6vjq380000gn/T/build8391693238079360471.tmp/
localhost:build8391693238079360471.tmp
$ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size *.o
   text    data     bss     dec     hex filename
      0       0       0       0       0 CDC.cpp.o
      0       0       0       0       0 HID.cpp.o
   1816       0     170    1986     7c2 HardwareSerial.cpp.o
    512       0       6     518     206 IPAddress.cpp.o
  10186     391     377   10954    2aca MainINOFile.cpp.o
   1872      14       0    1886     75e Print.cpp.o
   1414       1       0    1415     587 Stream.cpp.o
   1365       1      21    1387     56b Tone.cpp.o
      0       0       0       0       0 USBCore.cpp.o
    288       0       4     292     124 WInterrupts.c.o
    306       0       0     306     132 WMath.cpp.o
   4796       1       1    4798    12be WString.cpp.o
     30       0       0      30      1e main.cpp.o
    618       6       0     624     270 malloc.c.o
     56       0       0      56      38 new.cpp.o
    450       0       0     450     1c2 realloc.c.o
    588       0       9     597     255 wiring.c.o
    266       1       0     267     10b wiring_analog.c.o
    550       0       0     550     226 wiring_digital.c.o
    320       0       0     320     140 wiring_pulse.c.o
    260       0       0     260     104 wiring_shift.c.o
$ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size */*.o
   text    data     bss     dec     hex filename
   2790       0       0    2790     ae6 DS3231/DS3231.cpp.o
     38       0       1      39      27 EEPROM/EEPROM.cpp.o
   1444       0       0    1444     5a4 LSM303/lsm303.cpp.o
    782       0       0     782     30e Messenger/Messenger.cpp.o
    116       0       1     117      75 SPI/SPI.cpp.o
    142       0       4     146      92 SdFat/MinimumSerial.cpp.o
   2568       0       0    2568     a08 SdFat/Sd2Card.cpp.o
  10644       0       4   10648    2998 SdFat/SdBaseFile.cpp.o
   1322       2       0    1324     52c SdFat/SdFat.cpp.o
    152       0       0     152      98 SdFat/SdFatUtil.cpp.o
    233       0       0     233      e9 SdFat/SdFile.cpp.o
    736       0       0     736     2e0 SdFat/SdStream.cpp.o
   2604       0     523    3127     c37 SdFat/SdVolume.cpp.o
   3395       0       0    3395     d43 SdFat/istream.cpp.o
   1635       0       0    1635     663 SdFat/ostream.cpp.o
    754       0      86     840     348 Wire/Wire.cpp.o
$ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size *.elf
   text    data     bss     dec     hex filename
  29204     442    1279   30925    78cd MainINOFile.cpp.elf

As stated the IDE's equivalent to the make will compile anything everything it can find, in scope. But its linker has eliminate garbage enabled, hence anything not called or not static will not be linked into the EXE.

You can "avr-objdump -t" to create a map from your elf. And -d for an assembly listing. As to see exactly what is in the EXE, for your self. You need to enable show verbose output of compilation from the IDE's preferences, to display the temporary directory that contains the elf file.

example:

C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp>C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -t MP3Shield_Library_Demo.cpp.elf > MP3Shield_Library_Demo_wo_mem.cpp.elf.map
C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp>C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -d MP3Shield_Library_Demo.cpp.elf > MP3Shield_Library_Demo_wo_mem.cpp.elf.lst

I did the above and commented out a call to a function member of my library, between subsequent builds. To see that the code was not linked into the assembly.


Using for loop to set pinMode I notice problems with my output pins when I use this method of setting their pinMode:

int allOutputPins[] = {3, 4, 9, 10, 5, A3, 11, 12, 7, 8, A1, A2};

for(int a = 0; a < sizeof(allOutputPins); a++){
   pinMode(allOutputPins[a], OUTPUT);
  }//end for

Am I doing something wrong?

Re  “Am I doing something wrong?”, yes :)

The sizeof(allOutputPins) expression returns the size of allOutputPins[] in terms of bytes, so is 24 because the array contains 12 two-byte integers.  The loop's last 12 pinMode() calls will be garbage.

Among other ways of fixing the problem, you could change the expression to sizeof(allOutputPins)/sizeof(int) [which has the same value, 12, as (sizeof allOutputPins)/sizeof(int); eg see the syntax entries for the sizeof operator at cppreference.com] or you could change the base type of the array to byte or uint8_t.


Powering arduino and node mcu I want to power up my Arduino and my Nodemcu via 12 V , 1 A power adapter (it's an AC to DC power Adapter).

Recently I have two voltages regulators: a 5 V for nodemcu and 9 V for Arduino Uno.

The question is does the 1A affect both boards or not?

In principle not. However, the voltage regulators may become quite hot, since you are going down from 12 V to 9 V and 5 V (especially the step from 9 V to 5 V is quite a lot). It depends on the current (in (milli)Amps) how hot they get.

For the adapter it does not matter, if it is 1 A or 10 A, the microcontrollers will only take whatever they need. Only if the adapter can deliver less than needed by both microcontrollers there is a problem.

The voltage regulators are not of switching type I guess, so they will use the same amount of amperes. Assuming the Arduino Uno takes 300 mA (at 5 V) and the NodeMCU 200 mA (at 12 V), you can add them together: 200 mA + 300 mA = 500 mA. Since this is less than 1 A the adapter can deliver, you are ok.


How to perform two tasks in one loop in Arduino? I am trying to make a weather monitor using Arduino. I want my weather monitor to send me a message of the weather data every 5 hours using GSM sheild. Also, there is an LCD on my weather monitor which shows live weather conditions. The problem I am facing is that the delay of 5 hours in my code also applies to the LCD which updates the LCD every 5 hours and not every second as it should. Please tell me how to run these two functions simultaneously.

Consider using a finite state machine to track multiple tasks.  Specifically, the state in which you send your message once every 5 hours.  And, the state you update your LCD, perhaps once every second.

As your tasks are associated with time, consider using the built in Arduino call to millis() to find how many milliseconds the Arduino program has been running.  This will not block your program.  Instead it will immediately return with a number you then need to manage.

To create a delay, use the above number from millis() and add the number of milliseconds for the desired delay.  Call millis() repeatedly until it returns the calculated number or a number greater than the calculated number.  Use this to drive your state machine.  Perhaps you only use millis() to count seconds and use software to count up to 5 hours (5 x 60 x 60 seconds).

Note, millis() will eventually roll over as it is of type "unsigned long".  That is, it will roll over once about every 50 days.  If you want to keep accurate timing when this happens, you will have to account for the roll over in your program.


Using ATTiny85 as a USB HID Mouse Our project involves using an arduino compatible microcontroller to control a mouse on a computer with an accelerometer and flex sensor. We had narrowed down to the ATTiny85 due to its small size.

We found a particular tutorial on the Adafruit tutorial  website, using the Adafruit Pro Trinket using the same ATTiny85.

Is there a reason to believe that this won't work?

Also, does anyone have suggestions as to which board to use apart from Micro as it isn't too available here?

Due to the lack of USB-Support of the ATtiny85 you will be forced to use something like V-USB as the tutorial does. This might have implications when you are targeting a commercial product.

Personally I'd suggest using the ATmega32u4. It has USB build right in.

But basically I don't see any reasons why it should not work.


Which wireless technology should I use for medium range, many to one, bidirectional communication? Some clients, let's say 5 <= x <= 10, have to send information wirelessly to a server. Transmission does not need to be reliable (ACK).

The range would be between 50 and 100m, and may include soft obstacles like trees, cars, etc, but not major ones like whole buildings or concrete walls.

Also, as I plan to build about 20 clients, the price should be as low as possible.

Thoughts?

Depends on how much data you're sending, what packet structure you want to use, whether you want to spin your own PCBs or use a plug-in module, whether you need a low-power solution, etc..

For that distance, probably a sub-1GHz solution would work best.

I've had good results with the TI range of Value Line transceivers as they offload all the packet-handling, sync-words, CRC etc. from the microcontroller.  The modules also handle addressing, and have a "listen before talking" functionality - both of which could be useful with your physical architecture.

Down sides:

You'd probably need to spin your own PCB - they have good reference
designs.
No library for Arduino... but I'd personally rather use a
transceiver that manages all the low-level comms between the modules
so I can focus on the application.


Can stackable Arduino headers be automatically soldered? I want to design an Arduino shield with stackable headers, so it will allow other shields to be mounted on top of it.

I was wondering if these could be soldered automatically. Neither wave nor reflow soldering seems to be an option. Wave soldering would leave solder on the pins so they won't fit in sockets, and for reflow (pin-in-paste) the long pins will completely pull the paste from the holes.
Is hand-soldering the only way (making the board more expensive), or is there still another way? Would it be a good idea to supply the shield with the headers not mounted to save cost?
Or shouldn't I assume the average Arduino user has a soldering iron?

I would suggest using SMD headers on one side and through hole on the other side. One side with this: http://www.tracepartsonline.net/(S(30y0dp21y1rd0u3erv1mrrbw))/partdetails.aspx?Class=ASSMANN&ClsID=/F_ASSMANN/ASSMANN.010/ASSMANN.010.170/&PartID=10-18062010-079808
and one side with this: http://www.tracepartsonline.net/(S(30y0dp21y1rd0u3erv1mrrbw))/PartDetails.aspx?Class=ASSMANN&clsid=/F_ASSMANN/ASSMANN.010/ASSMANN.010.170/&ManID=ASSMANN&PartFamilyID=10-23062010-067691&PartID=10-23062010-067691&SrchRsltId=1&SrchRsltType=0

You will shift upper side a few mm from bottom side, and use glue to have upper side set in place and then reflow for soldering on both sides.


How to change colors and theme settings in 'Windows Store app' version of Arduino IDE? In the standard Windows (Win32) version of the Arduino IDE, theme settings like syntax coloring can be modified in C:\Program Files (x86)\Arduino\lib\theme\theme.txt.

For the Windows Store app version of the IDE the theme files are stored in protected app storage space.

Is there a simple/safe way to change theme settings for the Windows Store app version of the IDE without messing up security settings and inadvertently lowering Windows security?

(It would be easier and better if theme settings could be moved to the ArduinoData user folder where preferences.txt is stored.)

I think rrz0's answer skipped the part of the question:
"For the Windows Store app version of the IDE the theme files are stored in protected app storage space."

The only way is to take control of the windows app folder but I believe this is risky and M$ suggests that this can brick your pc (take that with a grain of salt).

There is an offline windows installer and zip link on the downloads page which I used to replace the windows store version. I see no advantage to the store version.


serial communication between arduino to 89c51 with gsm I need to connect the 89c51 with Arduino UNO but same time I need to connect 89c51 microcontroller with Arduino without using serial reception and transmission pins of UNO b'coz that pins already engage with GSM module. plz, suggest me the program solution to serially receive data from 89c51 and send the message to gsm module.

The Arduino Uno only has one (hardware) serial port. Since you need two, you have in principle two solutions:

Use a software serial, this will work only for low speed transmissions. You can download this as a library.
Use an Arduino (or other microcontroller) which has more than one hardware serial port, like the Arduino Mega which has 4.


Arduino Uno R3 cannot detect GPRS Shield SIM900 I am new to Arduino which I got only this week for my project which sends sms from my windows     application.
I have Arduino Uno R3 and GPRS Shield (Simcom) Sim900  (S2-1040S-Z0912)
I am currently following this guide > https://educ8s.tv/arduino-gsm-shield/
As of the moment I have problem connecting the Sim900 to Arduino (I think Arduino cannot detect Sim900). The Arduino is working properly as my PC detected it. Also I confirm that the SIM900 is working properly as I can call the Sim inside and it is ringing (also the led on the device is blinking almost every 3 secs or so)
I found this, but I'm planning to use USB powered only as I only need the SMS feature so I am stacking the SIM900 on top of the Arduino.
How to communicate the Arduino board with SIM900?
I am using this library http://www.tinyosshop.com/datasheet/GSM_GPRS_GPS_Shield_GSMSHIELD.rar
and below is the sketch:
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "sms.h"
SMSGSM sms;

int numdata;
boolean started=false;
char smsbuffer[160];
char n[20];

char sms_position;
char phone_number[20];
char sms_text[100];
int i;

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");

    if(started)
    {
        if (sms.SendSMS("214", "?15001"))
        {
          Serial.println("\nSMS sent OK.");
        }
        else
        {
          Serial.println("\nError sending SMS.");
        }
    }
};

void loop()
{
    if(started)
    {
        sms_position=sms.IsSMSPresent(SMS_UNREAD);
        if (sms_position)
        {
            Serial.print("SMS postion:");
            Serial.println(sms_position,DEC);
            sms.GetSMS(sms_position, phone_number, sms_text, 100);
            Serial.println(phone_number);
            Serial.println(sms_text);
        }
        delay(2000);
    }
};

and here is the output
Trying to force the baud-rate to 9600

1200
2400
4800
9600
19200
38400
57600
115200
ERROR: SIM900 doesn't answer. Check power and serial pins in GSM.cpp

status=IDLE

What I have tried so far:
I tried the sketch with SoftwareSerial mySerial(7, 8); and SoftwareSerial mySerial(9, 10) which i found on other tutorials but didn't work.
I tried modifying GSM.cpp and modify the value of _GSM_TXPIN_  and _GSM_RXPIN_  to 7, 8 and 9, 10 but didn't work.
Found that the pin on my Arduino is RX=0 and TX=1, and SIM900 is TX=0 and RX=1, tried the SoftwareSerial code above but with 0, 1 and GSM.cpp with 0, 1 but still not working.
I am currently still trying every other sketch i find on the internet but nothing works.
EDIT:
This is the link for the module i bought
https://www.lazada.com.ph/products/sim900-gsm-shield-i267689740-s379728457.html?mp=1
I cant find the link for the datasheet of this specific module so I will try to include the picture of the module

After many trials, I found the solution to my problem, thanks to @Majenko for mentioning the jumpers.
I am still stacking the SIM900 module on top of Arduino.
Switching the jumpers from D1 and D0 to D8 and D7 solved the problem (see green square on the pic)
I don't know why it needs to be on D8 and D7 since on board it says TX=0 and RX=1 and vise-versa for Arduino

Then used the below sketch from this tutorial > https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

With this, it displays correct output on serial monitor based on the tutorial and I can confirm that its working as well on my windows form application as it can send sms from the application.


How can I assign the value of a char array to a uint8_t array? I have a char array variable that has a value.
I need to send this value through LoRa. The library I use for the LoRa implementation accepts an array of uint8_t. How can I pass the value of a char[] to a uint8_t[] variable (and the opposite)?
if (Udp.parsePacket()) {
  int udp_received = Udp.available();
  char udp_buffer[udp_received + 1];
  Udp.read(udp_buffer, udp_received);
  udp_buffer[udp_received] = '\0';

  uint8_t udp_to_lora[] = "???";
  rf95.send(udp_to_lora, sizeof(udp_to_lora));
  rf95.waitPacketSent();

}

I need to pass the udp_buffer to uint8_t udp_to_lora[].

I don't have a compiler at hand, but you can cast the array  as a char and uint8_t are similar in size:
rf95.send((char*) udp_to_lora, sizeof(udp_to_lora));


Is my board broken by soldering? I've soldered a featherwing on my feather, then unsoldered it because it had stopped working: after the soldering of the featherwing, I was unable to upload new software to the board.

But now that the featherwing was removed, I still can't upload a software onto the board.

Here's the complete log I get:

$ ~/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/bin/avrdude -C~/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyUSB0 -b57600 -D -Uflash:w:/tmp/arduino_build_190205/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "~/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf"
         User configuration file is "~/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

I used to have this error from time to time before, but I always was able to make it work, either by using another USB port, choosing the right port for the arduino or rebooting Linux, but now nothing I do works.

So, I think I might have broken the board because of the soldering/unsoldering.

I attached the pictures of both sides of the board.

Three LEDs continue to blink: the red one when I connect the board to the USB, the battery one and the RX one when there is an attempt at transmission.

Can you tell me whether the board looks damage?

It looks like you have soldering paste all over the circuit board. If enough paste bridges a gap between the ceramic resonator and the IC, it can attenuate the oscillator signal to the point where the board won't work.

I use an old tooth brush and Isopropyl alcohol to clean excess soldering paste. As the alcohol evaporates, a lot of moisture forms on the circuit board, so it's important to ensure it's completely dry before you power it up.

Try cleaning the circuit board and see if that fixes the problem.

EDIT:

I would like to show you how much soldering paste it takes to stop a 328P from working. The following image shows the bottom of a perfboard with 0.1" hole spacing. You can see the soldering paste bridging the gap between pins 8, 9, and 10 of a Atmega328P DIP IC. Pin 8 is ground, and pins 9 and 10 are connected to the crystal / capacitors. All three pins are connected together via the paste, and since I forgot to clean the board before "final assembly", it's possible other pins are connected together via the paste.

The circuit board is from a "kitchen clock project", and was taken the day it stopped working. There are no mechanical connections to this circuit board except for the 328P's IC socket. This clock worked for 3 months, then it quit suddenly. I re-booted it once, it worked for an hour, then it quit again. The only factor that changed after the first three months was a change of seasons (the ambient temperature in the kitchen was reaching 90+ degrees F during the day). I don't know if the "blobs" of paste were touching each other when I assembled it, but they were when it failed. How does thick soldering paste start moving around on it's own? With some heat and Capillary action of course :)

Cleaning the board with Isopropyl alcohol fixed the problem, and the clock has been running for the past 6 months without issue.

EDIT 2

When I monitor pin 9 of a 328P on a 5V Arduino Uno, this is the waveform I see.

You can see the small amount of voltage change the oscillator has to make for the 328P to sense it, and function correctly (800mV peak to peak). If the soldering paste is conductive, capacitive or perhaps both, connecting this signal through the paste to ground, power or several other pins can disrupt the signal to the point where the IC fails to operate.


Bootloader difference between Atmel328p(through hole) and Atmel328p au(smd) It’s been bugging me lot that Can’t we burn the same bootloader for both 328p and 328p au?

I got confused when I see this linksmd 328p au bootloader burn.

Will there be any impact on performance or any other impact if I use same bootloader for both?

The bootloader doesn't care about how many pins the device has. All it cares about is the UART pins, and they are the same.

Internally the two chips are the same, it's just the packaging that is different. They take the same silicon chip and mount it on a different lead frame and encapsulate it in epoxy. Which is why the only pin differences are a couple of extra power and ground pins, and two dedicated ADC pins that they don't connect in the DIP package.  Even the pins are in the same order around the chip if you examine the pinouts in the datasheet.

Whether you use the DIP (Uno) or the SMD (Nano) bootloader it makes no difference (the two bootloaders are the same anyway). There can be no "perform better" anyway, since that isn't a valid concept. Either it is compatible, in which case it will work, or it's not, in which case it won't.

The only real thing of concern is to ensure that your fuses are set correctly for your chosen clock source, and that the bootloader you install is compiled to run at the speed of your chosen clock source. That has nothing at all to do with which chip it is you are using, but how you have designed your circuit.


Could I Connect many Arduino Nano boards together? I want to know if I could connect many Arduino Nano  boards together (Example : 10 boards ) , Also i want to know  if there is any problem in Communication between them  using I2C , could this affects processing speed on every board ,  and  if there's going to be any kind of delay when communicating?

I want to know if I could connect many Arduino Nano boards together...

Yes, you can read about it here at arduino.cc. Where is says: "...it can be helpful to set up two (or more!) Arduino ... boards to share information with each other..."

  ... i want to know if there is any problem in Communication between
  them using I2C ...

This feature, according to the above link, is expected to work.  (Can you explain the type of problems you are avoiding?)

  ...could [i2c communication] affect processing speed on every board ...

Most likely it will.  Most Arduino platforms do not run operating systems.  So your program is all that is running.  If your program is busy sampling sensors, it will be difficult (not impossible) to concurrently handle i2c communications.


How to power Arduino only when light is on I want Arduino to conserve energy and turn it on automatically only when the lights is on. Can I use some kind of light sensor and put it in between power supply and arduino somehow? Ideally light sensor will power from the same power source, if possible.
I'm not an electrical engineer - just enthusiast, so please explain your idea as detailed as possible. Many thanks!

For a chip like the basic Arduino's ATmega, you don't really "turn it off" to save power, rather you put it into a low-power sleep mode.

First, make sure you aren't consuming more power than needed normally.  Make sure unused peripherals like the ADC are off.  If your program spends most of its time waiting for external events, try reducing the clock speed either with a slower crystal or the 8 MHz oscillator, and with the clock prescale register.

Next, implement a sleep cycle.  Turn off everything you can, and program a hardware timer to generate an interrupt at some point in the future.  Enter sleep mode, so the processor stops and only the logic in the counter is still running.  When the interrupt fires, the ATmega CPU will wake up and continue operating, at which point you enable the ADC, use a GPIO to drive your light sensor, and take a reading from it.  If it doesn't meet your conditions, turn it all off again and go back to sleep until it's worth checking again.

In low power design you must be very careful of things outside the processor stealing power.  Watch out for any resistors pulling signals, if the signals are actively drive against the resistor.  LEDs are an obvious issue.  Also watch out for voltage regulators which may have high quiescent current.  And finally beware of peripheral chips - a stock Arduino has an entire second processor sitting there in the USB-serial adapter wasting power.  So you will either need to customize the firmware of that to shut down too, or else use a simpler board that doesn't have one (don't just hold it in hardware reset, as the reset pin has an internal pullup which will then consume power).


Leonardo - always on power, status remains between computer reboots? I'm looking for two answer here.

Is it possible to power a Leonardo to be always on, separate from the power from the USB host - I've tried with a full size Leonardo and a power adapter but for some reason the code didn't run when I did that. I've bought a battery shield too which will be arriving soon.
I want it be power-able via a switch with batteries so that I do a few things. For a start avoid it's boot up time and have it pressing a key as soon as the booted computer sees it (I'm running it as a keyboard/mouse via USB-HID) and also at one point I have the computer send serial data to have the Arduino run a different part of it's code...at this point the host computer reboots. Obviously that means the Arduino will see it's USB host disappear then come back online, will that automatically reset it and thus start it from the beginning again, or can I set it so that with always on power it will carry on doing what it is, irregardless of it's connecting to the host?

Do I need to change code, or libraries to achieve any of this?

With the theory intact answered, here is some of my actual code, i've stripped most of it out as it's just a bunch of keyboard presses

#include <Keyboard.h>
#include <Mouse.h>
char returnKey = KEY_RETURN;
char tabKey = KEY_TAB;
void setup() {
Keyboard.begin();
Mouse.begin();
// delay(60000); //Deploy Delay
delay(3000); //Testing Delay
// Keyboard commands
Keyboard.write(returnKey);
delay(14000);
// Welcome Screen
Mouse.click(MOUSE_LEFT);
delay(100);
}

void loop() {
}

Is it possible to power a Leonardo to be always on, separate from the power from the USB host

Yes, that is what the barrel jack is for.

  I've tried with a full size Leonardo and a power adapter but for some reason the code didn't run when I did that.

Then your code is wrong. Are you using while (!Serial); or something similar near the top of your code?

  For a start avoid it's boot up time

The most certain way of doing that is to not use the bootloader. Instead program the board directly with a hardware programmer disabling (or erasing) the bootloader.

  Obviously that means the Arduino will see it's USB host disappear then come back online, will that automatically reset it and thus start it from the beginning again, or can I set it so that with always on power it will carry on doing what it is, irregardless of it's connecting to the host?

The Leonardo only reboots if you open the serial port at 1200 baud, or toggle the RESET pin / button.

  Do I need to change code, or libraries to achieve any of this?

It sounds like you may need to, yes - since it's not working at the moment when if the code were correct it should work.

IMPORTANT

Most computers will not recognize the Leonardo until the operating system is fully booted. This means you cannot use the Leonardo to interact with the BIOS or boot menu. The Leonardo does not implement the "Boot Protocol" keyboard which is required to interact with the BIOS or other pre-boot environment.


ESP32 nodemcu serialbt sending data I'm currently trying to send data from esp32 to my android app that I made. The sensor readings are showing in the serial monitor, however, what's showing on my app are either @ or &. Please help and thank you. I'm new to bluetooth coding.
Here's the code:
#include "BluetoothSerial.h"
int sensorPin = 35;
int sensorreading;

BluetoothSerial SerialBT;

void  setup ()
{
    Serial.begin(115200);
    SerialBT.begin("ESP32_ABO");
    pinMode (sensorPin, INPUT);
}
void  loop ()
{
   sensorreading = analogRead(sensorPin);
   String toSend = String (sensorreading);
   sendData(toSend);}

void sendData(String textToSend){

   Serial.print(sensorreading);
   SerialBT.write(textToSend[sensorreading]);
}
delay(1000);}

You see very different output via bluetooth and Serial Monitor, because you are sending completely different things. On the Serial Monitor you see the sensor reading, since that is exactly, what you send:
Serial.print(sensorreading);

The print() function will convert the integer variable sensorreading into human readable text (meaning ASCII encoded text) and send this over Serial.
But then you do this:
SerialBT.write(textToSend[sensorreading]);

textToSend is a String object here. So with the parentheses [ ] you are taking one character of that string. You try to use the sensorreadingth character. Since sensorreading comes from an analogRead(), it is most likely, that is value is rather big, meaning bigger than the length of the string. So you are basically reading some random memory, that happens to lie behind your string variable. The write() function will then send that random data out over your bluetooth serial interface, without any conversion.
I guess you want to transmit the data over bluetooth also in human readable form. So just use the same code as with the Serial interface (for the Serial Monitor).
And remove all that manual conversion of the measured analog value to a String. That is not needed. If you want to also display some text, you can just use multiple print() commands, like this:
Serial.print("Value: ")
Serial.print(sensorreading);
Serial.print(" units");

Note, that it is rather bad to use the String object at all. The String class uses dynamic memory allocation, which leads to memory fragmentation, which can eat up your available memory. This is not as important on chips with rather big memory (as the ESP32) than on chips with smaller memory (like the Atmega328p, which is used in Arduino Uno and Nano), but you should still keep that in mind. Instead of the String class you would work with char arrays, aka C-strings.


Detection of DS18B20, arduino Mega I just bought a DS18B20 temperature sensor. I can't detect the device when i run this code :

#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into pin 10 on the Arduino
#define ONE_WIRE_BUS 10

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();
 }

 void loop(void)
{
  // call sensors.requestTemperatures() to issue a global temperature
 // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");

  Serial.print("Temperature for Device 1 is: ");
  Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
    // You can have more than one IC on the same bus.
    // 0 refers to the first IC on the wire

}

Here are my connections:

and output on Serial Terminal is:

      "Temperature for Device 1 is: -127.00 Requesting temperatures...DONE"

I also tried to detect the address of my device but with no success.
I am using an arduino Mega 2560, i have read in some forms that maybe it has something to do with Clock speed or something like that.

I appreciate your help.

I mainly followed this tutorial : http://www.hobbytronics.co.uk/ds18b20-arduino

In the Tutorial, which you are following, it says,

  So we will use the 2 wire method. Simply connect both the GND and VDD
  pins to 0V (yes both)

and it shows:

but I think you are missing this step, because i can't see any connection like that here: