Powering an USB to Serial from USB I am creating a PCB which is a modification of the Arduino on a breadboard. I am intending to buy an USB to Serial breakout from Adafruit so that I can upload my sketches to the atmega 328 I'll be using.

However, in order to reduce power consumption (later I want to run my circuit by using some AA batteries), I would like to turn off the USB to Serial breakout. I thought originally about adding a SPST switch to disconnect it when not using it, but I wonder if it is possible to power it from the USB (whenever I connect something) instead of having to connect its VCC header to the circuit's 5v power.

Is it possible to do that? Or is there any other way I to accomplish this that I'm not thinking of?

UPDATE: For clarity sake, I will explain my design choices: I want this circuit to power some peristaltic pumps that work on 12V. Thus, I'm providing 12V for the pumps and using a regulator to lower the voltage to the circuit. I don't see this is a huge problem for power consumption because the circuit will be in low-power 98% of the time, only waking up one minute per hour. Sometimes, it will run on batteries, which is the reason I wanna eliminate the USB-to-Serial. However, when connected to a power adaptor, I want the USB to be available.

All the best,

Francis

That is not easy to do. You could try diodes and mosfets as switches, but one way or the other, there will probably some leakage current. The 6N137 requires power for the receiving signal.
Other common optocouplers might have leakage current in the nA range for the transistor output. That might be possible. Connect the GNDs. The RX and TX via optocouplers. DTR to RESET with 100nF as usual. Maybe you don't need extra inverters when the transistor outputs are used as emitter followers.

Could you make your project with the ATmega328P without the usb-to-serial module ? The Arduino Pro Mini does not have a usb-to-serial either.
Now that I mention the Arduino Pro Mini: Instead of making an Arduino compatible circuit with a ATmega328P, you could also buy a Arduino Pro Mini 8MHz, and remove the voltage regulator and the power led. Then you have the same thing.

That breadboard Arduino tutorial has +5V connected to AREF. Please don't do that. Keep AREF open, or connect a capacitor of 100nF to it to reduce some noise for analogRead.

In the deepest sleep mode, the ATmega328P can run more than a year on three AA batteries. The timer of the WatchDog can be used to wake up.
The voltage of the three AA batteries is directly connected to the VCC of the ATmega328P, without voltage regulator.

A very good tutorial about power saving is this: Nick Gammon about power saving


Am I able to connect an anti static wrist strap to the ground pin on the Arduino uno? So you have the pin on the arduino uno which is ground, are you able to use a jumper wire to send the ground source out the other end of the wire to the alligator clip for the antistatic wrist strap?

I was about to write that I wouldn't do that, but in view of the post I linked to - I am changing my mind.

The point to the wrist strap it to have you, and the thing you are touching, at the same potential (whatever that is relative to the known Universe). Now if you connected the strap to the earth on your power point, that would not achieve anything unless your Arduino was also grounded (eg. via a USB cable).

So using the ground wire on the Arduino sounds sensible enough. Personally I don't usually do that, however if I have moved around (and might have shuffled over some carpet, etc.) I always touch some metal part to ground myself (for example, a metal switch on a lab power supply) and discharge any static that might have built up by moving around on the floor.


Arduino Uno Sensor DHT11 Failed to read from DHT sensor I get this error every time. I used the DHT tester file from this library. Which gives me an error.

And then I realized that in my code Arduino recognizes only the readTemperature function, not readHumidity, but it doesn't give any compile error. Also, when I read the sensor, this is the output:

  Humidity Sensor Test
  Temp: 0C, Humidity: 0%
  Temp: 0C, Humidity: 0%
  Temp: 0C, Humidity: 0%

My code is here:

//DHT11 Sensor:
#include "DHT.h"
#define DHTPIN 5 // which digital pin we're connected to
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

//I2C LCD:
#include <Wire.h> // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>

// Set the LCD I2C address
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup() {
  Serial.begin(9600);
  delay(300);
  lcd.begin(16,2);
  Serial.println("Humidity Sensor Test");
  dht.begin();
  delay(300);
}

void loop() {
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  int h = dht.readHumidity();
  int t = dht.readTemperature();

  // set the cursor to (0,0):
  lcd.setCursor(0, 0);
  // print from 0 to 9:

  lcd.print("Temp: ");
  lcd.print(t);
  lcd.print("C");

  // set the cursor to (16,1):
  lcd.setCursor(0,1);
  lcd.print("Humidity: ");
  lcd.print(h);
  lcd.print("%");

  Serial.print("Temp: ");
  Serial.print(t);
  Serial.print("C, Humidity: ");
  Serial.print(h);
  Serial.println("%");
  delay(2500);
}

Also I have the 10k resistor between data and Vcc pins. Data is connected to digital pin 5. Has anyone had this problem before?

There are several versions of the DHT11 library for Arduino out there. This is the one that worked for me: https://github.com/adidax/dht11. Here is a simple sketch to test the sensor with the output going to the serial monitor.

// 5k ohm pull up resistor is used on the data line.
// Sensor operates at 5VDC.
// Data line connects to Arduino Uno pin 3.

#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 3

// Sensor calibration. Start with 0 for each.
const int HumidityCorrection = -10;          // -10 worked with my sensor.
const int CelsiusTemperatureCorrection = 2;  // 2 worked with my sensor.

const float FahrenheitTemperatureCorrection = CelsiusTemperatureCorrection * 1.8;

// Update the serial display every 60 seconds.
const float UpdateSerialDisplay = 60000;

// Celsius to Fahrenheit conversion.
double Fahrenheit(double celsius){
  return 1.8 * celsius + 32;
}

void setup(){
  Serial.begin(9600);
  // Minimum wait for good data recommended is 1 second.
  delay(2000);
  Serial.println("DHT11 TEST PROGRAM ");
  Serial.print("LIBRARY VERSION: ");
  Serial.println(DHT11LIB_VERSION);
}

void loop(){
  Serial.println("");
  int chk = DHT11.read(DHT11PIN);
  switch(chk){
    case DHTLIB_OK:
      //Serial.println("OK");
      break;
    case DHTLIB_ERROR_CHECKSUM:
      Serial.println("Read sensor: Checksum error");
      break;
    case DHTLIB_ERROR_TIMEOUT:
      Serial.println("Read sensor: Time out error");
      break;
    default:
      Serial.println("Read sensor: Unknown error");
      break;
  }

  Serial.print("Humidity: ");
  Serial.print("\t");
  Serial.print(DHT11.humidity + HumidityCorrection);
  Serial.println(" %");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(DHT11.temperature + CelsiusTemperatureCorrection);
  Serial.println(" C");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(round(Fahrenheit(DHT11.temperature) + FahrenheitTemperatureCorrection));
  Serial.println(" F");

  delay(UpdateSerialDisplay);
}

Once you get this working you can add the LCD code to it. Here is a link to the DHT 11 Humidity & Temperature Sensor manual / data sheet: http://www.micropik.com/PDF/dht11.pdf


NRF24L01+ Getting Started Acknowledge Failed I have followed numerous guides and tutorials for getting the NRF24L01+ modules working with an Arduino Uno. I have swapped to a genuine Arduino and tried 4 different NRF modules. All without luck.

I am trying to get the most basic example from Simple nRF24L01+ 2.4GHz transceiver demo to work.

Hardware Connections:

Simple TX Test Code:

// SimpleTx - the master or the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[10] = "Message 0";
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    radio.stopListening();
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);

    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[8] = txNum;
}

Serial monitor:

Using radio.printDetails( ); returns:

Please let me know what I'm missing.

The Arduinos 3V3 does not privide enough current. To eliminate this as a source of your problem you can use a ceramic capacitor of 100µF across VCC and GND pins of the nRF24L01+ module or buy a 5V to 3V3 step down converter specially made for nRF24L01.


Power LED Matrix With LiPo Battery & ESP32 I want to power an ESP32 with a 3.7V LiPo battery. There's a LED matrix of 64 WS2812 LEDs attached to the ESP32. I learned that I need a buck boost converter to power the microcontroller as it needs a 5V power input. The boost converter delivers that when there is no matrix attached. However if the matrix is attached it only receives about 2.7V. Turning the potentiometer on the boost converter changes nothing in this case. What is the reason for this? I am sorry if this question seems basic to you. I am an beginner with electronics.
Here is a rather hideous scetch of the connections. I hope this is okay:

This is the buck converter I used: https://www.amazon.de/gp/product/B079H3YD8V/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1

The way you have it set up is fine if you aren't going to light up all the LEDs at full brightness. And if you do, you're not going to break your ESP32 Dev Board the way you have it set up in your diagram (since you are not running the power THROUGH the board). The LiPo battery probably has its own little regulator on it to prevent it from being damaged.
Check your dev board specifications on how much power you actually need to supply to the Vin pin. The ESP32 chip operates between 2.3 and 3.6 volts (3.3 recommended). Your dev board regulates the 5v to provide that amount to the chip.
Most likely, your dev board will run fine on the 3.7V provided by your LiPo without the buck-boost. I use a similar setup (without a buck-boost) to demo little projects to friends. I use a ESP32U-01 dev board from EZSBC, a 64 LED Matrix from Adafruit, and a 3.7v LiPo battery.
Depending on how many LEDs are lit (and what color), you shouldn't expect the battery to last very long. And the overall brightness of your led matrix will be limited.
If you are using the FastLED Animation Library, I would recommend setting a power limit using set_max_power_in_milliwatts function and limiting it to 1500mW for starters. Again, if you are not drawing power THROUGH the ESP32 board, you're fine.


WiFiClient.connect() does fail all the time (ESP8266 Core for Arduino) I have one ESP(1) opening an AP and running a server on it. The other ESP(2) is running a client on it and is connecting to the AP and after that trying to connect to the host server. The connection to the AP does succeed but the connection to the host always fails and I cannot figure out what the problem is here. Testing the server via netcat and packetsender works fine. Connecting to it via telnet fails because the connections gets closed by the "foreign host".

Server Sketch

#include <ESP8266WiFi.h>

const char* ssid = "artex11";
const char* pw = "getmenow11";
WiFiServer server(80);
WiFiClient client;

void setup() {
  Serial.begin(115200);
  //setup AP
  WiFi.softAP(ssid, pw);
  Serial.println("AP started at: ");
  Serial.print(WiFi.softAPIP());
  server.begin();
  Serial.println("Server started...");
}

void loop() {
  client = server.available();

  if(client){
    Serial.println("Client connected!");
    Serial.print("HasClient: ");
    Serial.println(server.hasClient());
    char message = client.read();
    Serial.printf("Message: %c\n", message);
  }
}

Client Sketch

#include <ESP8266WiFi.h>

const char* ssid = "artex11";
const char* pw = "getmenow11";
const char* host = "192.168.4.1";
const int port = 80;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pw);
  Serial.println("Connecting to AP");
  while(WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
   }
  Serial.println(" connected");
}

void loop() {
  WiFiClient client;
  Serial.println("Connecting to host");
  if(!client.connect(host, port)){
    Serial.println("...connection failed!");
    Serial.println("Retrying in 5 seconds...");
    delay(5000);
    return;
  }
  client.print("A");
  Serial.println("...TCP message fired!");
  delay(2000);
}

If the server has a default IP address of 192.168.0.1 and the client has an IP address of 192.168.4.1 my guess is they won't be able to talk because you are using a 24 bit mask.

The subnet mask defines the number of bits that makes up the subnet, so if you were using the two addresses above and had a mask of 255.255.255.0 or 24 bits then the subnets you were using would be 192.168.0 and 192.168.4.  To cross subnets you need some form of routing process (usually a router, switch that can route, etc).

So you need to either change the mask or, stick both devices on the same subnet.
(Don't rely on defaults, when they change your code breaks)


DHT22 Does not update Good evening :)

I am fairily new to coding the fabulous Arduino UNO. My project right now are consisting of reading Temperature from a DHT22 (AM2302) and writing to a 4-digit 7-segment display. I have got the display to work, but the system does not update the temperature at all. Just the first reading are displayed

#include <DHT.h>
  #include <TimerOne.h>
  #include <SevenSeg.h>

  #define DHTPIN 4    //Defines the temp-pin

  /* DHT22- Pin1 (left) - 5V/3.3V
  Pin2- DATA
    Connect a 10K res from pin1 to pin2
  Pin3 - NC
  Pin4 - GND
  */

  //#define DHTTYPE DHT11   // DHT 11
  #define DHTTYPE DHT22   // DHT 22  (AM2302)
  //#define DHTTYPE DHT21   // DHT 21 (AM2301)

  DHT dht(DHTPIN, DHTTYPE);

  SevenSeg disp (13 ,2 ,3 ,8 ,5 ,6 ,7);
  //            (11, 7, 4, 2, 1, 10, 5)
  const int numOfDigits =4;
  int digitPins [ numOfDigits ]={9,10,11,12};  // uten transistorer
  //                            (12,9,8,6) Alle med 220 Ohm seriemotstand
  //int digitPins [ numOfDigits ]={12,11,10,9};  // med transistorer

  void setup ()
  {
    Serial.begin(9600);
    Serial.println("DHT22");

    disp . setCommonCathode();  // uten transistorer
    //disp . setActivePinState(HIGH,HIGH);  // med transistoere
    disp . setDigitPins ( numOfDigits , digitPins );

    Timer1.initialize(15);   // 0.015 sek
    Timer1.attachInterrupt(loop);
  }

  void loop() {

    dht.begin();

    delay(300);
    float t = dht.readTemperature();

    disp.writeFloat(t);
    Serial.println(t);

  }

How do I get the Sensor to update regularly?

Try moving dht.begin(); to setup().

The DHTs are pretty slow and need some time (of the order of seconds!) between consecutive reads. In dht.begin() an internal timer is reset that is used in readTemperature() to ensure that reading data from the DHT is not attempted in shorter intervals than supported. By calling dht.begin() every 300 ms you're making this meachanism inoperative. You're supposed to call dht.begin() only once at start-up.

Edit: And please also remove the Timer1 that calls loop. loop is already an infinite loop, so no good in calling it additionally from an interrupt...


I've been working on a project and I get an error compiling for board arduino uno. kindly help ##include <jm_LiquidCrystal_I2C.h>

#include <LiquidCrystal.h>

#include <Wire.h> // For I2C
//Set the pins on the I2C chip used for LCD connections
//ADDR,EN,R/W,RS,D4,D5,D6,D7
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7); // 0x27 is the default I2C bus address of the backpack-see article

#define echoPin 3 // Echo Pin (OUTPUT pin in RB URF02)
#define trigPin 2 // Trigger Pin (INPUT pin in RB URF02)

int led = 5;
int maximumRange = 350; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int brightness;

void setup() {
  lcd.begin (16, 2); // 16 x 2 LCD module
  lcd.setBacklightPin(3, POSITIVE); // BL, BL_POL
  lcd.setBacklight(HIGH);
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  // The following trigPin/echoPin cycle is used to determine the distance of the nearest object by bouncing soundwaves off of it.
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58, 2; //Calculate the distance (in cm) based on the speed of sound.
  lcd.home (); // Set cursor to 0,0
  lcd.print("The Water Level is");
  lcd.setCursor (0, 1);
  lcd.print(distance); // Custom text
  lcd.print("cm");
  Serial.println(distance); // distance in cm
  brightness = map(distance, 1, 100, 0, 255);
  analogWrite(led, brightness);
  delay(1000); //Delay 50 ms

#include <LcdKeypad.h>

#include <LiquidCrystal.h>

#include <Wire.h> // For I2C
//Set the pins on the I2C chip used for LCD connections
//ADDR,EN,R/W,RS,D4,D5,D6,D7
LcdKeypad lcd(0x3f, 2, 1, 0, 4, 5, 6, 7); // 0x27 is the default I2C bus address of the backpack-see article

#define echoPin 3 // Echo Pin (OUTPUT pin in RB URF02)
#define trigPin 2 // Trigger Pin (INPUT pin in RB URF02)

int led = 5;
int maximumRange = 350; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int brightness;

void setup() {
  lcd.begin (16, 2); // 16 x 2 LCD module
  lcd.setBackLightOn(3); // BL, BL_POL
  lcd.setBacklight(HIGH);
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58, 2; //Calculate the distance (in cm) based on the speed of sound.
  lcd.home ();
  lcd.print("The Water Level is");
  lcd.setCursor (0, 1);
  lcd.print(distance);
  lcd.print("cm");
  Serial.println(distance);
  brightness = map(distance, 1, 100, 0, 255);
  analogWrite(led, brightness);
  delay(1000);
}


Cannot set Pins to LOW I am controlling 2 motors from my Arduino Pro Mini and L293D motor driver module. Problem is, I have to set a pin high and after 1 second set it to LOW. But that doesn't happen... The pin just stays HIGH and is never LOW.

Here's my Code -

    int IN2Left = 10;
    int E1 = 12;
    int E2 = 7;
    int IN3RevRight = 6;
    int trigPin1 = A0;
    int echoPin1 = A1;
    int distance1 = 0;
    int IN4Right = 5;
    int IN1RevLeft = 11;

    void setup()
    {
      pinMode(IN2Left, OUTPUT);
      pinMode(E1, OUTPUT);
      pinMode(E2, OUTPUT);
      pinMode(IN3RevRight, OUTPUT);
      pinMode(IN4Right, OUTPUT);
      pinMode(IN1RevLeft, OUTPUT);
      pinMode(trigPin1, OUTPUT);
      pinMode(echoPin1, INPUT);
      pinMode(13, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(E1, HIGH);
  digitalWrite(E2, HIGH);
  digitalWrite(IN2Left, HIGH);
  digitalWrite(IN4Right, HIGH);
  delay(3000);
  digitalWrite(IN4Right, LOW);
  digitalWrite(IN3RevRight,HIGH);
  delay(500);
  digitalWrite(IN3RevRight, LOW);
  digitalWrite(IN4Right, HIGH);
  delay(1500);
  digitalWrite(IN2Left, LOW);
  digitalWrite(IN1RevLeft, HIGH);
  delay(500);
  digitalWrite(IN1RevLeft, LOW);
  digitalWrite(IN2Left, HIGH);
  delay(100000);
    }

The IN2Left Pin never goes LOW... I am assuming a faulty Arduino but my Arduino seems to be working just fine as it runs other stuff (tested blink and reading an Ultrasonic sensor) just fine.

My deadline is 2 hours from now...

EDIT: Here's the complete void loop function... Note the two pins on top which go HIGH? They Never go LOW again in the entire code.

Your code sets it high, delays for 1000ms, sets it low, and then... turns around and sets it high almost immediately after. Try delaying in between.


Why declare analog pins as ints? I often see code like this:

const int piezo = A0;
const int sensorPin = A1;

From my understanding, an int variable can hold things like -123, 0, 1, 456, etc.

How can A0 or A1 be an int?

The board definition (pins_arduino.h) has this:

static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Since A0 is a constant variable equal to 14, if you assign that to a variable, it just assigns 14.

In other words:

A = 14.
B = A.
Therefore B = 14.


Error while installing bootloader ATmega328 I'm trying to install a bootloader on my ATmega328P-PU. I'm trying to install it from Arduino Uno (not original). I can install all sketches. After I click "Burn bootloader" I get the following error:

Arduino:1.6.11 (Windows 10), Board:"Arduino/Genuino Uno"

avrdude: Yikes!  Invalid device signature.
avrdude: Expected signature for ATmega328P is 1E 95 0F
 ***failed;
avrdude: verification error, first mismatch at byte 0x0000
         0x00 != 0x3f
avrdude: verification error; content mismatch
Error while burning bootloader.

How to fix it?

EDIT: First ensure that you have made the hardware correctly (see comment below this post).

If you need different settings for custom avr hardware the following will help:-

The best way to create a custom board definition is to create your own boards.txt entry in the Arduino custom hardware folder.

But less effort to learn is to try to temporarily change or add to the Arduino IDE avr board definitions.

The board definition (properties) are passed to the tool that burns the bootloader. All board specific properties are provided by the boards.txt

Edit the [ArduinoIDE\Hardware\hardware\arduino\avr\boards.txt with a text editor and find the Uno section.

It looks like this. Notice the mcu, vid, pid and uno.bootloader.file= settings in particular. The bootloader points to a file in [ArduinoIDE\Hardware\hardware\arduino\avr

uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

You can add a new entry like this. The example uses a board prefix of uno2. but it can be any simple unique name.

Save the changes to boards.txt then restart the Ide:-

uno2.name=Arduino ATmega328P-PU

uno2.vid.0=0x2341
uno2.pid.0=0x0043
uno2.vid.1=0x2341
uno2.pid.1=0x0001
uno2.vid.2=0x2A03
uno2.pid.2=0x0043
uno2.vid.3=0x2341
uno2.pid.3=0x0243

uno2.upload.tool=avrdude
uno2.upload.protocol=arduino
uno2.upload.maximum_size=32256
uno2.upload.maximum_data_size=2048
uno2.upload.speed=115200

uno2.bootloader.tool=avrdude
uno2.bootloader.low_fuses=0xFF
uno2.bootloader.high_fuses=0xDE
uno2.bootloader.extended_fuses=0x05
uno2.bootloader.unlock_bits=0x3F
uno2.bootloader.lock_bits=0x0F
uno2.bootloader.file=optiboot/optiboot_atmega328.hex

uno2.build.mcu=atmega328p
uno2.build.f_cpu=16000000L
uno2.build.board=AVR_UNO
uno2.build.core=arduino
uno2.build.variant=standard

note: make a copy of the .txt or grab a new one from the zip on arduino.cc if you mess it up.


Counting pulses with interrupt I have been trying to count pulses from a 12,500 Hz square wave to trigger an output. Here's the code I have so far. When the Arduino is reset it prints 315 to the serial over a 25 ms sample. 315 x 40 = 12600. Which seems to me it's working perfectly.

My only problem is it only returns this number once upon reset of the board. Now if I move that same code down into void loop, it counts consecutively giving me inconstant returns.

I am not understanding what I need to put in the loop section so I can repeatedly and accurately count how many toggles of the input pin I am getting over a period of time so I can do something to the output based off the presence of the 12,500 Hz signal or not.

volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
   // Put your setup code here, to run once:
  Serial.begin (9600);
  attachInterrupt(pin_irq, IRQcounter, RISING);
  delay(25);
  detachInterrupt(pin);
  Serial.print(F("Counted = "));
  Serial.println(IRQcount);
}

void IRQcounter() {
  IRQcount++;
}

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

Using the above code, every time I press the reset button I get one line in the serial window.

Counted = 441
Counted = 442
Counted = 441
Counted = 441
Counted = 441

Now I want to get the same result, but repeating over and over. That way if the signal drops out I can trigger an output to turn off (LOW). When the signal is present the output will go high.

My attempt was to move the attach interrupt down into void loop, so it would repeat. Here's what it looks like.

volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
  // Put your setup code here, to run once:
  Serial.begin (9600);
}

void IRQcounter() {
   IRQcount++;
}

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

  attachInterrupt(pin_irq, IRQcounter, RISING);
  delay(25);
  detachInterrupt(pin);
  Serial.print(F("Counted = "));
  Serial.println(IRQcount);
}

The return I get is self-updating, but the "count" instead of starting from 0 each time starts from the previous count. So it gets larger and larger. I am looking to return a constant value that represents my 12500 Hz signal so that, and only that, will trigger my output.

Counted = 442
Counted = 886
Counted = 1330
Counted = 177
Counted = 2221
Counted = 2667
Counted = 3112
Counted = 3557
Counted = 4002
Counted = 4448
Counted = 4893
Counted = 5338
Counted = 5784
Counted = 6229
Counted = 6674
Counted = 7120
Counted = 7565
Counted = 8010
Counted = 8456
Counted = 8901
Counted = 9347
Counted = 9792
Counted = 10237
Counted = 10683
Counted = 11130
Counted = 11576
Counted = 12022
Counted = 12469
Counted = 12915
Counted = 13361
Counted = 13808
Counted = 14254
Counted = 14700
Counted = 15147
Counted = 15593
Counted = 16040
Counted = 16486
Counted = 16932
Counted = 17378
Counted = 17825
Counted = 18271
Counted = 18717
Counted = 19164
Counted = 19610
Counted = 20056
Counted = 20503
Counted = 20949
Counted = 21395
Counted = 21842
Counted = 22288
Counted = 22735
Counted = 23169
Counted = 23616
Counted = 24062
Counted = 24508
Counted = 24955
Counted = 25401
Counted = 25730
Counted = 25756
Counted = 26200
Counted = 26646
Counted = 27093
Counted = 27539
Counted = 27985
Counted = 28432
Counted = 28878
Counted = 29324
Counted = 29770
Counted = 30217
Counted = 30663
Counted = 31110
Counted = 31556
Counted = 32002
Counted = 32449
Counted = -32641
Counted = -32195
Counted = -31748
Counted = -31302
Counted = -30855
Counted = -30408
Counted = -29962
Counted = -29515
Counted = -29069
Counted = -28622

You need to reset IRQCount back to 0 before attaching the interrupt again. Otherwise it will just continue counting from where it stopped last time.

I would actually keep the interrupt attached and just reset the variable just before the delay. That way the overhead of attach/detachinterrupt doesn't get added to the 25ms delay.

volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  attachInterrupt(pin_irq, IRQcounter, RISING);
}

void IRQcounter() {
  IRQcount++;
}

void loop() {
  // put your main code here, to run repeatedly:
  IRQcount = 0;
  delay(25);
  int result = IRQcount;
  Serial.print(F("Counted = "));
  Serial.println(result);
}

Since an int is 2 bytes an interrupt might occur in the middle of setting/reading those two bytes. This might result in an occasional wrong value. To prevent that you should disable interrupt while setting/reading the value

volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  attachInterrupt(pin_irq, IRQcounter, RISING);
}

void IRQcounter() {
  IRQcount++;
}

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

  cli();//disable interrupts
  IRQcount = 0;
  sei();//enable interrupts

  delay(25);

  cli();//disable interrupts
  int result = IRQcount;
  sei();//enable interrupts

  Serial.print(F("Counted = "));
  Serial.println(result);
}


Arduino IDE 2.0 Beta doesn't start Yesterday i downloaded the new version of the IDE to take advantage of all the new features, but it just won't open. I tried installing it to different paths, different PC's, i deleted the package_index.json and the cache folder, but nothing. It stucks in the opening screen (see image below), any other ideas?

I have a very slow internet connection and the Arduino IDE seems to depend a lot on it. When I launch it, I shut down internet and it opens in a breeze.


Serial Error Correction I currently have a setup where I take serial output from Arduino 1 and push it through a transmitter to the receiver of Arduino 2 where it is fed back into the serial input and further processed. I want to ensure that there is as little error as possible and recover the data wherever possible.

I have come across the syndrome decoding technique which seems to be the ideal one for me, but I am confused as to how I would go about implementing it.

I know that the Arduino Serial transfers data byte by byte, each being 8 bits, but do not know how this data is sent over the serial connection (i.e. how the start & stop bits & parity is implemented).

I would assume that a solution to this could either involve modifying the data in the buffer or reading it from the buffer and then operating upon it. I could also use adjacent bytes of data for error correction, but this seems wasteful.

How should I proceed with this?

Welcome to the wide world of Communications.  You are asking about "Error Detection and Correction".  This is different from "framing", which allows you to determine when a message starts and ends.

With "error detection", you know there was an error, but you can't necessarily recover from it.  With "correction", you know there was an error and you can determine what was originally sent.

This always requires extra bytes.  There are many schemes, but the Fletcher checksum for Error Detection is easy to implement, fast, and only requires 2 extra bytes in the message (4 if hex digits).

The generic approach is to use a finite-state machine.  In complicated message protocols, there would be nested state machines: the inner-most would probably determine framing, the next one out might looks at addressing, etc.  Any or all of those layers could use Error Detection and/or Correction.

For your simple "protocol", a single state machine is probably sufficient.  The states might be IDLE, RX_PAYLOAD and RX_CS.  As characters are received, they are processed according to the current state and occasionally change the state variable.

while (Serial.available()) {
  uint8_t c = Serial.read();
  switch (state) {
    case IDLE:
      if (c == MSG_START)
        state = RX_PAYLOAD;
      break;
    case RX_PAYLOAD:
      if (c == MSG_END) {
        state = RX_CS;
        cs = 0;
        csCount = 0;
      } else if (length < MAX_LENGTH-1) {
        msg[ length++ ] = c;
      }
      break;
    case RX_CS:
      //  Add in the next hex CS digit
      cs = cs * 16 + fromHex(c);
      if (++csCount == 2) {
        // both digits received, see if the CS matches
        if (cs == csOfMsg( msg, length )) {
          // Handle the message
          msg[ length ] = '\0';
          Serial.println( msg );
        } else {
          Serial.println( F("Bad message!") );
        }
        state = IDLE;
      }
      break;
  } // end switch
} // end while

There are entire books written on protocols and their design.  This is just a made-up example to give you an idea of how it should be structured: a finite state machine, driven by received character "events".

Sometimes you can compute the checksum as the characters are received, like Fletcher.  Here, it waits until the entire message plus 2 CS bytes are received.


In what situation would the Vin pin be attached to any of the I/O pins? In what situation would the Vin pin be attached to any of the I/O pins?

Also, in what situation would the Vin pin be attached to an external circuit?

Vin is exactly the same as using the barrel jack (DC in) on the Arduino.  You can use it when you want to power your Arduino from an external source and you don't want to have the bulk of a big power plug.  It can also be used as a power output when you are using the barrel jack, for instance for powering relays or motors.  It just saves on having to splice wires into the cable of a wall wart, for example.

The voltage you feed in to the Vin pin should be of the same specification as the barrel jack - that is, between 7 and 12V.  From there, just like the barrel jack, it goes to the 5V regulator to provide the 5V for the board, and then on to the 3.3V regulator for low powered peripherals.

If, at any time, you power the board from the USB and have something connected to the Vin pin that consumes power you risk damaging the 5V regulator on the Arduino since power will flow backwards through it form 5V to Vin, which it really isn't meant to do.  In these situations it is good to connect a diode between 5V and Vin such that the anode is on 5V and the cathode on Vin - so that if the 5V is higher than the Vin voltage then the current will bypass the regulator safely.


How much current needed to power arduino uno? I am planning to build an rc car based on arduino uno. I will use 3S 11.1 V Li-po to power whole circuitry. So my question is;

First, can arduino be powered directly with 11.1V from its Vin pin? Would it be a problem or not? If it is OK, then no need to answer the bold part below.

If it is not, then one solution comes to my mind is to use a voltage regulator which will convert 11.1 V to 5 V. But while choosing a regulator, I saw that max output current is one of the important specs. So what is the minimum amount of current needed to run Arduino UNO?

The maximum voltage at the Vin pin is 12V, so using your battery is fine!

Considering the current consumption:
The arduino itself will usually source less than 200mA, but your whole setup will probably sink more than that.


What is a safe way to power arduino nano with 7.4V Lipo battery? I'm trying to power Arduino Nano with 7.4V LiPo battery and use it to run 2 DC motor using L293D. I have figured out how power it with the connection just like in the figure below(the diagram uses Uno and the battery is 9V but try to imagine it as Nano and 7.4V).  I also found another way to power it by connecting the red wire from battery to Vin on the Arduino instead of connecting it to the positive power rail.

So, my question is which is a safer way to power it and what is the difference and risk of one the way I mention.

Connect it via the Vin pin. That way the 6-8.4 volt of the battery will go through the voltage regulator on the Nano, giving you a stable 5v.

What you show in your diagram is the wrong way of connecting the battery. The absolute maximum you can supply to the Arduino's 5V pin is 6 Volt. Atmel recommends no more than 5.5V. So your battery exceeds this when it's full.


Can a video game potentially detect arduino leonardo? If I automated an action in a video game through arduino leonardo, can it be detected? Things like autohotkey can be easily detected, however i would expect an arduino would be far more difficult. How easy/difficult would it be detect?

Yes.

First you'll need to define how you plan to inject the new input signal, into the data "packets" as a spoof of controller signals, or just jumping the switches?

In the context of any modern gaming console, it could be detected. Easily. Consoles and controllers use any number of proprietary protocols which sync.commands to improve response and reduce controller lag. If you're just jumping the switches, then no, you could simulate hadouken and probably get away with it just fine.

If you're referencing PC gaming, then that would be hard if not impossible with the variance of input control available.  The best deterrent would be the security of the game software itself and the genre of the gaming. Some games actively encourage Hotkeys.


Odd symbols in ESP8266 responses to AT commands I used the code below to control an ESP8266.  I am getting some unknown symbols in the responses.

#include <SoftwareSerial.h>
const byte rxPin=2;
const byte txPin=3;
SoftwareSerial ESP8266( rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200);
  delay(1000);
  // put your setup code here, to run once:

}

void loop() {
  Serial.println("sending an AT command");
  ESP8266.println("AT");

  delay(100);
  while(ESP8266.available())
  {
    String inData = ESP8266.readStringUntil('\n');
    Serial.println("Got Response:" + inData);
    delay(1000);
      ESP8266.println("AT+RST");
    }
  // put your main code here, to run repeatedly:

}

The unknown symbols are shown in the screen shot.

What might the problem be?

I nutted over this for quite a while. If you look up the reference for SoftwareSerial - https://www.arduino.cc/en/Reference/SoftwareSerial - and look at the limitations, you'll find that it won't work above 57k baud rate and pins 2 and 3 wont support change interrupts, whatever they are.  Sometimes I think some of these projects are untested.  I think I'll use the hardware ports on two arduinos and use SoftwareSerial on the right pins and baud rate to get the two arduinos to communicate, or use Software serial to talk to the pc through a MAX232.  I don't think you'll get a 115200 baud esp to talk SoftwareSerial


Connecting Peltier module to Arduino Nano I am a beginner to Arduino programming and started working on my first Arduino project recently to power a Peltier cooling pad. Below is the code I used and in the circuit,
I connected the positive (red wire) end of the Peltier to D12 of Nano Arduino board and the negative end( black wire) to the negative end of the 6V battery. Then I powered the Arduino board by connecting Vin(Arduino) and battery(+) using a jumper wire. The GND pin of the Arduino was connected to the battery(-) using a jumper wire.

The Peltier is not working and it would be a great help if someone can help me to understand what I did wrong.

int p=12;

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

void loop() {
   digitalWrite(p,HIGH);
   delay(2000);
}

I prepared a little circuit that should help you safely connect the Peltier module to Arduino. It uses a single n-channel MOSFET and 1K resistor.

I couldn't find any Peltier in Tinkercad so instead I used a simple light bulb. (In previous version of this answer I used a DC motor, but it was not a good replacement for Peltier module)

When Arduino Pin12 is HIGH light is bright (high current flows through it just like it should through the Peltier) when Pin12 is LOW light bulb goes dark (no current is flowing)


How to control 6 stepper motors with Arduino? I would like to control 6 stepper motors (0.225A, 2 V) with Arduino. I was thinking to use motor drivers from Pololu website, for example DRV8834.

Is it possible?

Any suggestion for another type of motor driver?

We need to limit the current, but I also got the advice to use the PWM signal to control the stepper motor. Any advice for this?

Yes it is possible, of course everything is possible!

These drivers need two IO lines at very minimum: DIR and STEP. Pulsing STEP makes one step movement forward or backwards (depending on DIR).

For 6 steppers you need therefore 12 outputs from Arduino. (Which Arduino please? pick one which has enough IO, or otherwise use an I2C output extender).

M0 and M1 controls microstepping mode - configure at your wish. CFG is high on this Pololu board, allowing the board to use as a stepper driver out of the box.

Steppers (if you want to get them working at full torque) require a constant-current drive. (Inexpensive solutions use a constant voltage drive, such as using an ULN2803 - however those can not get too much torque). Happily this driver can do this well, the potentiometer sets the maximum current.

Steppers need considerable current when starting movement to a next step. However, unlike DC motors, even a still position will consume current, which eventually makes the motor hot. Therefore you are supposed to limit the current when the motor is not moving. This is usually done from software (the driver does not known when it is time for a long period at stop).

The way for limiting motor current at stop can be either an analog limiter, or a PWM. This driver has no dedicated input for this purpose. You can do two things:

use smaller drive current (use the potentiometer) - this can work well if you're satisfied with the torque
use the sleep mode of the driver with a PWM from the Arduino side.

This latter solution needs you to:

connect all EN pins of all 6 drivers, and connect it to one Arduino pin which has PWM (i.e. analogWrite())
drive this to 0, then start movements
once movements are finished, use analogWrite() and set to say, 128 (usually half of the move current is a good guess for holding current)

This way when the motors are stopped, the holding current will be less, hence the motors don't get hot.


message received from GSM contains parenthesis instead of curly braces the GSM code i have been working out is up and running, I use JSON format in sending the data obtained by my sensors, but the JSON message I have been receiving contains parenthesis instead of curly braces.

One or both of your GSM endpoints is incapable of handling ESC prefixes according to GSM 03.38. The only difference between "{" and "}" and "(" and ")" is that the former are signified by a preceding ESC which either is not being generated by the sender or is not being interpreted by the receiver.


Link Arduino Uno to Particle Photon I'm working on a prototype with a Particle Photon, but I've realized the required number of pins is bigger than the number of pins on my photon.

I thought I could have an Arduino Uno wired to some sensors, and link the Arduino to the photon via a Software Serial from the Arduino (as its serial pins will already be busy) to the Serial pins of the photon.

Is it possible, and is there a better way to solve my problem?

If you just need to get more inputs you could use multiplexing. The multiplexing method is more robust than software serial will be. How to do this is explained here and datasheet for the commonly used cd4051 here

You don't specify what kind of sensors you will use. if the sensors are i2c or similar it is possible to daisychain (multiplex too) them.


pcDuino 3B Wire library errors I recently purchased a pcDuino 3B and I am very pleased with the Board so far. I can use the preinstalled arduino IDE to program the board from the board and run programs.

However, when I came to use I2C, it generated a load of errors with the built-in libraries when I tried to compile. I don't know why it did this, it does it when trying to compile any program using I2C. Here is the error list (Yes, I am using an Adafruit display library that works fine with exactly the same sketch on my laptop):

In file included from /usr/share/arduino/hardware/arduino/pcduino/cores/arduino/Stream.h:26:0,
                 from /usr/share/arduino/hardware/arduino/pcduino/libraries/Wire/Wire.h:9,
                 from Stopwatch_new.ino:1:
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/Print.h:47:23: error: ‘byte’ has not been declared
In file included from Stopwatch_new.ino:1:0:
/usr/share/arduino/hardware/arduino/pcduino/libraries/Wire/Wire.h:41:23: error: ‘byte’ has not been declared
Stopwatch_new.ino:5:51: error: cannot allocate an object of abstract type ‘Adafruit_RGBLCDShield’
/home/ubuntu/Arduino/libraries/AdafruitLCD/Adafruit_RGBLCDShield.h:68:7: note:   because the following virtual functions are pure within ‘Adafruit_RGBLCDShield’:
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/Print.h:47:17: note:  virtual int Print::write(int)
Stopwatch_new.ino:5:23: error: cannot declare variable ‘lcd’ to be of abstract type ‘Adafruit_RGBLCDShield’
/home/ubuntu/Arduino/libraries/AdafruitLCD/Adafruit_RGBLCDShield.h:68:7: note:   since type ‘Adafruit_RGBLCDShield’ has pure virtual functions
Stopwatch_new.ino: In function ‘void updateScreen()’:
Stopwatch_new.ino:125:27: error: call of overloaded ‘String(float&, int)’ is ambiguous
Stopwatch_new.ino:125:27: note: candidates are:
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/WString.h:44:14: note: String::String(unsigned int, unsigned char)
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/WString.h:43:14: note: String::String(int, unsigned char)
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/WString.h:42:14: note: String::String(unsigned char, unsigned char)

It seems that no one else is having this issue.

Just to clarify, the issue is not with my code or the library, it compiles fine on my other computer running WINDOWS but same Arduino version (1.5.3), same sketch code and same library code.

Help much appreciated, thanks!

It turns out that the libraries for compiling were incomplete. Having copied the libraries for the official IDE, it worked fine.


The LCD doesn't display the words typed I've tried this code on an LCD, and instead of displaying "Hello World!" it displays what is shown on the picture.

Code:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
}

void loop() {
  lcd.print("Hello World!");
  delay(500);
  lcd.clear();
  delay(500);
}

Try the following

Double-check the LCD soldering
Double-check your wiring
Ensure that the pins you are using for your LCD are not assigned to some other function. This caused jumbled, random characters here.


Setting ESP8266-01 up with AT commands I am facing for the first time with the ESP8266-01 module, so sorry if will write any stupid things.
I bought this module and I wanted to check its parameters through AT commands. Following some guide and wiring schemas found on the web I finally hook the ESP8266 up with an Arduino Uno (as in the picture below. The resistors are 220ohm each and the capacitor is 100uF) in order to print out to the serial monitor the AT commands and responses.
I uploaded the following code to Arduino Uno:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(6, 7);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Started");

  // set the data rate for the SoftwareSerial port
  esp8266.begin(57600);
  esp8266.write("AT\r\n");
}

void loop() {
  if (esp8266.available()) {
    Serial.write(esp8266.read());
  }

  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

But when I open the serial monitor (with both NL and CR selected and baud rate set to 9600) I got no response!!
If I try to send simple AT or AT+GMR commands, it returns to me nothing or random characters.
Does anyone please could tell me what I am doing wrong?

We faced similar problems when using ESP8266 for the first time, Following approach to the problem was fruitful

ESP8266 is 3.3v compatible so to avoid problems make a simple adaptor circuit to make it compatible with 5v Arduino (find details here)
First thing you need to do is check and confirm if you are able to communicate with your ESP module, you can use any USB to TTL interface and connect ESP Module directly with your computer/laptop. (explained in detail here)
Use ESP8266 configuration utility, it will speed up the ESP Module setup and help get the desired product develop faster. (explained in detail here)

Hope it helps.


How to convert string to long? There is String.toInt(), but no String.toLong() or the many other variations. Do I have to resort to atol(String.c_str()) or is there a better way to convert a String to a long?

Using atol(String.c_str()) looks OK to me. If there was a String.toLong() it would be written that way anyway.

In fact, looking at the code for String.toInt() that's exactly what it does:

long String::toInt(void) const
{
    if (buffer) return atol(buffer);
    return 0;
}

So the answer is: use String.toInt().


Connecting Something Big to an Arduino - Sending more than 5V So I am turning a relay on and off with my Arduino. I am using python to control it but wrote the simple basic code in the Arduino IDE. I am able to send 5 or 0 volts to the pin. My question is, how can I turn something on and off that requires more than 5 volts to turn on?

Thank you.

Use a transistor, amplifier, opto-isolator or if you can drive a 5V relay use that relay to drive a higher voltage/current item item.


Are the output pins on the 74HC595 shift register protected against shorting? In the following schematic you can see that Q1 and Q4 both are connected to a Arduino's Digital Input Pin. So if Q1 is high and Q4 is low, would there be current flowing from Q1 through Q4 (and through the chip) to Ground - or is there already some protection inside?

Are the output pins on the 74HC595 shift register protected from connected voltages in the realms of their own VCC? Or do you need to put a diode in?

I feel like this is a very basic question, which makes it very weird that I didn't find an answer to this, already... :-( Am I looking into the wrong resources? I had a look into the provided datasheet, but couldn't find any information. Didn't get any results from searching for existing posts on Stack Exchange or other sites.

In this data sheet it says:

  When the output-enable (OE) input is high,the outputs are in the
  high-impedance state.

However on page 3 you will notice that the *OE pin controls all outputs at the same time.  So if you connect 2 output pins and one is high and the other is low and you hold *OE low ... you will likely burn out the driver for one of the 2 output pins if not the chip its self.

If you add diodes to BOTH outputs you are essentially creating a wired or gate.  (You should add a resistor.  See the examples in the provided link.) This is fine as long as you understand how a wired or gate works.


LED does not blink - Arduino UNO+WiFi R3 ATmega328P+ESP8266 board As I am learning the Arduino coding, I want to see if my program can turn on the LED light. I have tried all the things, but the code does not start the LED light I have installed on the board.
The code compiles successfully and upload on the board, but nothings happens after that. See the output logs as below:
See all the configuration of board as below:
The board I have:
UNO+WiFi R3 ATmega328P+ESP8266 CH340G Board compatible with Arduino
https://robocraze.com/uno-wifi-r3-atmega328p-esp8266-ch340g-board-compatible-with-arduino
Board switch settings:
5,6,7 => ON (to upload the code from Arduino IDE)
Yellow LED installed:
13 => Positive, GND => Negative
Board setup:

Arduino IDE Setup:

Program:
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH);
  delay(2000);
  digitalWrite(13, LOW);
  delay(2000);
}

Output logs after uploading the code:
esptool.py v2.8
Serial port COM8
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: ec:fa:bc:3e:2e:6f
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Flash params set to 0x0340
Compressed 261472 bytes to 193134...
Wrote 261472 bytes (193134 compressed) at 0x00000000 in 17.1 seconds (effective 122.1 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

As you can see, the last message is Hard resetting via RTS pin....
Would anyone please tell me what is happening here? Why the program does not start the LED light even after everything looks fine?
Any help would be greatly appreciated.
Thanks.

The Uno+WiFi board is an Uno. With DIP switches 3 and 4 in ON position it is a normal Arduino Uno clone with CH340 chip for USB. All the pin headers at board sides and the ICSP pins are as on an Arduino Uno. Every sketch for Uno will work.
The esp8266 is added for WiFi functionality. The DIP switches allow to program the esp8266 over the CH340 or to connect the esp8226 to Serial of the Uno part (ATmega328p).
To have Serial free for USB, it is usual to wire the esp8266 to a common Uno on some other pair of pins then RX/TX and use SoftwareSerial. There is no such connection on this Uno+WiFi, but the esp8266 header has the Rx/RX pins of the esp8266 so it is possible to wire SoftwareSerial pins with jumper wires (power and ground are connected on board of course).

Don't switch the DIP switches too frequently. They are not made for it and fall apart. Upload some permanent firmware to esp8266 or use OTA upload for esp8266.


how does c++ understand which function must to use? in this code:

    void AdptSendReply(const char* str)
{
    string s(strlen(str) + 2);
    s = str;
    AdptSendReply(s);
}

void AdptSendReply(const string& str)
{
    string s(str.length() + 2);
    AdptSendReply(s); // use the next one
}

void AdptSendReply(string& str)
{
    if (AdapterConfig::instance()->getBoolProperty(PAR_LINEFEED)) {
        str += "\r\n";
        AdptSendString(str);
    }
    else {
        str += "\r";
        AdptSendString(str);
    }
}

i think c++ use of overloading ability.but how it can recognize which of the two functions "void AdptSendReply(string& str)" or "void AdptSendReply(const string& str)" must use?!

The compiler decides which function to use based on the variable type information. Imagine you write

str += "test";

If you declare str as a constant, the above line will throw an error. So if you write AdptSendReply(str) instead, the compiler will call the const function. Likewise, if you declare str as a mutable variable, the above line will compile fine, and, should you call AdptSendReply(str), the compiler will use the non-const function.


How can I stop a loop when using a servo with a Key input? How can I stop my following code using a key?

Basically the code should run the servo in a loop if "t" is pressed and stop the loop if "s" is pressed.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position
int servodata;

void setup() {
  myservo.attach(8);  // attaches the servo on pin 9 to the servo object

  Serial.begin(9600);

}

void loop() {
  if (Serial.available()>0){
    servodata = Serial.read();
    while (servodata == 't'){
           for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(3);                       // waits 15ms for the servo to reach the position
  }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(3);                       // waits 15ms for the servo to reach the position
    }
    }
  }
  while (servodata == 's'){
    break;
  }
}

thank you for help.

Here is a quick and dirty solution, where each loop() iteration
corresponds to one “start sweeping”/“stop sweeping” cycle:

wait for the “start” command
then sweep back and forth in an infinite loop
stop at any point if you receive the “stop” command

void loop() {
    // Wait for the 'start' command.
    while (Serial.read() != 't')
        continue;

    // Repeatedly sweep back and forth.
    for (;;) {
        for (int pos = 0; pos <= 180; pos += 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
        for (pos = 180; pos >= 0; pos -= 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
    }
}

Note that this approach has a couple of drawbacks:

As this is blocking code, you cannot easily extend the program to do
other things.
The sweeping runs always start at position 0, instead of resuming
from the position that was current on the last “stop” command.

If you need anything more sophisticated, you should go to a non-blocking
approach based on a Finite State Machine (c.f. jsotola's
comment). Note that you can get away with delay(3);, as it is a quite
short delay, but you would have to break the sweeps into one step per
loop() iteration.

I suggest you give the FSM approach a try: read the tutorial I linked
to, then try to implement it. If you cannot get it to work, you can
always post another question here.


Unknown type name 'IRsend' In the C file in simplesample_mqtt.c, which connects Arduino to the Azure IoT hub, I need to use the IRsend and IrRemoteESP8266 libraries to send an infrared signal with Azure IoT hub.

 #include <IRremoteESP8266.h>
 #include <IRsend.h>
 IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

I don't have any problem when I use this code in my main Arduino file. But when I use these includes in a C file (simplesample_mqtt.c), I get this error from line 3: "unknown type name 'IRsend'".

error full info :

Arduino: 1.8.2 (Windows 10), Board: "NodeMCU 0.9 (ESP-12 Module), 80 MHz, 115200, 4M (3M SPIFFS)"

In file included from sketch\simplesample_mqtt.c:29:0:

C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:1: error: unknown type name 'class'

class IRsend {

C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:14: error: expected '=', ',', ';', 'asm' or 'attribute' before '{' token

class IRsend {

simplesample_mqtt.c:31: error: unknown type name 'IRsend'

IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

simplesample_mqtt.c:31: error: expected declaration specifiers or '...' before numeric constant

IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

exit status 1
unknown type name 'IRsend'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I solved this problem. The reason for this is because main Arduino is c++ and simplesample_mqtt.c is c code and we have to use c++ code in c code:

In main Arduino file you have to declare function like this :

extern "C" void TurnOn();
void TurnOn()
{
    digitalWrite(RELAY_SONOFF, HIGH);
    digitalWrite(LED_SONOFF, HIGH);
}

and use this function in c code:

void TurnOn();
EXECUTE_COMMAND_RESULT TurnOn(ContosoAnemometer* device)
{
    (void)device;
    TurnOn();
    (void)printf("Turning fan on.\r\n");
    return EXECUTE_COMMAND_SUCCESS;
}


Internet of Things at home only My question isn't specific to Arduino but can concern Raspberry Pi and all Internet of Things homemake projects.

As I'm preparing a personal projet with sensors, data storage and visualisation/reporting web page (not yet Android app) I'm looking about Internet of Things platform.

It seems all that I can find are cloud related system. I would prefer a home localized solution but I'm not able to find one (and maybe open source) where datas don't go outside home.

The goal is to be able to :
    send datas from my Arduino to a home storage server
    store these data into database for later query (may be MySql)
    trigger some computation or aggregation job over datas
    prepare some graphs
    generate some html page from template
    option: allow Android client to connect and get datas/graphs

Before starting thinking how to create my own (non standardized) system is anyone can give me some advice ? some name of such existing system ?

Thanks

Thomas

I recently worked extensively on a Home Automation Project and here's what I would recommend based off of that:

Use Arduino for hardware interfacing.
Use Raspberry Pi for hosting your server.
Write your server using Node.js (or Python if you wish).
Use Express, Socket.io (or Python simple server). Google these.
Use Serial (USB) for communication between Arduino and Raspberry Pi
Use RF/BLE if you want to go wireless.
Use Redis or MySQL for database.
Use a graph JS API for charting.
To build an android app, send http requests (or a Socket.io link), for communication.

This is a simple to implement, but you'll need to put some time. Good luck.
All of the above steps are abstracted from each other. This means that if you want to incorporate additional features, you can change any stage without affecting the whole.


You have two options.

You can make an array of arrays like this:

const uint16_t sources[3][RAW_DATA_LEN] = {
    { 8546, 4310, 558, ... }, // CD
    { 8550, 4310, 526, ... }, // AUX
    { 8550, 4306, 530, ... }  // CDR
};

But then you don't have the sourceCD, etc. variables any more. If you
want, you could #define aliases for them like this:

#define sourceCD  (sources[0])
#define sourceAUX (sources[1])
#define sourceCDR (sources[2])

You can make an array of pointers, as suggested in the comments:

const uint16_t sourceCD[RAW_DATA_LEN]  = { 8546, 4310, 558, ... };
const uint16_t sourceAUX[RAW_DATA_LEN] = { 8550, 4310, 526, ... };
const uint16_t sourceCDR[RAW_DATA_LEN] = { 8550, 4306, 530, ... };
const uint16_t *sources[3] = { sourceCD, sourceAUX,  sourceCDR };

This works because, in the last line, the array identifiers such as
sourceCD implicitly “decay” to pointers to their first elements. Note
the const keyword in the last line, needed for consistency with the
types of the arrays declared above.


My RTC is returning a sporadic date/time RTC seems to be sporadically returning bogus date/times. Here are the logs from my serial monitor:

2016/3/23 8:19:46
2017/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2165/165/165 15:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46
2016/3/23 8:19:46

That 2165/165/165 15:19:46 appears throughout the logs.

Here's the relevant code:

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

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

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop() {
  DateTime now = rtc.now();

  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(" ");
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
}

I have a Grove RTC module.

The RTC library does not check for communications success. In particular, here:

DateTime RTC_DS1307::now() {
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.send((byte) 0);
  Wire.endTransmission();

  Wire.requestFrom(DS1307_ADDRESS, 7);
  uint8_t ss = bcd2bin(Wire.read() & 0x7F);
  uint8_t mm = bcd2bin(Wire.read());
  uint8_t hh = bcd2bin(Wire.read());
  Wire.read();
  uint8_t d = bcd2bin(Wire.read());
  uint8_t m = bcd2bin(Wire.read());
  uint16_t y = bcd2bin(Wire.read()) + 2000;

  return DateTime (y, m, d, hh, mm, ss);
}

There should be a check for a zero returned from Wire.endTransmission(). It isn't otherwise possible to detect if the data is invalid (if we got the endTransmission OK) however generally speaking I2C will return 0xFF if the transmission has ceased.

The code in the library for bcd2bin is this:

static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); }

You can see that if passed 0xFF (255) it will return:

   255 - (6 * 15) = 165

Thus if any of the minutes, hours, day or month (which are not further affected in the code above) are 165 (or if the year is 2165) you can assume the whole date/time is bad.


How can I use separate power source for the Arduino and the motors How can use a separate power source for powering Arduino, and another battery for powering the motors?
How can I make connections through the motor driver module L298N? I know how normally we use one battery to power the Arduino as well as the motors. But I am facing the problem while using different power sources.

That motor driver has an optional on-board 5V regulator. It can be enabled / disabled with a jumper.
With that regulator enabled you just need to connect a ground and your control signals (ENA/IN1/IN2 or ENB/IN3/IN4).
If you disable that regulator (remove the jumper) then you need to provide power from the Arduino's 5V pin to the +5V screw terminal.
The ENx pin(s) (after removing any jumpers that may be on them) connect to any PWM capable pin (this is the speed control pin). IN1/IN2 or IN3/IN4 connect to any IO pin since these are just used to set the direction or control the braking modes.  ENA controls the speed of motor 1, and IN1/IN2 control the direction of motor 1. ENB and IN3/IN4 are likewise for motor 2.


Arduino as an automation controller I am considering using an Arduino as a controller for a water treatment system and would love to hear your opinions. All it has to do is open/close a water gate (by starting/stopping a motor) at predefined times. It would have to...

Be able to connect to a phone using a usb cable. The phone would act as a UI to change settings and water flush times on the Arduino (via a custom app)
Log data which would be easily retrievable
Ideally, be able to connect to a cell network and send/receive packets. I believe there is a shield for this
Consume MINIMAL POWER. All it has to do is flush once every few days, log data, and possibly receive data from shield/usb. It would be running off of a solar panel and battery. In winter it could run out of power.

And thats pretty much it! Can this project be done with an Arduino? I would greatly appreciate any advice and recommendations!

Have a look at my Temperature and humidity sensor - battery powered. That works from 3 x AA batteries, and has been going for a few years. I think I replaced the batteries once. It keeps track of the time, and logs data to the disk (SD card).

I don't have room to describe the whole project here, but the general idea is that the processor sleeps most of the time (consuming around 6 µA). Now this particular project doesn't turn on a motor, but adding a solid-state relay should be all you need to do that.

  Be able to connect to a phone using a usb cable. The phone would act as a UI to change settings and water flush times on the Arduino (via a custom app)

I think this will take a lot of power, keeping the phone active. One possible thing to try would be to power up the phone (eg. using another relay) during a certain "window" of time (eg. 6 pm to 7 pm). Then you would know to try to configure the device during that time.


Program Arduino Uno via Nano To keep the question short:

I'm trying to burn a bootloader on my Arduino Uno using an Arduino Uno. Could someone please tell me the pin connections? Thanks.

To burn a bootloader from source Nano to target Uno make the following connections:

Nano.Pin   Uno.Pin

10         Reset

11         11

12         12

13         13

GND        GND

See here for more details: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard


Stacking 3 of the same shields on top of each other and instructing them in sync Context:
I have an audio track separated into individual channels grouped by frequency and speaker location. I need to play all three of these channels simultaneously and perform instructions like play, stop, repeat, skip across all channels to keep them in sync.
This is part of an outdoor installation so the solution must be modular and robust.
If possible, the most elegant solution I could come up with is to use an Arduino Leonardo and stack 3 Adafruit Music Maker Shield on each other.
Reasons why I think it might be technically feasible:
1. Each shield can share communication over I2C

Looking at the VS1053b Datasheet (the IC used in the shield) the chip at max load consumes Maximum 60mA, and typically 37mA. Arduino can drive a max of 500mA so these three shields should consume a small portion of that.
The Arduino will also be powered via 12v power supply.

Details i'm not so clear on:

How will I differentiate between each shield when sending instructions or do I need to even need consider this if I want them to function as one?

The shield actually uses SPI.

So you will need to trace the chip select and make sure that each shield uses a different arduino pin.


ESP8266 -01 doesn't reply with anything The problem started when I tried to upload the Blink program to the module, it uploaded with no issues through Arduino but after that the blue LED didn't blink.

I searched a lot for it and found that the pin number may need to be changed.

So I uploaded this code

int LED0 = 0;
int LED1 = 1;
int LED2 = 2;

void setup() {
  pinMode(LED0, OUTPUT); // Initialize the LED_BUILTIN pin as an output
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  Serial.print("LED_BUILTIN = ");
  Serial.print(LED_BUILTIN, DEC);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED0, LOW); // Turn the LED on (Note that LOW is the voltage level
  digitalWrite(LED1, LOW); // but actually the LED is on; this is because
  digitalWrite(LED2, LOW); // it is active low on the ESP-01)
  delay(1000); // Wait for a second
  digitalWrite(LED0, HIGH); // Turn the LED off by making the voltage HIGH
  digitalWrite(LED1, HIGH);
  digitalWrite(LED2, HIGH);
  delay(2000); // Wait for two seconds (to demonstrate the active low LED)
}

to ensure the blinking but still nothing out.

After that I tried AT commands and no replies also.
After that I did some searches and found that it may need to update the flash program and that's what I did.
No sync occurs until I remove and connect the power to the module while the tool is trying to sync. Otherwise, it gives a fail.
By removing and connecting the power to the module I was able to upload that flash,
But I still have the same problem - no reply from the module to AT commands and the blink output is nothing.
Finally I directly connected the TX to the 3.3 V and the blue LED is on so I figured that the problem is in the replying from the module.

Any help would be appreciated.

Hasn't the ESP8266 got different pin numbering? ie
arduino pin 2 = pin 4 on esp8266,
arduino pin 3 = pin 5 on esp8266,
and arduino pin 4 = pin 2 on esp8266? and pin 4 on esp8266 is the built-in led.
hope it helps.


Upgrade ESP-01 firmware on MacOS I recently bought an ESP-01 as well as an FTDI programmer (3.3v-5v) and after typing AT+GMR I noticed it said:

AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

I have looked and looked on a way to upgrade its firmware (on MacOS) to no avail. How can I upgrade it? I want to be able to change the baud rate to 9600. A lot of examples to do it are in windows requiring another application or something like that but how can I do it in a Macbook? Thanks.

Here is the step-by-step on upgrade the ESP-01 AT Command firmware (for running on macOS).
Wiring
For flashing the ESP-01 firmware, you need to have a USB-TTL adaptor as a programmer.
+---------------------+---------+
|                     | RxD Vcc |
|       Top View      | IO2 RST |
|                     | IO0 CPD |
|                     | GND TxD |
+---------------------+---------+

ESP-01          USB-TTL Adaptor
 VCC   ---------- 3V3
 GND   ---------- GND
 TxD   ---------- RxD
 RxD   ---------- TxD
 CH_PD ---------- see note* below
 GPIO0 ---------- Connect to a push switch (Flash button) to GND
 RST   ---------- a push switch (Reset button) to GND

Note: depend on whether you have ESP-01 or ESP-01S, for ESP-01, you will need to connect CH_PD either directly to 3v3 or via a 3k-10k resistor to 3v3. However, you don't need the an extra pull-up resistor for ESP-01S as CH_PD already has on-board pull-up resistor. This picture shows the different between ESP-01 and ESP-01S, visually ESP-01 has 2 LEDs on board near the antenna, while ESP-01S have two extra resistor between header pins and ESP8266EX chip, and with only one LED.

Download and install esptool
Download and install esptool from https://github.com/espressif/esptool. esptool is a python application. You need to have python installed as well.
Download firmware 2.1
Download ESP8266 nonOS SDK - Release 2.1.x, noticed that this is not the latest version as the latest version doesn't works for ESP-01 based on my experience.
Upgrade the firmware
You will actually only need 4 files for the upgrade, I would suggest that you copy and paste those files into your esptool directory from the downloaded bin/ directory. cd into your esptool directory and run the following commands to upgrade the firmware.
To put ESP-01 into programming mode:

Press and hold BOTH buttons;
Release the Reset button while keep holding the Flash button until the upload is completed;
Press Reset to start the newly uploaded program when all upgrades are done.

./esptool.py --port /dev/cu.SLAB_USBtoUART write_flash 0x00000 boot_v1.7.bin
./esptool.py --port /dev/cu.SLAB_USBtoUART write_flash 0x01000 user1.1024.new.2.bin
./esptool.py --port /dev/cu.SLAB_USBtoUART write_flash 0x7c000 esp_init_data_default.bin
./esptool.py --port /dev/cu.SLAB_USBtoUART write_flash 0x3e000 blank.bin
./esptool.py --port /dev/cu.SLAB_USBtoUART write_flash 0x7e000 blank.bin

Please noted that /dev/cu.SLAB_USBtoUART is the USB port for my USB-TTL interface, yours might be different, run ls /dev/tty.* to find out your USB port


Emit region-neutral keyboard signals The Keyboard API allows the Arduino boards such as the Micro or Leonardo to emit USB signals mimicking a physical keyboard. However, the signal seems to transmit key strokes and not characters which means that machines with different region settings interpret the USB signal differently. For example, a y will be interpreted as z in a German OS since the keyboard layout has these keys swapped.

Is there any way to output a signal that will result in the correct character being transmitted regardless of the OS settings without any modifications to the machine the Arduino is attached to?

Download Device Class Definition for Human Interface Devices (HID)

https://www.usb.org/sites/default/files/documents/hid1_11.pdf

See section 6.2.1 HID Descriptor

bCountryCode 0x09 German

also see section E.4 (page 67)

E.4 HID Descriptor (Keyboard)
Part            Offset/Size  Description                                         Sample
                (Bytes)                                                          Value
----------------------------------------------------------------------------------------
bLength           0/1        Size of this descriptor in bytes.                    0x09
bDescriptorType   1/1        HID descriptor type (assigned by USB).               0x21
bcdHID            2/2        HID Class Specification release number
                             in binarycoded decimal—for example, 2.10 is 0x210).  0x101
bCountryCode      4/1        Hardware target country.                             0x00
bNumDescriptors   5/1        Number of HID class descriptors to follow.           0x01
bDescriptorType   6/1        Report descriptor type.                              0x22
wDescriptorLength 7/2        Total length of Report descriptor.                   0x3F


Can I stack an Arduino to another Arduino? I'm using Arduino clones, which have pin headers the same as Arduino's shields have (with extended "legs" below the board to be stackable).

Can I stack my Arduino (Mega) clone to an Arduino (Uno) clone without destroying both? Wouldn't it explode or something?

Just asking before trying it.

Thanks!

No, I don't think that is a good idea. You would basically short the pins of each of them together, plus their power supplies. The only way it might conceivably work was if one Arduino had all its pins as inputs and the other as outputs, otherwise they would be "fighting" each other to drive a pin high or low. You would also have connected together their Reset pins so they would both reset at the same time. And doing serial comms would be problematic as the serial ports would be fighting each other.

Also, uploading sketches would be virtually impossible, as when you started the upload, both would be reset, both bootloaders would try to read the incoming data, and reply at the same time. Plus, the Mega and the Uno have different uploading protocols. So at the very least, you would have to separate them every time you uploaded new code, to either one.


How frequently do you need to poll UI buttons before they are perceived as laggy? Whilst it is possible, and sometimes desirable, to use pin change interrupts to read the state of buttons, it is simpler to poll the state of buttons in loop(). This is a commonly used technique.

If you loop() executes quickly enough, then button presses are always going to be caught and the user will not be able to perceive any delay or lag.

It is possible that your loop would take so long as to cause a delay or lag to be perceived.

The question is, how long would it be, in general, before a user would see this?

The short answer is that you have 100 miliseconds to respond to the user if you want them to feel the action occurred instantaneously.
According to Jacob Nielsen in his book Usability Engineering, from 1993, which is considered an important reference in Systems Usability and User Experience:

0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.

He also mentions that this basic advice regarding response times has been about the same for many decades [Miller 1968; Card et al. 1991].
I've taken this citation from this article: Response Times: The 3 Important Limits, also writen by Jacob Nielsen.
Note that in this time you must include all time taken to read the button press and give feedback to the user.
Other response time thresholds that are important for user experience, from the same source, but that were not mentioned directly by the OP are:

1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.

10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.


Serial Monitor stops printing data I have an IMU sensor (MPU 6050) connected with arduino UNO. Pin maps are as follows:

MPU6050 --> Arduino
Vcc --> Vcc
Gnd --> Gnd
SCL --> A5
SDA --> A4

(Not using any pull up resistors)

I am using jeff rowberg's MPU6050 library to get data from sensor. To test the sensor, I am using the raw value example sketch from the library. I am getting readings for both the accelerometer and the gyroscopes.

The problem is after some time the serial monitor just stops printing data. I have tried to figure it out but have not succeeded in solving the problem. It could be due to one of two reasons:

The MPU6050 stops giving sensor values
There is a problem with the serial monitor

As far as I have figured, the sensor is giving values because when I restart the serial monitor, the data starts to print again on the serial monitor and stops printing after same duration of time as it did before restarting the monitor.

I have tried the serial monitor of the arduino IDE and hyperterminal. In both cases the data stops printing after some time.

Any idea, what causes the serial monitor to stop printing data? Is it the sensor or the serial monitor?

Help would be greatly appreciated. Thanks in advance.

I had exactly same situation.
I initially started to inspect on FIFO overflow of MPU6050, then experimented setting different clock speed for I2C communication, tried to tweak with pullup resistors as recommended.
Finally, here is the solution which worked for me. Basically, I just disconnected INT pin from MPU6050.

Now the schema is:
(MPU) -> (Arduino)

AD0 -> GND
SDA -> A4 (No pullup)
SCL -> A5 (No pullup)
GND -> GND
VCC -> 3.3V

I used this code as an example:
https://github.com/jarzebski/Arduino-MPU6050/blob/master/MPU6050_gyro_pitch_roll_yaw/MPU6050_gyro_pitch_roll_yaw.ino

from this library:
https://github.com/jarzebski/Arduino-MPU6050


detachInterrupt(0) in arduino not working ? after giving continuous ground to INT0 wakeupnow function should execute once not again and again #include <avr/sleep.h>

int wakePin = 2;                 // pin used for waking up
int led=13;
int flag=0;

void wakeUpNow()
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
  int count=10;
  while(count!=0)
  {
    delay(1000);
    count--;
    Serial.println(count);
    delay(1000);
  }
}

void setup()
{
  Serial.begin(9600);
  pinMode(wakePin, INPUT_PULLUP);  // wakePin is pin no. 2
  pinMode(led, OUTPUT);          //   led is pin no. 13
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow()
{
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();                        // enables the sleep bit in the mcucr register
                      delay(500);
                      Serial.println("Rajat");
                      delay(500);
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                      delay(500);
                      Serial.println("Rajat");
                      delay(500);
    sleep_mode();     // here the device is actually put to sleep...!!
      // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
                      delay(500);
                      Serial.println("Rajat2");
                      delay(500);
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
    sleep_disable();         // first thing after waking from sleep: disable sleep...
                      delay(500);
                      Serial.println("Rajat3");
                      delay(500);
       detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.

}

void loop()
{
      digitalWrite(led, HIGH);
      delay(1000);
      digitalWrite(led, LOW);
      delay(1000);
    /* delay(500);
      Serial.println("jam");
      delay(500);  */
      if (flag==0)
      {
      sleepNow();     // sleep function called here
      flag=1;
      }
}

After Last Rajat I give ground to INT0.

Output in serial monitor :

Rajat
Rajat
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
& so on..!

You're detaching in completely the wrong place. After sleep_mode() returns from sleep and before the interrupt is detached you have an entire second of time where your interrupt can still fire. And it will fire, since a LOW interrupt will keep firing while the input is LOW.

sleep_mode();     // here the device is actually put to sleep...!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
                  delay(500);
                  Serial.println("Rajat2");
                  delay(500);
detachInterrupt(0);

Instead you should detach the interrupt within the interrupt routine itself:

void wakeUpNow()
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up

    detachInterrupt(0);

  int count=10;
  while(count!=0)
  {
    delay(1000);
    count--;
    Serial.println(count);
    delay(1000);
  }
}

Also, all those delays and Serial prints in an interrupt are seriously problematic. An interrupt should never delay() and should never Serial.println().


Problems with Arduino + IR + Raw code low memory im having a problem with my new project with arduino + ir emitter + big raw codes.

I've tryed this way:

https://gist.github.com/jjmjr/41ed083c8229d0218c962641c5af27b0

As you can see each of my raw code from air conditioner is huge so i've tryed with progmem using "a" (as turn on) command on serial to send the first line from the ir raw codes but didnt work.

Any one can help me?

Thanks


Headers linking - PlatformIO For those who use the IDE Platform IO, I have an issue for you. I use to program a home application of sensor reading and use the library "JC_Button.h" to manage buttons. There are other third-party libraries, but this in especial is cumbersome. The project tree is shown below.

.

The compile log of the build is here. I have few notion of what is happening. In my opinion, the project does not find the necessary lib.

Thank you in advance.

It looks like you are not telling PlatformIO that you need the JC_Button library. Try adding this to your platformio.ini file:

lib_deps = https://github.com/JChristensen/JC_Button


What is preventing my code from checking the number of pushbutton values for a correct/wrong answer? My code is supposed to generate a random number and then display it in binary using four LEDs. After you press it, it waits for two seconds before checking your number of pushbutton presses to see if they equal the random number, and it turns the green/red LED on accordingly and restarts the loop.

It doesn't do that, and also it counts multiple pushes if you keep the button pressed in, since it reads the pushbutton as being "on".

Code:

//VARIABLES:
const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 4;
const int ledPin4 = 5;
const int buttonPin = 6;        //push button
const int ledPincorrect = 8;   //green LED that switches on for correct answer
const int ledPinfalse = 9;    //red LED that switches on for wrong answer

int randomNumber = 0;
int buttonState = HIGH;
int buttonPushCounter = 0;             //counter for button presses
int lastButtonState = HIGH;             //previous state of the button
int getal;
int i;                              //for the ConvertBinary function, i serves as a variable for the LED's
unsigned long Timer;               //Timer, switches on after buttonstate = LOW, and after 2 seconds the game restarts
long lastDebounceTime = 0;         // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
int ledState = HIGH;
int remember;

void setup()
{
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(ledPincorrect, OUTPUT);
  pinMode(ledPinfalse, OUTPUT);
  Serial.begin(9600);
  randomSeed(analogRead(0));
  buttonState = digitalRead(buttonPin);
  Timer = millis(); // unsigned long Timer = millis();

}
void loop()
{
  if (randomNumber == 0) {
    Serial.print("lets start with random");
    getal = random(1, 16);
    Serial.print("random is: ");
    Serial.println(getal);
    randomNumber = 1;
  }

   int remember = getal;
   for (int i = 2; i < 6; i++) {
   remember = remember / 2;
      if (remember % 2 == 1){
       digitalWrite (i, HIGH);
      }
     else ((digitalWrite(i, LOW)));
    }

    // reading the button state

    // read the state of the switch into a local variable:
    int reading = digitalRead(buttonPin);

    if (reading != lastButtonState) {
      lastDebounceTime = millis();
      if (reading == LOW) {                    // if (reading == LOW) ????
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes:  ");
        Serial.println(buttonPushCounter);
        Timer = millis();
        lastButtonState = buttonState;

      } else {
      // if the current state is LOW then the button wend from on to off:
      Serial.println("off");
    }

      if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      lastButtonState = reading;
    }

    if (Timer >= 2000UL) {
      if (buttonPushCounter == getal) {
        digitalWrite(ledPincorrect, HIGH);
        digitalWrite(ledPinfalse, LOW);
        digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      randomNumber = 0;
      buttonPushCounter = 0;
      }
      else {
        digitalWrite(ledPinfalse, HIGH);
        digitalWrite(ledPincorrect, LOW);
        digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      randomNumber = 0;
      buttonPushCounter = 0;
      }
}

    }
}

}

Let us start with the simplest issue in your code:

Timer = millis();
...
if (Timer >= 2000UL) {
...
}

After 2000 ms this is always true (for about 49 days)?

Cheers!

Please format your code if you expect anybody to take the time to read it and help.


What pins to use to externally power an Arduino Fio (without battery) I need to power an enclosed Arduino Fio project with 12V. The intention is not to attach a battery because there is no need as this is a fixed installation with a 12V DC available (for a pair of relays which will be controlled by the Fio).

My question is what Pins should I use. The Fio page (https://www.arduino.cc/en/Main/ArduinoBoardFio) on the Arduino web site says...

Input Voltage   3.35 -12 V
Input Voltage for Charge    3.7 - 7 V

Unfortunately, there is no indication what pins these specs refer to. I assume that the "Input Voltage for Charge" refers to the mini-USB port and unlike other Arduino boards, there is no Vin pin to supply the board externally. Looking at the board layout on the same web page, I think the only possible option is via the two pins in parallel to the battery port which I suppose are then going into the voltage regulator on the board.

Any comments or suggestions? Has anyone done something similar?

I used the external switch input JP7-1 for 12v, any GND hole, and make sure the switch is off.  This bypasses the charge circuit which doesn't like 12v.


Arduino hangs after 3-4 minutes on battery power, but not on USB I have a simple sketch running on a BE Leonardo-compatible board.

It reads input from a potentiometer, and outputs to two RGB LEDs which change colour over time - in a different pattern if certain inputs are received.

Other than that, the only code is serial I/O for debug purposes.  (It's disabled using a #define in the running version, to prevent serial buffer overflow when not connected.)

When the board is powered by USB, everything works.

When the board is powered by 9V battery, after about 4 minutes it hangs - the LEDs go off, and the L13 light on the board starts glowing at varying strength.  (There is nothing connected to pin 13.)  Even the reset button doesn't work.

If the board is then connected to the computer's USB port, after a few seconds the hang clears and the program resumes.

Can anyone offer a possible explanation for (and solution to) this fault?

As somebody else suggested, 9V batteries are pretty weak. They only provide a very small number of mAh (milliamp/hours) before their voltage starts to drop. Once the voltage drops to around 7 volts, the regulator in the Arduino can't keep providing 5 volts, so your Arduino resets.

Wire up 6 AA batteries in series. That will provide a much "stiffer" 9 volt supply (more instantaneous current) plus a lot more mAh of total power. If you REALLY want long life, wire up 6 C or D batteries in series, or an external 9V supply through a "wall wart" power supply.


Does a delay in a loop save energy? I've noticed most example snippets always have a delay in the loop even if it's not needed for proper execution of the program.

I can only assume this is added because people copy and paste without understanding what's going on but it got me thinking if adding a delay could possible save power too.

If I have a loop that checks some inputs for changes could it be possible that adding a delay(10) saves some cycles and thus power?

No, it burns energy by doing nothing.

You definitively should send your MCU to sleep and wake up on events or use the watchdog timer to wake up after a predefined period of time.


Controlling an OSX app by Arduino I am trying to control an app on OSX with an Arduino Uno.  Specifically, I would like to start and stop play of an MP3 on iTunes, or a track on Spotify, using an Arduino connected to the Apple computer with USB.

Any suggestions would be greatly appreciated.

I am now having Screen output to log.txt, and the following applescript works just great!

set trigger to 1

set stopString to ""

repeat until (stopString = "stop")

set testTxt to paragraphs of (read POSIX file "/Users/fed/log.txt")
set countTxt to (count of testTxt) - 1
set lastLine to item countTxt of testTxt
if lastLine contains "Start MP3" and trigger is 1 then
    tell application "Spotify" to playpause
    set trigger to 0
end if

if lastLine does not contain "Start MP3" then
    set trigger to 1
end if

if lastLine contains "Stop Loop" then
    set stopString to "stop"
end if
end repeat


Erroneous sensor reading while connecting extra load I'm making a speedometer using arduino. I've made use of the interrupt pins to achieve the same. My problem is with the power source. I'm using a 12 V battery supply to power the arduino and I'm also using the same battery to use a horn. But, whenever I push the button to sound the horn, the IR sensor connected to the arduino is getting activated and I'm getting an erroneous reading. The only common thing between the arduino and the horn is the battery supply.

If the horn has a speaker coil or other magnetic actuator in it, then it will present an inductive load that may cause a voltage spike when you turn it off.  Or, if it's a buzzer, it may generate voltage spikes all during its operation.  Voltage spikes or other electrical noise are the most likely cause of the problem.

It also is possible that the horn draws enough current to drop your battery voltage so low that the Arduino or the sensors don't function reliably.

To find out which is the problem, take voltage readings with and without the horn in operation.  If you have an oscilloscope, look for spikes on system power.

Try isolating and/or buffering the Arduino's power.  If power glitches are the problem, that should fix the problem.  If the problem is electromagnetically radiated electrical noise, further isolation (eg shielding) may be needed.

To isolate the Arduino's power, either operate it from another battery (which is something you can do anyway, while diagnosing the problem) or add one diode into the Arduino's power lead and another into the horn's.  Connect an electrolytic capacitor, eg 100 to 1000 μF, from the Arduino's +V input to ground.  If necessary add ferrite beads around the power leads.

A capacitor across 12 V from the battery will buffer the power, but for more isolation and buffering you can add a buck converter which can manufacture eg +7V from a +12V input while remaining relatively impervious to spikes on the +12V.  Put the large electrolytic across the +7V if you use a buck converter.


Powering Down Arduino MKR1000 The MKR1000 is still pretty new and I'm having a hard time getting good information on it. I'm using the Arduino IDE but don't find any functions to sleep the MKR1000. Most libraries I encounter are for AVR chips while the MKR1000 has an ARM chip. I want to put it to sleep until an external interrupt is called. I also use the millis() function, will this function be rendered useless if it goes to sleep?

In the data sheet for the ATSAMD21 it talks about the Wait for Interrupt instruction which puts the machine to sleep but it doesn't say how to call the instruction. How can I do this in the Arduino IDE?

The rocketscream low power library looks like it supports the ATSAMD21.