My sketch is not working as intended I am a beginner with Arduino. I am doing something to cool down my room temperature using an exhaust fan and cooler through relays. I am trying to reduce the temperature initially using an exhaust fan and wait for 10 minutes to see if the temperature reduced to a set range. If not, the exhaust fan is turned off and the rest of the cooling is done by the cooler.

At the beginning of the program all goes well: it turns on the exhaust fan and waits 10 minutes and if it's not dropping, it transfers the job to the cooler. But after one cycle, when the temperature increases, the cooler is turned on directly, without the exhaust fan urning on, or waiting for 10 minutes and things. I tried a lot but I can't understand what is happening. Please suggest something to solve the problem.

#include <dht.h>

dht DHT;

#define DHT1_PIN 7 // dht11 connected to pin 7

int exhaustpin = 4; // set pin for exhaust fan relay
int coolerpin = 5; // set pin for cooler relay
boolean exhaust;
void setup(){
   Serial.begin(9600);
    pinMode(exhaustpin, OUTPUT);
  pinMode(coolerpin, OUTPUT);
  digitalWrite(exhaustpin,HIGH );
  digitalWrite(coolerpin,HIGH );
  exhaust= LOW;

}
void loop()
{

    DHT.read11(DHT1_PIN);
  Serial.print(" MY Room Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("MY Room Humidity = ");
  Serial.println(DHT.humidity);
 delay(500);
  int  roomtemp =DHT.temperature;
  static unsigned long interval;
  long interval;
  if (exhaust== LOW){
  if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH )){
    digitalWrite(exhaustpin,LOW ); // if temperature increses above 30 the exhaust starts to work
     interval = millis();
  }
  }
   if (digitalRead(exhaustpin)==LOW){
     exhaust= !exhaust;
 if ((millis()-interval) >= 600000){
    digitalWrite(coolerpin,LOW );
    digitalWrite(exhaustpin,HIGH );   // after the starting of exhaust fan it wait for 10 minutes ,then it turn
                                      // on the cooler and turns off the exhaust fan
       }
   }
  if (roomtemp<28){
    digitalWrite(coolerpin,HIGH );
     digitalWrite(exhaustpin,HIGH );
     exhaust= !exhaust;
   // i am trying here to start cooling the room with my exhaust fan
   // then wait 10 minutes ,if it is still not less than 28 degrees turn on the cooler to do the cooling
   // and turn off the exhaust fan
   }
  }

if (digitalRead(exhaustpin) == LOW) {
    static unsigned long interval = millis();
    if ((millis() - interval) >= 600000) {
      digitalWrite(coolerpin, LOW);
      digitalWrite(exhaustpin, HIGH);
      // after the starting of exhaust fan it wait for 10 minutes, then it turns on
      // the cooler and turns off the exhaust fan
    }
  }

interval is only ever set once. So 10 minutes after it is first set it will remain over 10 minutes.

The simplest fix is to set interval to millis() when you set exhaustpin to low:

if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH)) {
  digitalWrite(exhaustpin,LOW );
  // if temperature increses above 30 the exhaust starts to work
  interval = millis();
}


WiFiManager - Combine NonBlocking portal AND addParameter I wish to config WiFiManager and addParameter of MQTT topic and local server on its ConfigPortal.
Additionally in a case of a power outage or any, in case of losing WiFi, to continue in a NonBlocking way.
The problem is when combining both features in one sketch, I get some errors.
Entire code is ( please notice comments marked Marker[i] ):
#include <WiFiManager.h>
#define MQTT_SERVER "192.168.3.200"
WiFiManager wm;

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

  WiFiManagerParameter custom_mqtt_server("mqtt_server", "mqtt server", MQTT_SERVER, 40);
  WiFiManagerParameter custom_mqtt_user("mqtt_user", "mqtt user", "", 10);
  WiFiManagerParameter custom_mqtt_pwd("mqtt_pwd", "mqtt password", "", 10);
  WiFiManagerParameter custom_mqtt_topic("mqtt_topic", "mqtt topic", "", 10);
  WiFiManagerParameter custom_mqtt_group("mqtt_group", "mqtt group", "", 10);
  WiFiManagerParameter custom_mqtt_root("mqtt_root", "mqtt rootTopic", "", 10);
  wm.addParameter(&custom_mqtt_server);
  wm.addParameter(&custom_mqtt_user);
  wm.addParameter(&custom_mqtt_pwd);
  wm.addParameter(&custom_mqtt_topic);
  wm.addParameter(&custom_mqtt_group);
  wm.addParameter(&custom_mqtt_root);

  WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  //  wm.resetSettings();

  //  wm.setConfigPortalTimeout(180);
  // wm.setConfigPortalBlocking(false);  // <--- Marker [#1]

  //  if (!wm.autoConnect("AutoConnectAP")) {
  //    Serial.println("failed to connect and hit timeout");
  //    delay(3000);
  //    //reset and try again, or maybe put it to deep sleep
  //    ESP.restart();
  //    delay(5000);
  //  }

  bool res;
  res = wm.autoConnect("test123", "password"); // password protected ap
}

void loop() {
  // put your main code here, to run repeatedly:
  //  wm.process(); //<--- Marker [2]
  Serial.println("hi");
  delay(100);

}

When Marker[1] & Marker[2] are commented out ConfigPortal works as expected, and in Blocked state - meaning there is no hi's on Serial monitor.

When only Marker[2] is commented out, ConfigPortal is reached, lacking all addParameter fields.

When Marker[1] & Marker[2] are not commented out, ConfigPortal is now reachable, but not having Non-Blocking feature...

What is the purpose of wm.process() ?

Guy

The WiFiManger's autoConnect function starts the configuration web server (and AP) only if connection to configured WiFi network is not established.
If you want to run the WiFiManger's web server to reconfigure WiFi or to set other parameters, you can start the WM web server with the startConfigPortal function.
autoConnect and startConfigPortal are blocking by default. The library has a loop inside this functions which runs until the web server is stopped calling [Exit] action on the configuration web page or the timeout set with setConfigPortalTimeout is reached after last contact from browser.
To run the WM web server 'parallel' to your sketch you can configure it as not blocking with setConfigPortalBlocking(false). Then to allow WM handling of the web server the sketch must periodically call wm.process().
In not blocking mode the [Exit] action on the configuration wen page doesn't stop the web server. The server must be stopped in code.
The parameter definitions must by global in sketch, if you want to run WiFiManager with parameters outside of setup(). Parameters local in setup() don't exist after setup() finishes. WiFiManager detects this and doesn't use the parameters.
The OnDemandWebPortal example and OnDemandNonBlocking example demonstrate startConfigPortal in blocking and not blocking use.


How to burn the bootloader and upload sketches on ATmega328P U (specifically this model)? Recently I started to learn embedded electronics and C/C++ and for a couple of days I tried and I am still trying to burn a new ATMega328P U bought from Aliexpress. From what I know new ATMega328P's come with bootloader included, but after I wired everything up and connected the FTDI FT232RL to load the sketch (wiring is completely right after many many hours of checking on the internet for a dozen of pictures), I get errors like "programmer is not responding" in case of sketch upload and "error while burning the bootloader" or "Yikes, signature bla bla". I don't think the FTDI is the problem since the Arduino IDE recognizes it as COM7 on my PC. Now here's my question: is my atmega328p u broken or have I missed something during the process of both (trying to) burn(ing) the bootloader and upload(ing) the blink sketch? (I have also tried uploading the board programmer from Nick Gammon on my arduino Uno and the burning the bootloader AND followed the instructions from arduino.cc "from arduino to microcontroller on a breadboard"). If you need pictures of some sort, I'll provide them

IT WORKED, FINALLY. I followed this tutorial: https://www.electronics-lab.com/project/installing-the-arduino-bootloader-on-the-atmega328p-microcontroller/, followed exactly as it is explained, made the connections (nothing more, nothing less; I even removed the LED on pin 19 and its resistor) and to my surprise... the bootloader was actually loaded and the sketches were uploading just by using the FTDI. Thank you a lot for your help and information and I hope someday I'll pass this knowledge to someone who will be in the spot I was until now. Have a great time and love ya all


RX/TX not working as intended I am currently working on a project with a HC-06 module. I hooked it up accordingly like so:

Arduino -> HC-06
5V -> VCC
GND -> GND
TX -> RX
RX -> TX

and I ran this code:

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

void loop() {
   Serial.print("test");
   Serial.print("\n");

}

Strangely enough that does not work at all. When I am using neither with or without PC as the power source. When I am using SoftwareSerial like this it works like a charm:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(0, 1); // RX, TX

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

void loop() {

   mySerial.print("test");
   mySerial.print("\n");

}

Can someone please explain why and of course how to fix that?

You are using a Leonardo. Pins 0/1 aren't Serial, they're Serial1.  Serial is the built-in USB connection.

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

void loop() {
   Serial1.print("test");
   Serial1.print("\n");

}


Why do my temperature sensor values become inconsistent when additional hardware is added to the board? I have this strange problem. My TMP 36 sensor works fine when it is the only thing connected to my Arduino Uno board. The voltage measurements, and thus the temperature, are accurate and consistent. However, when I attach an LCD screen to the Uno and have a program print the TMP's measurements to the screen, the values become inconsistent, and can change up to 10 degrees F from one reading to another. (I have the sensor take a measurement every second.) This does not happen when the LCD screen is not plugged in. I decided to remove separate connectors from the screen and see when the measurements became consistent again. I tried this once and found that a ground wire that goes to connection 5 on the screen caused to value to change when I repeatedly inserted and removed it from a ground pin. The TPM values were changing even when there was nothing else connected to the LCD (it wasn't on) except for the ground wire. I don't understand how this is possible, and I don't know if this is a hardware or software issue.

I rewired the LCD screen starting with sensor wires, then ground wires, and then the two 5V connections, with one of them having a 220 ohm resistor. I did this while the circuit was powered, and watched the values for any large changes. The first change was a few seconds after I wired the last 5V wire. The sensor measured 80 degrees F and then 85 degrees F one second later. It then went to 81 for a few seconds, then 87. The values continued to change, but not by as much as previous times. By the way, the temperature in the area that the Arduino is in is about 82 degrees F.

TMP values do not change by more than 3 degrees F when the LCD is not connected to the screen. I don't understand what could be causing this. Has anyone else had this problem before, or know the cause?

Here is the layout.

#include <LiquidCrystal.h>

LiquidCrystal lcd(12,11,5,4,3,2);
const int sensorPin = A5;
const float baselineTemp = 20.0;

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

void loop() {
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor value: ");
  Serial.print(sensorVal);
  float voltage = (sensorVal / 1024.0) * 5.0;
  Serial.print(", volts: ");
  Serial.print(voltage);
  Serial.print(", degrees C: ");
  float temperature = (voltage - .5) * 100;
  Serial.print(temperature);
  Serial.print(", degrees F: ");
  float fahrenheit = (temperature * 1.8 + 32);
  Serial.println(fahrenheit);
  delay(1000);
  lcd.begin(16,2);
  lcd.print(fahrenheit);
  lcd.print(" degrees F");
  float averageTemp;
  if(temperature < baselineTemp) {
    lcd.setCursor(0,1);
    lcd.print("Below room temp");
  }
}

Don't take power for LCD from Uno pins. Connect LCD power to separate power source.


Arduino pro mini (clone) @1Mhz target does not answer Recently I have been experimenting with battery powered sensor (mySensors).

I created node with 3.3V Arduino Pro Mini (ATMega328P @ 8Mhz with nordic radio chip and BME280 sensor) and successfully programed it many times using either USBAsp programmer or serial (to USB) programmer.

I wanted to lower power consumption and so I disconnected power led and burned fuses as follows:
lfuse 62
hfuse DA
efuse 7

It worked successfully and I recompiled the sketch and upload it with USBasp.
I got an error that data cant be verified. It was late in the night so I jumped to Internet and googled it. In one forum I found, post (which I am unable to find again) that stated the he was able to upload sketch when he switched programmer to 5V. (Power was connected to Vcc)

I did that and it worked fine.

Than I tried to make change to sketch and upload it again (on 3,3V) and again got verification error so I unplugged programmer and switched back to 5V.

When I did that, the device stopped answering.

I regularly used this command to check that device responds and see fuses

avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -cusbasp -Pusb

What i did

Checked wiring.
Tried program fuses on blank new arduino - worked (programmer is
fine)
Measured voltage ok
Measured current (its around 4mA, I see it as the board is not
sleeping and is actively doing something)
I noticed that when I issue command mentioned above the on board led
quickly lights up and then goes off again.
I tried to power it from raw, from Vcc and from Vcc on serial hader (picture).
I measured power on Vcc when connected to Raw pin and it reads 3.3V
so power regulator should be ok.
I used -B10 switch to averdude with no luck

My question is

Is it possible that I burned the ATMega chip?
Is it possible that I see target not answering because of USBAsp is unable to lower programming frequency? (warning: cannot set sck period. please check for usbasp firmware update.)

Please suggest if there is anything I can try before throwing it out.

Thank you.

EDIT 2017-01-07
I was able to brick another board.
I think that the programmer is the cause.

I tried to upload bootloader with fuses from arduino and it failed with verification error.

I was able to burn bootloader from command line after seting fuses and restarting the board.

When I tried to upload the program it I got

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x00 != 0x0c
avrdude: verification error; content mismatch

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: lfuse changed! Was 62, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: hfuse changed! Was da, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: efuse changed! Was 7, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: Fuses OK (H:07, E:DA, L:62)

I answered yes because in in earlier attempts it just froze.

Now the board is in same condition as the first one.

Is it possible to revive it?
Thanks.

I am closing this thread.

The board is probably not destroyed, more likely are fused corrupted.
There are ways of reviving ATMega328 chip and program fuses back its called high voltage programming. You need to probably unsolder the chip or modify your board (post from tontrack).

Also if you are wondering what to do or not to your Arduino board here is quite interesting page (you wil find it in comment).

I did not found a way how it could have happen but it did.

Anyway Iam done with UsbAsp programmer and ordered AVR pocket programmer. Until it arrives I stop any more attempts.

Hope this helps somebody.


Using different ADC channels How could the same code be used with different ADC channels?

const byte adcPin = 0;  // A0

const int MAX_RESULTS = 100;

volatile int resultsV [MAX_RESULTS];
volatile int resultsI [MAX_RESULTS];

volatile int resultNumber;

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

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);
  OCR1A = 338;
  OCR1B = 338;   // 39 = 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  //  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering
}

// ADC complete ISR
ISR (ADC_vect)
{
  resultsV[resultNumber++] = ADC;

  //resultsI[resultNumber++] = ADC;

  if (resultNumber == MAX_RESULTS)
  {
    ADCSRA = 0;  // turn off ADC
  }
}

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void loop () {

  while (resultNumber < MAX_RESULTS)
  { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.print( resultsV);
    Serial.print("   ");
    Serial.print( resultsI);
    Serial.println();
  }
  resultNumber = 0;
  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF) | bit (ADPS2) | bit (ADATE);
  // turn ADC back on
}

From what I understand, you want to read two ADC channels
simultaneously. First, you have to understand that you cannot read them
exactly at the same time, as you have a single ADC. What you can do,
however, is read them one after the other: you read the V channel, then
the I channel, then the V channel again, etc. This means you will have
to change the multiplexer setting (the ADMUX register) in between the
readings. The most convenient place to do this is within the ADC ISR,
the logic of which becomes:

Save the value that has just been read
switch the multiplexer to the other channel
turn off the ADC if you are done.

Example code (not tested):

const byte PIN_V = 0;  // A0
const byte PIN_I = 1;  // A1

// ADC complete ISR.
ISR(ADC_vect)
{
    if (ADMUX & 7 == PIN_V) {
        // We have just read the V channel.
        // Save the value and switch to the I channel.
        resultsV[resultNumber] = ADC;
        ADMUX = bit(REFS0) | PIN_I;
    } else {
        // Otherwise we completed a (V, I) pair, we can increment
        // resultNumber.
        resultsI[resultNumber++] = ADC;
        ADMUX = bit(REFS0) | PIN_V;
    }

    // Turn off the ADC when done.
    if (resultNumber == MAX_RESULTS)
        ADCSRA = 0;
}

Note that this example assumes you do the readings in the (V, I) order.
Thus, within setup(), you have to initialize the multiplexer for the V
channel, as in

ADMUX = bit(REFS0) | PIN_V;


Library to send large amount of data over 433 MHz I am trying to communicate between two Arduinos using two RF 433 MHz modules (transmitter receiver). I found that the library Wildewire.h allows a maximum of 77 bytes so is there any another library that allows to send a more than that?

Radio modules send packets of data (and for very good reasons) so, if the total size of the data you want to send is greater than the packet limit, you have to engineer a higher level system (called a protocol) that can split your bigger message up into chunks that can be handled by the .h file.

I'm not saying one isn't available and indeed you may find one but, if you don't find one, you are facing the design of a protocol to handle bigger messages. It's not too difficult - imagine splitting the data you wish to send into 64 byte chunks and appending a single byte at the start of the data that describes the packet payload: -

As being a full message
As being a start of message (message overruns 64 bytes)
As being a mid message
As being an end of message (i.e. the last few bytes of data in the message)

This is enough information for your receiver code to reconstruct the original message but make sure you do good error checking if there isn't sufficient in the .h code. And also make sure your receiver "acknowledges" each packet received as being error free.

You might also wish to embed an address that makes your transmission and reception more robust or even add a packet count to the mid message marker byte. You have a maximum of 77 bytes for the payload so you have a few bytes spare for improving integrity but, the minimum payload system is 1 byte header and 76 bytes of payload (which may include other checks like CRC).


Problem controlling a Stepper motor with AccelStepper I have an Arduino connected to a stepper motor with an Easy Driver as follows:

I am controlling the position of the stepper motor using the Serial. This is my code:

#include <AccelStepper.h>
AccelStepper stepper(1, 9, 8);

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(10000);
  stepper.setAcceleration(5000);
}

void loop()
{
  char c;
  if(Serial.available())
  {
   int steps = Serial.parseInt();
   Serial.print(steps);
   stepper.moveTo(steps);

  }
  stepper.run();
}

The code works well but I'm facing a problem, when I set a high position value, it starts turning in the opposite direction, like if there was a limit on the steps. Does anyone know why it starts turning to the opposite direction?

I have tried to solve this problem by using:

if (stepper1.distanceToGo() == 0)
         {
            stepper1.setCurrentPosition(0);
         }

so I can set lower values to the serial. But the problem goes back again when the value goes up to the power of 6 (like 1000000).

Any idea?

Thanks!

Ints on vanilla Arduinos are 16 bits, and signed, which means they hold values from -2^15 to +2^15-1, so of course you cannot assign 10^6 to one of them. Use unsigned long (4 bytes), or, better yet, specify the length explicitly by using uint32_t.


Arduino Uno rev 3 - what are the additional 2x3 set of pins for? I recently bought Arduino Uno rev 3 board and I spent a lot of time trying to figure out the function of each individual pin. I googled all the fancy terms like IOREF, SDA, etc. and one by one I figured out the functional purpose for most of the pins.

However, there are few pins (actually pin groups) which have no labels around and I find it really difficult to figure out what these pins are supposed to do.

Again, I googled around and found this schematic from which I figured out that the 6-pin group  at the bottom is about something called ICSP (or at least this is what is written there). When I googled this term, I found this excellent explanation about the serial communication protocols.

However, at this point I am really confused.

The explanation about the serial protocols doesn't mention at all ICSP. By googling even further I only get more and more confused. Yes, I found the ICSP wiki page but I am not 100% sure that the bottom 6 pins are related to ICSP.
From the same schematic which I found I see there are 4 additional soldered pads with label JP2 right above them. Currently I have no clue about the function of these pads. Question 1 - what are these soldered pads for?
Right next to the JP2 stuff is a group of 6 pins (3 rows, 2 columns). The schematic is not clear about these pins. Question 2 - what is the purpose of these pins? Question 3 - where can I find the actual schematic (layout) about each individual pin?
I am not 100% sure that the bottom group of pins (2 rows, 3 columns) is related to ICSP. Maybe that's the case, maybe it's not. Question 4 - what is the purpose of these pins? Question 5 - where can I find the actual schematic (layout) about each individual pin?

Thank you in advance for your help!

The ICSP pins have two functions:

For programming the ATMega328P directly using a hardware programmer (In Circuit Serial Programmimg)
SPI connections for shields in a standard place.

They are used for SPI because different boards have the SPI pins on the main headers in different locations. All boards should have this 6-pin block in the same place though meaning that shields can then work with more boards.

On the Uno they share the same physical connections as digital pins 11-13 plus reset and power.

JP2 and the other 6-pin block are connected to the USB interface chip (ATMega16U2). The 6 pin block provide ICSP for programming that chip. The other 4 (unpopulated) pins connect to GPIO pins on that same chip. They can be used for anything you like if you replace the firmware on the USB chip.

For now ignore those two pin groups. They aren't really anything to do with the Arduino side of things, only the USB interface.

You can find all this on the official Uno schematic which is on the official Uno product page: https://www.arduino.cc/en/Main/ArduinoBoardUno


Arduino Pro Mini Serial Monitor garbage This is my first post. I hope that I am posting in the right section of the forum. Otherwise, could an admin move this topic to the appropriate section please?

Board : Arduino Pro Mini 3.3V 8MHz

Arduino IDE : 1.6.12
Arduino is powered by a FTDI Board and USB Mini-B cable from the computer USB port in the following order :

Arduino        FTDI

BLK              GND

GND             CTS

VCC             VCC

RXi              TX

TXo             RX

DTR             DTR

Also, I have connected a HC-06 bluetooth module in the following order :

Arduino    HC-06

GND         GND

VCC         VCC

D10         TXD

D11         RXD

The Serial Monitor is open on COM4, Newline, 9600 baud.

The code that I'm trying to run is :

#include <SoftwareSerial.h>
SoftwareSerial BT(10, 11);
void setup()
{
  pinMode(13, OUTPUT);
  BT.begin(9600);
  // Send test message to other device
  BT.println("Hello from BTSerial");

  Serial.begin(9600);
  Serial.println("Hello from Serial");
}

char a; // stores incoming character from other device
void loop()
{

  if (BT.available())
  // if text arrived in from BT serial...
  {
    a=(BT.read());
    if (a=='1')
    {
      digitalWrite(13, HIGH);
      BT.println("LED on");
    }
    if (a=='2')
    {
      digitalWrite(13, LOW);
      BT.println("LED off");
    }
    if (a=='?')
    {
      BT.println("Send '1' to turn LED on");
      BT.println("Send '2' to turn LED on");
    }
    Serial.println(a);
  }
}

I am trying to communicate with the HC-06 from an Android phone.
I am posting in this section of the forum because when I send a message from the phone to Arduino the following is printed in the Serial Monitor :

à„…€ƒ¦¤„„‡…§¤¦„‡Å„EóAãbBãbHãb

When I am trying to send a message from Arduino to the phone, nothing is received on the phone.

Could someone please explain why I get garbage output on the Serial Monitor even though the baud rate is the same in the code as it is in Serial Monitor window?
Is there a problem with the Arduino IDE?

Edit 12.11.2016

This is what I get when I open the Serial Monitor in the Arduino IDE with this code :
Newline, Baud rate 9600

‚Æ‡¥Ç$¤†Fó

If I change the Serial Monitor properties to Newline, Baud rate 19200 this is what I receive :

Hello from Serial

On the Android phone application I do not get anything printed.

Also, please note that this question is also addressed on the Arduino forum at the following link :
http://forum.arduino.cc/index.php?topic=434623.0
I will try and answer in both places as I am not sure that everybody has an account on the forum

Flip the RX and TX wires of the HC06. This is because this statement : SoftwareSerial BT(10, 11); actually means SoftwareSerial BT(RXpin, TXpin);. Considering this, 10 is your Rx and 11 is your Tx. In this case, you have to connect pin 10 (software Rx) of your Arduino to the Tx pin of your HC06 and pin 11 (software Tx) to the Rx pin.


Scheduled loops using same function I am using an Arduino due and have multiple schedules running at the same time. I am using this Library.

I have a function that 3 different loops use. Two of the loops are driven by user interaction so timing is not possible. The function does reset global variables and I would have no issue with the variables being reset multiple times as it wouldn't cause any problems for me.

What I was wondering, on the very slim chance that two loops called the function at the same time, is it possible for the loops to modify the same variable at identical times?

My understanding of the scheduler would lead me to believe that the scheduler will only yield to another loop after it has completed a line of code and thus the to instructions to reset the global variable could not happen at the very same time, just extremely quickly one after the other.

Would this be a correct assumption?

It is a simple schedular. It only changes to another task when yield() is called. The delay() function uses yield() and a lot of code and libraries use delay().
That means that if you code does not contain a delay() then you need to call delay() or yield() now and then, or other tasks will never execute.
It is probably safe to use the same function, but every time a delay() is used, an other task could run or another task will continue from there.


Is there a way to setup an interrupt to trigger at n number of clock cycles from now? I currently have an nRF transmitter/receiver pair setup on my desk. The transmitter is sending a single byte (0xAA) every 5ms. The receiver sets an LED high to indicate that it received the byte, which is about 10us (+/-2) after the byte was sent. I want to use this nRF pulse for a precise timing/sync application with +/-0.5us accuracy so I need to filter these receiver pulses such that I can estimate the time the transmitter actually sent the byte and the time the next one should arrive. I created an algorithm that uses past nRF pulse times (measured in clock cycles using Teensy's ARM_DWT_CYCCNT register) to estimate the next pulse and it seems to be working reasonably well - though I can't say yet if I'll get the 0.5us accuracy I want.

Now I want to take that estimate and have my microcontroller set an output pin high as soon as the clock count reaches the estimated clock value. Currently I do this by waiting in a while loop and polling the register, but the loop itself takes up several hundred clock cycles which reduces my accuracy. Is there a way to instead have an interrupt trigger when the clock cycle counter reaches my estimated value? I would somehow need to set this interrupt after computing each estimate.

Thanks!

Use a timer to count the system clock and preload the counter with an offset that overflows in the desired cycles.
Use a timer to count the system clock and set a compare match a desired number of cycles out.

To expand the number of cycles, you can do fancier processing in thee Isr but the basic gist IS the same.

Other approaches also exist but the two outlined here are easier.


Clearing SRAM in loop() Very broad question here.  I don't know exactly what the problem is but I'll edit this post as we narrow down the possibilities.

I think I'm running into memory constraints.

I'm running a sketch that records two temperature values every 60 seconds and transmits them to an AWS RDB via wifi.  It works well for about two hours then stops.  I don't know if it's a memory constraint but I suspect that it is.  What other common problems (often overlooked by newbies) can cause a sketch to end after a couple hours of run-time?

Is there a simple way to add an instruction to a loop to clear the SRAM?

Arduino UNO + WiFi 101

Edit #1 12/24/2015:It's the WiFi board.  It happily remains connected to my phone's hotspot but only lasts an hour or two on my home network.  Working on root cause...any ideas are welcome!

Edit #2 12/25/2015:Tried to Wifi.disconnect() and reconnect with no luck.  Why do some networks kick the board off while others work just fine?  Will look into the watchdog.

The problem was solved with a "soft restart" loop. Posts #10 and #11 are all I needed:
http://forum.arduino.cc/index.php?topic=49581.0


Can I Implement a PLL on an Arduino? Is it possible to create a system like a PLL using an Arduino?
I ask this because there are some parts in the PLL system, such as: phase detector, VCO, divider, and I don't know how to make for each part in Arduino board.

A PLL is a very complex device which is not something that can easily be created purely in code.

Many microcontrollers include a PLL as part of their oscillator systemm which allows them to run internally at a higher speed than their external crystal.  This is not a programmable peripheral that you can use for your own things, but an integral part of the workings of the microcontroller.

While it may be possible to write one in software the results would be very somewhat limited. The best you could hope for is to use timers to measure an incoming frequency and use the results to output another frequency through some means, maybe PWM.

To create a real PLL you would be best off using either a dedicated PLL chip (which you can buy off the shelf) or use some form of programmable logic like a CPLD that has a built in PLL block.

Some microcontrollers, most notably the Cypress PSoC range, have programmable logic blocks built in that may be more suited to your task than an Arduino.

A typical digital PLL looks something like this:

Implementing all that in code would be both tricky and somewhat slow on a little 8-bit MCU with no floating point support.  However, the basic principal of what a PLL can be summarised in one simple sentence:

  The frequency coming in determines the frequency going out.

The PLL, or Phase Locked Loop is just one method of achieving that desired result.

Another method, which is not using any form of PLL, is purely algorithmic and consists of just three things:

Three simple blocks, all of which the Arduino is, to a certain extent, capable of performing.

The first block, the Frequency Detector, works out what the frequency of the incoming signal is.  That could either be by counting the number of pulses that arrive over a certain time frame, or measuring the time between successive pulses.  Which method you use (Frequency Counting or Frequency Measuring) is really down to what frequency ranges you are using.  Frequency Counting is better for higher frequencies, whereas Frequency Measuring is better for low frequencies.  There are many examples on the web of how to do both of those using timers on the Arduino.

The Decision Making is basically working out what your output frequency wants to be according to your input frequency.  This could be as simple as "Output = input * 2", for instance, or something more complex like "Between these frequencies I want to output this frequency, between these frequencies this other frequency, etc".  It's entirely up to you.

The third block just takes the decided-upon output frequency and generates it.  That could be done using the hardware PWM generation of the Arduino.

All this, though, will be limited to relatively low frequencies (tens of kHz maximum really) though with clever coding you could push it up slightly higher.

One thing that really makes this method differ from a PLL is that you don't get the "PL" portion of it - that is, the phase of the incoming frequency is lost, and the output frequency is running entirely with its own phase.  There is little or nothing you can do to synchronise the phases of the input and output like you get with a full PLL.


Why echo "R" > /dev/ttyUSB0 doesn't work, but on the same PC Serial Monitor in Arduino IDE works? I have a strange problem. I am running Ubuntu and NodeMCU si plugged into USB. I have very simple sketch running on it, when it reads letter "R" on serial, it turns ON relay.
When I open Serial Monitor in Arduino IDE and I type letter "R" and send it, it works perfectly. However when I run commands below, it does nothing:
stty -F /dev/ttyUSB0 115200
echo "R" > /dev/ttyUSB0

I tried running the same commands on different PC with Ubuntu and these system commands work just fine.
I also tried copying exact same configuration from stty -a -F /dev/ttyUSB from PC where it works to PC where it doesn't, but it didn't help either.
I don't think it's driver issue, because if it would, then I suppose it wouldn't work with Serial Monitor also.
Thank you for any help or hints in advance.

I had the same issue.
After entering command that Majenko suggested:
stty -F /dev/ttyUSB0 -hupcl

I still wasn't able to send commands to Arduino nano.
Strangely, when I open Arduino IDE Serial Monitor and send command it works.
When I close it, I can send commands in terminal to Arduino for some time. Then it stops working again :/


Extra `eecfbba=.@aa` file in sd card I am doing a project, and I need an SD card. Everything worked well, but after a while when I read the SD card from my PC(Windows 10 64 bit, Intel Core), I found a file called eecfbba=.@aa. It's so big that it almost ate up one GB storage of my SD card. But when I tried to open it with notepad, notepad tells me that there is actually no such file, and asks me if I want to create it. I tried to delete it, but file explorer also told me there is no such file. What is it?

This is my code:

#include <ArduinoJson.h>

// Version 0.20.1.19.3.7:
// 2020/01/19, 16:10, button record test, 7th version.

#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#include <Wire.h>
#include "RTClib.h"
//#include <string.h>

RTC_DS1307 rtc;
String strdoc;
char daysOfTheWeek[7][2] = {"su", "mo", "tu", "we", "th", "fr", "sa"};
#define SD_ChipSelectPin 10  // 如果使用 arduino nano 328 可使用Pin4

TMRpcm audio;
void setup() {
  audio.speakerPin = 8;
  Serial.begin(9600);
  pinMode(25, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  else
  {
    Serial.println("rtc started");
  }

  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("SD Fail");
    return;
  } else {
    Serial.println("SD OK");
  }

  audio.setVolume(6);
  audio.CSPin = SD_ChipSelectPin;

  StaticJsonDocument<200> doc;
  doc["sensor"] = "gps";
  doc["time"] = 1351824120;
  JsonArray data = doc.createNestedArray("data");
  data.add(48.756080);
  data.add(2.302038);
  serializeJson(doc, strdoc);
}
bool isrecording = false;
bool recordButtonPressed()
{
  return (digitalRead(25) == LOW);
}
bool playButtonPressed()
{
  return (digitalRead(7) == LOW);
}
void loop() {
  delay(200);
  // Below is the formatted datetime.
  DateTime now = rtc.now();
  // Below is the serialized datetime.
  String filename = (String)(now.unixtime() % 10000000) + ".j";
  //  Serial.println(filename);
  if (recordButtonPressed())
    if (!isrecording)
    {
      isrecording = true;
      audio.startRecording("test.wav", 16000, A0);
      Serial.println("stt");
    }
    else
    {
      isrecording = false;
      Serial.println("stp");
      audio.stopRecording("test.wav");
    }
  Serial.println("sdsad991===`=`");
  if (playButtonPressed())
  {
    audio.play("test.wav");
    Serial.println("ply");
  }
  String dataString = strdoc;
  if (!isrecording)
  {
    File dataFile = SD.open(filename, FILE_WRITE);

    if (!dataFile) {
      Serial.println(F("Failed to create file"));
    }
    else
    {
      dataFile.println(dataString);
      Serial.println("Wrote string.");
      dataFile.close();
      Serial.println("Closed file.");
    }
  }
  /* Please ignore this line */
  //  //    audio.play("test.wav"); break;audio.volume(1); break;audio.volume(0); break;audio.stopPlayback(); break;
}

P.S. I'm using Mega 2560, so MISO, MOSI, SCK and CS pins are different.(Which is 50,51,52,10).

Edit 2020/1/25, 14:15(Beijing Time) At 1/20 I have bigger problems. There are more and more big files. All of them are the same situation. For details, take a look at this photo(ignore selected files): Imgur or 咱们中国人上不去imgur，用这个：File-up（直接下载）

Thanks to @Juraj, I fixed the problem. Deleted those files by manually formatting the SD card.

This is not really the answer, you can see the answer in this comment under the question.


Why does my Arduino IDE hang/crash so often? I've traditionally used a text editor with avr-gcc and makefiles for working with Arduino boards. I'm now trying to develop projects for the wider Arduino user-base, so I am trying to use the Arduino libraries and common IDEs for ease of use.

I started using Stino, but then found out that the Arduino IDE has some toolchain "quirks" that mean I will need to test everything in Arduino IDE expressly.

Since starting to use it more, I have found it frequently hangs or crashes. The triggers for this are:

Creating a new sketch takes about 15s, and shows me the OS X beach
ball.
Saving a sketch takes about 15s.
Going to File->Examples frequently crashes the IDE - I need to force quit.
Going to
File->Sketchbook always crashes the IDE.
It sometimes randomly hangs.

I don't have any other stability issues and other Java based IDEs like Pycharm work flawlessly.

I have installed numerous libraries, including the entire Teensyduino suite (which is a lot of libraries!). Outside of that, no changes have been made.

Is this a common issue? Is there any logging or anyway I can try and work out what is causing this issue?

This is happening with:
 - Arduino 1.05
 - Arduino 1.55

I have tried uninstalling and reinstalling.

Just report it to Arduino.

You don't really have any other option. I've been waiting to answer this question until I was sure that no one here knew the answer. You don't really have any other option.

This seems like a bug. We're not Arduino developers or a bug tracking site. We can only do so much here. Even if it was confirmed a bug and we fixed it, there's only so much that can be done without submitting a report.

BEFORE YOU SUBMIT A REPORT:

I'd try copying out the libraries from Arduino. So many libraries
might make Arduino IDE somewhat heavier. I don't know if it'll really
affect the sluggishness but it's worth a shot.
The only other thing that I can think of, besides RAM (which you
already said wasn't an issue) and the libraries, is some sort of
cache/temporary file. Try reinstalling Arduino, even if you haven't,
and also I'd try using the beta 1.5.6-r2
version. It has to be pretty
stable for it to be the only version that supports the YUN and DUE.
Both have been out for a considerable amount of time with this
software, so I'd imagine that it's pretty stable minus a few issues.

  Many things are said to have been improved compared to the previous 1.0.5-r2 version.

It'd be stupid not to try the newer version.


How to keep amperage in serial and parallel? I have a 2000mA AC adapter and also I have the lights that I show here:

Each of these lights consume up to 300mA.

If I make a circuit with 3 lights in serial, ¿will the amperage of each light decrease?

If I make a circuit with 3 lights in parallel, ¿will the amperage of each light decrease?

I am asking it because I don't want the lights to decrease the luminosity. I want the maximum luminosity in each light.

The lights are for growing lettuces. Now I am using a low consumption light but are not efficient:

You haven't said what the voltage rating of your Power Supply is, but if we assume it is a "constant voltage" regulated supply, then it will attempt to maintain a constant voltage up to the rated current capacity (2000 mA).

If you put your LEDs in series, then the voltage from your power supply is distributed across the LEDs, and is therefore lower on each LED. This would cause your LEDs to be less bright.

If you put your LEDs in parallel, then the voltage remains constant.


Control arduino with keybaord via computer I'm brand new to arduino but I'm trying to figure out how to set up a WASD steering system for my robot I made.

I have the physical setup all ready but I don't know the code to use that would allow me to use my computers keyboard. I would like to still have my keyboard attached to my computer while I do this. I.E. I don't want to manually plug the keyboard into arduino.

I asked this on Robotics stack exchange but they said to ask here.

A list of functions/blocks Iof code that is applicable would be the best answer, but I'll take anything that'll get my bot moving :)

Edit I'm using a wireless keyboard, but my arduino is connected via USB.

The problem with using the keyboard is the device would have to be tethered to your computer. If you mean for this "robot" to be an explorer, that limits its choices. If it's an arm or something that stays in place, you're fine using the typical serial libraries to monitor your keyboard for input like Chris suggests.

Unfortunately, I don't know of any way to simply plug in the USB keyboard and take in keys. Usually, serial communication is processed between two systems much like two people texting each other. When you see the light blinking on your phone, you know you have a text and how to open it to retrieve the message. In the case of the Arduino, it's checking for a flag bit called RX for the received message and flags a bit for transmitting a message (TX). Each system then pulls down its message and interprets it. In the case of your sketch, you'll be looking for this flag and schedule an action whenever it's checked. Read about Serial communications here and work through the examples to get a feel for it. Because you probably want a real-time response, it might be worth your while to check out interrupts, as well. These are sudden events that get flagged (such as receiving your text) and get handled immediately instead of waiting for the program to refresh and search for the values manually. As a final note, baud rates are the calculated time frames you and your recipient agree on. It would be difficult to receive a full message if you kept cutting off your friend, so it is with computers. This stuff can kind of be tricky at first, but keep at it. Nothing is more ridiculously satisfying than getting that response character from your device.

There's a neat tutorial for getting your Arduino to work through your iPhone here, but it requires an ethernet board, which means a router and wireless board.

Without knowing what you intend to do with it, it's hard to say how to help, but I hope this gets you into it.


Can I power two 5V with Arduino powered with 9V power adapter? I have a setup where I have a 5V IR receiver and 5V relay board and Arduino Uno.

I am currently powering the Arduino from the PC USB and both the IR receiver and the relay board from the Arduino. And it works fine.

Now I want to know how it would work when I power it with a 9 volts wall adapter. Will the voltage be enough for both the IR receiver and the relay board? And will Arduino work fine?

The voltage will be fine - as long as you plug it into the DC barrel jack, and don't try to wire directly to the 5V pins. The barrel jack has a voltage regulator on it that will convert 7-12V down to the required 5V.

But there's a second reading that you need to look at, not just voltage. The 9V adapter will also have a current rating expressed in milliamps (mA) or amps (A, which is 1,000 mA). The Arduino needs around 25 mA to do its thing, and your adapters add to the total current - maybe 20 mA each again. So if your adapter only provides 50 mA, it won't be able to provide enough current and the system won't work.

The USB port provides 5V, but it also provides up to 500 mA, which is more than enough for the job. If your wall adapter is 100 mA or above, that should be enough. And unlike voltage, a larger number for current is better - that's its maximum capacity of supply, rather than something that will burn out the equiment!


Arduino Nano PWM pin not functioning I am building a project using an Arduino Nano. In it, I am using pin 3 as PWM output. However, If I supply values lower than 255 to it, the pin does not output any voltage at all.

According to this diagram, pin 3 is PWM:

I have tested it on two boards, it doesn't function on either one. It's not my sketch, either (I tested it with a simple analogWrite();).

This is the code:

void setup() {
  // put your setup code here, to run once:
  #define E1 3  // Enable Pin for motor 1
  #define E2 10  // Enable Pin for motor 2
  #define I1 4  // Control pin 1 for motor 1
  #define I2 2  // Control pin 2 for motor 1
  #define I3 A1  // Control pin 1 for motor 2
  #define I4 A0  // Control pin 2 for motor 2
}

void loop() {
  // put your main code here, to run repeatedly:
  // I use differential steering, speed is important
  analogWrite(E1, 100); // Run in full speed
  analogWrite(E2, 100); // Run in full speed

  // always go forward
  digitalWrite(I1, LOW);
  digitalWrite(I2, HIGH);
  digitalWrite(I3, LOW);
  digitalWrite(I4, HIGH);
}

What could be the reason of this?

Try to replace #define E1 3 with #define E1 PD3 and see if that helps.

The PBx, PCx and PDx designations are unambiguous, so using those are pretty much a safe bet.


Getting better results from DHT22 I am working on a dew point sensor, and I am using the Arduino Uno board with the DHT22 sensor. I have it taking a reading once ever 2 seconds and I am using the DHT.h library.
The problem I am having is when I compare the values to our standard here the Humidity reads high and the Temp reads low. Is there anyway to get the values to read closer to what the standard is?

Using a RH and Temp Calibrator I had access to I was able to get better results by all lines to adjust the RH and Temp to a better value. Basically a correction equation.


AMIS30543 - Library code | Order of pinDirection and pinOut This piece of code was taken from AMIS30543- Arduino library,
void init(uint8_t slaveSelectPin) {
    ssPin = slaveSelectPin;
    digitalWrite(ssPin, HIGH);
    pinMode(ssPin, OUTPUT);
}

Facts I know

digitalWrite - makes the pin to the corresponding voltage level
pinMode - makes the pin either input or output
ssPin is active low pin usually.

So I was wondering before setting the pinDirection why the pin is made HIGH, Then immediately after that the pinDirection was declared as OUTPUT
Also I know , if a pin was made HIGH and on the next line if the direction of the same is set as  INPUT will bring the internal pull up resistor in action .
So what am I missing here. More over in Arduino does the order of pinMode/digitalWrite matter.? if So what is the meaning of this particular lines of code Github link to the library

The library is doing this to make sure, that the pin will never go low during initialization.
Imagine doing it the other way round:
pinMode(ssPin, OUTPUT);
digitalWrite(ssPin, HIGH);

If the corresponding PORT bit is set to zero (LOW) previously (which is also the standard after reset/power cycle), the pin will go LOW for a very short time, until digitalWrite() sets it HIGH again. That LOW time is short, but it might needlessly activate the slave. If you first use digitalWrite(ssPin, HIGH), you activate the internal pullup (as standard mode after reset/power cycle is INPUT) and set the corresponding PORT bit to 1. Thus, when you now change the pin mode, the pin is HIGH immediately, without ever going to LOW in between.
Internally the Arduino uses 3 SFRs (Special Function Registers), which are directly connected to the IO hardware of the pins. The DDR register of each port controls the "pin mode" aka direction of the pin (input or output). The PORT register controls the output value (HIGH or LOW; or turning the pullup resistor on or off in input mode). The PIN register reflects the current state of the pin (for reading it). In this case the double function of the PORT register is important, as it activates the internal pullup resistor, when set while in input mode.


How to connect an LED to Arduino LilyPad Mp3 can anyone help me with connecting LED to Arduino LilyPad Mp3  in a way, that each switch (1 of 5) light up a different LED?

I tried connecting an LED between the switch and the board, then the LED light up, but the speaker does not play the audio file.

I also tried connecting an LED directly to the speaker, then LED lights up and the speaker plays the sound file, but the problem is that all of the LED´s light up at the same time....

You might try connecting the anode side of your LEDs through a current limiting resistor to the positive side of the supply.  Then connecting the cathode side of the LED to the switched pin on the Arduino LilyPad Mp3.  So, in this diagram:

...that would be the pads where the switches are connected.

The current limiting resistor depends on the specifications of the LED.  Check the voltage and current required to light the LED.  Subtract the voltage needed from your supply voltage.  Then use the V=IR equation and solve for R.  That is, V = the voltage difference between your supply and what is needed by the LED and I is the current (probably in milliamps, so watch your math!) that the LED needs to light up properly.  You will probably need small current limiting resistors somewhere around between 100 and 800 ohms.

Added later...

Thanks to @Gerben we have a diagram of what I was describing:

In Gerben's diagram he has used the regulated 3 volt output of the Arduino LilyPad Mp3.  We can double check all the pin labels using a diagram from Sparkfun:

You should be able to repeat this circuit for each switch.  Sparkfun has an LED tutorial here.  But I'm not very happy with their guess approach when picking out a current limiting resistor.  Ah, this tutorial is much more to the point.

So, if we assume the LEDs you are using need 3mA @ 3V (remember to use values for YOUR LEDs!) and use this equation (Vs = supply voltage and Vf = LED voltage):

...then we set it up like (3 - 3) / (0.03) which is zero.  That's because I was using LEDs that work at 3 volts.  But if I used LEDs that worked at 3mA at 1.8V then I need... (3 - 1.8) / (0.03) = 40 ohm resistors.  Or there about. As most resistor values are on a log scale I suspect there should be a 47 ohm available.


Coding problem (gesture sensor) Hi I am using an Arduino Mega 2560 with two sparkfun zx gesture sensors, two servos, 4 rgb leds strips and 4 light switches.

With the sensor, the code relies on interrupts, which interfere with the bahaviour of the servo and leds.

My knowledge of coding is limited so I am unsure of how to work around this, I think I have to introduce some new code.
interrupts leds and servos
However, I am unsure of how to introduce it.

Any help would be appreciated.

Driving servos and LEDs from a hardware PWM may help. They will maintain a steady state even if there are interrupts. They may be a little less responsive to changes if there are interrupts.

Are you doing too much when the sensor interrupts? Typically a sensor makes multiple measurements and may be filters the results. When it is ready it interrupts. In the interrupt it should do as little as possible. Typically sending a message via global to a polling function that is not running in an interrupt. For example it may set a flag and the poling function reads the result. Reading the result in the interrupt would be bad.


2 way communication between Arduino with XBee and Computer I have an Arduino Uno with a Wireless SD Shield and XBee S1 and a PC with another XBee S1 connected to it. What I'm after is for me to be able to send a message from my computer and receive a message back from the Arduino (For now let's just say if the Arduino receives a "1" I want it to send an "A" back)
Here is the code I have been practicing with (courtesy of SparkFun)

#include <SoftwareSerial.h>
SoftwareSerial XBee(0, 1); // RX, TX

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

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

(I have changed the pins from 2,3 to 0,1 as the latter is on the Arduino itself)
I have set my Xbees up and have been able to get them to talk to each other when both connected to separate PC's, but I am having trouble getting the Arduino to send information to the other XBee. When I try and send data from the Arduino IDE both RX and TX Led's flash.
Could anyone steer me in the right direction?

You don't need to declare an extra (software) serial port because the wireless shield connects the Arduino TX and RX on pins 0 and 1 directly to the TX and RX of the Xbee. So, Serial.available, Serial.read and Serial.write directly addresses the xbee. Just leave out the software serial from your code and it should work.


Stepper motor jittering I'm trying to make a nema17 stepper motor work using ramps1.4 and A4988 driver.
But when I'm trying to rotate motor, it spins with almost no torque and constant shaking.

Motor 2-phase nema17 , Step Angle 1.8° .
Power supply 12v/60w.

Here is the sketch:
(I copied it from RepRap wiki , and removed everything except X Motor)

#define X_STEP_PIN         54
#define X_DIR_PIN          55
#define X_ENABLE_PIN       38

void setup()
{
  pinMode(X_STEP_PIN       , OUTPUT);
  pinMode(X_DIR_PIN        , OUTPUT);
  pinMode(X_ENABLE_PIN     , OUTPUT);
  digitalWrite(X_ENABLE_PIN, LOW);
}

void loop ()
{
  if (millis() % 10000 < 5000)
  {
    digitalWrite(X_DIR_PIN    , HIGH);
  }
  else
  {
    digitalWrite(X_DIR_PIN    , LOW);
  }

  digitalWrite(X_STEP_PIN     , HIGH);
  delay(1);
  digitalWrite(X_STEP_PIN     , LOW);
}

The wiring diagram:
(I have only X Motor plugged in)

and video: (Google Video link is dead @ 2017-02-09)

Add a second delay after:

digitalWrite(X_STEP_PIN    , LOW);

Also try increasing the delay maybe you are pulsing the step pin too fast.


What is the worst time case for Arduino Mega? I'm going to implement home automation using an Arduino Mega with 8*6=48 channels relay in my new home. I have prepared an Android app for an HC-05 Bluetooth controller. How much time can I keep running an Arduino Mega with all the appliances in a home? Can I keep it working 24/7 for a while?

Yes.

(For better guidance than that, we'd need to know more.)


Can I use string and int in Serial.println together? I just yesterday started programming on Arduino, and I have a little problem.

I want to print "#S|SKAITYMAS|[1]#" in one line, except instead of "1" I would like to use an int value. However, this one doesn't work:

Serial.println ("#S|SKAITYMAS|[",LINENR,"]#");

Any hint or tips would be appreciated.

The answer by canadiancyborg is fine. However, it is always better to avoid using String objects if at all possible, because they use dynamic memory allocation, which carries some risk of memory fragmentation. Simple and safe:

int answer = 42;
Serial.print("The answer is ");
Serial.println(answer);

The only drawback is that the constant string ("The answer is ") takes some RAM. This can be avoided by embedding it in the F() macro, which means “keep this in Flash memory only”. Then, the most memory-friendly idiom is:

int answer = 42;
Serial.print(F("The answer is "));
Serial.println(answer);


RS422 interfacing with the Arduino Good day,
I have a sensor which supports serial data output using RS422 which has 4 wires (RX+, RX-, TX+, TX-)
my question is how can I connect this sensor to the Arduino.
I read that i can use 2 max485 chips to do this but uncertain of the exact procedure.
Thanks in advance.

There are pre-made and very inexpensive Arduino RS-485 modules available on Ebay or Amazon.  Much simpler than building your own circuit.

They look like this:


Arduino IDE 1.8.13 won't launch properly Recently I have been trying to install Arduino IDE 1.8.13, and I have ran into according problem.
When trying to launch Arduino IDE with ./arduino command it shows according error:
./arduino: line 35: /home/wiktor/Downloads/arduino-1.8.13/java/bin/java: No such file or directory

I have checked and java file does indeed exist.
I am using 32 bit version of Arduino IDE and 32 bit version of Linux Alpine 3.13.3.
Thanks for all answers

Note: Below, technician 274 (the original poster) commented:

It ended up working, after following alpinelinux wiki and installing
the IDE using flatpak.

Part of the problem is how confusing the message is.
No such file or directory is not actually referring to the java file.  It's referring to the ld-linux.so interpreter specified in the elf file.
If you run the file command on the java executable, you'll see output that looks like:
./java/bin/java: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.9, not stripped

If you look for /lib/ld-linux.so.2, you're going to find that you don't have one, and that's the file it's complaining about.
Alpine Linux apparently uses Musl and the java binaries were compiled for glibc, which is normal for desktop Linux.  On a typical desktop Linux system, that the java that ships with the Arduino IDE was compiled for, all kinds of executables make use of ld-linux.so.2.  On your Alpine system, you'll find they're referring to /lib/ld-musl-i386.so.1 instead.  From this vantage point, it's more of a Linux problem than an Arduino one, but I thought it might as well have something of an answer to point people toward relevant looking resources:

https://wiki.alpinelinux.org/wiki/Running_glibc_programs
https://github.com/sgerrand/alpine-pkg-glibc

You may find it's easier to replace the java interpreter, but that won't be enough, because the Avrdude and GCC binaries will also expect ld-linux.so.2.
In the end, it may be easier to just not use Alpine Linux.


actual use of noTone() in arduino What is the use of noTone() function as the duration for which the note must be played can be specified using the third argument of note() function.

So that you can terminate the output prematurely, e.g. during an interrupt.


Why is the T2 transistor used in Arduino Micro? I was about to design a small custom board using ATmega32U4, replicating the Arduino Micro. I know that T1 is used to block VUSB when VIN is connected.

But why T2? The gate is 5V, so it will be always OFF! Or does it act as a diode?

Schemtic https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf

T1 and T2 implement a power supply ORing of the VUSB and VIN voltages. Read this for extended information.

The body diode of each MOSFET performs the basic ORing function. When the MOSFET is turned OFF it just behaves as a diode. But when the MOSFET is turned ON, the diode is shorted by the conduction channel, thus avoiding its voltage drop (and achieving a behaviour closer to an ideal diode).

So:

When VUSB is present and VIN is not connected (but pulled down to ground by R9), T1 turns ON and the +5V rail is connected to VUSB. Also, T2 turns OFF and the regulator input is isolated from VIN and the regulator simply doesn't operate (thus, avoiding a potential conflict because its output +5V is being forced to VUSB).
When VUSB is not connected and VIN is present, T1 turns OFF and VUSB is isolated from the +5V rail. Also T2 turns ON and VIN is connected to the regulator input, which then regulates the voltage down into the +5V rail.
When both VUSB and VIN are connected, the behaviour is the same as in case 2 above. Because VIN is supposed to be >7V and VUSB approx 5V, T1 will isolate VUSB and avoid a conflict with the regulator output. Also, a VIN >7V will allow T2 to turn on hard enough to bypass the body diode and avoid its voltage drop.


Modified Mesh networking using nrf24l01 I am trying to make a mesh network of three nrf24l01 nodes in which all three are transceivers, such that all three are in a line. The modification I want to make is that if two end nodes are not able to communicate with each other as they fall short of range the signal must be sent via the middle node. How should I approach?

To be honest, I still have to receive my RF's... But I have a similar problem, meaning I also need to have them all to both receive and transmit.

I thought it was not possible, since in a 6-1 network, one is receiver, 6 are transmitting. With auto-ack messages can be returned.

Depending on the amount of messages being sent and latency you can let them talk when needed and hope there is not too much sending simultaneously (causing resends).

One solution you could use, is to put in the message a receiver ID. Suppose the 'geographic location' of your objects are

A   <---->   B  <----> C

Assume A wants to send to C, but it will not be received by C, C does not auto-ack, and A knows this. Know A can send the message to B, which can auto-ack, and B has to send it to C. Possibly the original source (A) has to be added to the message as well, if this is important for C to know.

Update: (in steps)

Suppose A wants to send a message m to C

A sends message m to C
C does not receive it, thus is does not send an ACK-message back to A
A gets a timeout
A knows that message m has not been sent to C (so it is out of range)
A sends the message m to B (adding 'A' as sender of the message if not already done)
B receives message m
B sends an ACK back to A
A knows message m has been sent to B
B sends message m (with A as sender) to C
C receives the package
C sends back a message to B
B needs to send a message to A that m has been sent successfully

Some generic remarks:
- This scheme is maybe not full-proof or can be optimized (like that A knows from now on it needs to send to B first to reach C).
- Also both B and C can be out of range, you want to resend it (later)?


Dc motor backvoltage, how to place the diode correctly? My previous questions have been anwsered, so thank you all for that!

I make a new question post because I have some other problems with my setup. I use a esp12s 8266 chip. It sends a PWM signal to a n-channel mosfet, so I can regulate the speed of the dc motor that is attached to the drain of the mosfet. The DC motor has extra power from a 9v battery and this battery negative is connected to the GND of the 8266. I can control it with bluetooth hc-05 module, it has 3 options, 40%, 0% (off) and 100% (full power).

Here's the problem:
I can control everything and it seems like it works all fine, but when the motor starts spinning I see a yellow led flashing on my 8266 chip and I can't control it anymore. I read about backvoltage from the motor. So I think maybe the backvoltage is causing the chip not to function anymore. To make it work again I need to disconnect and reconnect the chip for it to work again.

So my question is: could this be the backvoltage or something else?
And if it's the backvoltage how do I need to connect the diode (1n4001) in this circuit?

I read when a motor stops then the backvoltage happens, but in my case the led on the 8266 starts flashing when it spins. So maybe I hooked something the wrong way. here I have some pictures of the different setups I tried.

Of course I will solder everything nicely, but for now it's just to get a quick impression of the hookup.

Hopefully someone can help me out, thanks in advance!

I read when a motor stops then the backvoltage happens,

That is not true. With a brushed DC motor the back-EMF ("backvoltage") occurs at least twice (often more, depending on the number of commutator segments) per revolution of the motor.  Brushed DC motors are very noisy.

While you can use a diode (connected as you would for a relay) it's not the best solution.  Instead you really need a proper EMI-absorbing circuit.

This consists of three capacitors - all very small values, in the range 1-10nF, which connect all parts of the motor together and bleed off any induced voltages safely.

The first capacitor connects directly across the terminals.  This will safely remove the back-EMF created in the windings as the voltages switch back and forth due to the rotation of the commutator.

The other two capacitors each connect from one terminal to the metal housing of the motor (one to each side of the housing).  This will safely couple the housing to the rest of the circuit and cause it to act as a shield containing the magnetic fields better within the motor.


Sending values from Matlab to arduino using serial communication I want to send numeric value from matlab to arduino but code is not working.

Matlab code is as:

doi = 3 ;
arduino=serial('COM5','BaudRate',9600); % create serial communication object
fopen(arduino); % initiate arduino communication
fprintf(arduino, '%s', char(doi)); % send answer variable content to arduino
fclose(arduino);

Arduino code is as:

  int solenoidPin = 13; //This is the output pin on the Arduino
int doi;

void setup()
{
  Serial.begin(9600);
  //pinMode(13, OUTPUT);
  pinMode(solenoidPin, OUTPUT); //Sets that pin as an output
}
void loop()
{

  if(Serial.available()>0)
  {

    doi = Serial.read();
    //Serial.println(doi);
    //Serial.println("\n");
    //doi = doi - 48;
   if (doi == 1)
   {
    //Serial.println(1);
    digitalWrite(solenoidPin, HIGH); //Switch Solenoid ON
    delay(1000); //Wait .15 Second
     digitalWrite(solenoidPin, LOW);
    }
  else if (doi == 2)
    {
     //Serial.println(2);
    digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
    delay(2000); //Wait .165 Second
    digitalWrite(solenoidPin, LOW);
    }
  else
    {
      //Serial.println(3);
      digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
      delay(3000); //Wait .180 Second
      digitalWrite(solenoidPin, LOW);
    }

  }
}

I used str2num(doi) also instead of fprintf(arduino, '%s', char(doi)) but no output.

Please give suggestion to correct this.

Thanks.

You send a string of ASCII characters representing a number in human readable format.

You then read one of those characters that represents a single digit and then try and use it as if it were a number.

Instead you need to read the whole string of numbers (which means having some way of knowing where the end of the numbers are in the stream of characters that arrive) and then interpret it back into a number again.


Mysterious behavior when using objects I am writing a project that involves using complementary filters to combine gyroscope and accelerator readings in 3 directions. The relevant code is below.

class CompFilter {
 public:
   long prevTime;
   float alpha;
   int angle;

   CompFilter(float Alph);
   int combine (float gyroRate, float accelAngle);
};

CompFilter::CompFilter(float Alph) {
 alpha = Alph;
 prevTime = 0;
 angle = 0;
}

int CompFilter::combine(float gyroRate, float accelAngle){
  Serial.println("Here THREE");

 long timeStep = millis() - prevTime;
 if (timeStep == 0) { timeStep = 1;}

 angle = alpha * (angle + gyroRate * timeStep);

 angle += (1.0 - alpha) * accelAngle;

 prevTime = millis();

 return angle;
}

//Global Objects
CompFilter *senPitch; CompFilter *senRoll;  //Declare Complementary Filters

//Adjustable Parameters
float alpha = .5;   //Constant affecting Gyro's vs. Accel's influence on sensor reading

void setup(void)
{
  //Open Data Channel
  Serial.begin(115200);
  Serial.println(F("IMU Complementary Filter Tester")); Serial.println("");

 //Initialise TMU sensors
 sensorInit(accel, mag, gyro);
 senPitch = new CompFilter(alpha); senPitch = new CompFilter(alpha);
  Serial.println("HERE ONE");
}

void loop(void)
{
 //Variables for reading sensors
 sensors_event_t accel_event, mag_event, gyro_event;
 sensors_vec_t   orientation;

 // Retrieve Sensor Readings
 accel.getEvent(&accel_event);
 gyro.getEvent(&gyro_event);
 mag.getEvent(&mag_event);

 Serial.println("HERE TWO");

 int anglePitch = senPitch->combine(gyro_event.gyro.y, orientation.pitch);
 int angleRoll = senRoll->combine(gyro_event.gyro.x, orientation.roll);

}

I had to keep track of a couple of pieces of information for each direction, so rather than trying to use parallel arrays, I created a CompFilter class. I think I am using the correct syntax in the class and constructing the object, but I am getting very unusual outputs from Serial.print().

RE ONE
RE TWO
Here THREE
Here THREE
entary Filter Tester

Depending on how I fiddle with the code, I can get setup() repeating over and over or loop() running once before silently failing.

I suspect that I have misdirected a pointer somewhere, but I am not sure. I would appreciate any help.

Dave X is absolutely right.

I never assigned the senRoll pointer to an object. Then when I tried to dereference it, it went to some random address. I guess there are very few memory protections, so rather than causing a seg fault it just caused erratic behavior.

Thanks for the help.


How to make 1 second delay more accurate? I have written two (1 second) delay programs.

The first program as follows:

void setup()
{
Serial.begin(9600);
TCCR1A = 0;
TCCR1B |= (1<<CS12);
TCCR1B &= ~(1<<CS11);
TCCR1B &= ~(1<<CS10);
TCNT1 = 3036;
TIMSK1 |= (1<<TOIE1);
}

ISR(TIMER1_OVF_vect)
{
  Serial.println(millis());
  TCNT1 = 3036;
}
void loop()
{
}

Whose output is as follows:

999  // 1 sec
1999 // 2 sec
3000
3999
5000
6000
7001
8000
9000
10001
.
.
.
58012
59013
60013
61012
62013 //60 sec

It has an error of around 13 ms at 1 minute and at 1 hour it will be 780 ms and in one day it will be around 19 seconds.

The second program is as follows:

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

void loop() {
  Serial.println(millis());
  delay(1000);
}

Whose output is near about as same as the first one's.

Is there any way to decrease the error and make it more precise? So that I can use it in my Arduino based stopwatch?

Majenko is perfectly right: you cannot expect much accuracy from an
Arduino clocked by a ceramic resonator. Typical drift is of the order of
1,000 ppm, and is affected by temperature and aging. You can,
however, get a delay which is pretty close to the CPU's idea of one
second. In other words, you can get something that is really close to a
perfect period of 16,000,000 CPU cycles. If that is what you want,
your best bet is to use a timer.

In your overflow ISR, you wrote:

  Serial.println(millis());

There are two issues here. The first is the use of Serial.println()
within an ISR. This should normally avoided: since Serial relies on
interrupts, using it with interrupts disabled can lock your program if
you ever fill the output buffer. In this particular instance, it happens
to be safe, because at this rate you are never going to fill the output
buffer anyway. However, while it can be OK to do that in a small test
program like yours, I would advise you against doing it in production
code.

The other issue is the use of millis(). This function does not provide
true millisecond resolution: it is a counter that is updated every
1024 µs. Every now a then it is updated by 2 ms at once in
order to compensate for the drift. Thus, you should think of millis()
as being good to within ±2 ms. If you need anything better, use
micros().

  TCNT1 = 3036;

This should be avoided. Dispatching an interrupt takes time, and this
time depends on whether there is already an interrupt handler (or other
critical section) running. If the timer happens to increment after the
interrupt fires but before you have time to execute the line above, then
you miss a timer tic. It has been suggested to you to move this line
before the Serial.println(). That would certainly reduce the risk, but
it will not completely prevent it.

The right thing to do is to never reset a timer if you want it to have
time continuity. Instead, set it to CTC mode (clear timer on compare
match) and let it reset itself when it reaches a value of your choosing.
In this case, you would have it repeatedly count from 0 to 62,499
instead of from 3,036 to 65,535.

Here is a modified version of your program illustrating the points
above:

void setup()
{
    Serial.begin(9600);
    TCCR1A = 0;            // undo the Arduino's timer configuration
    TCCR1B = 0;            // ditto
    TCNT1  = 0;            // reset timer
    OCR1A  = 62500 - 1;    // period = 62500 clock tics
    TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
           | _BV(CS12);    // clock at F_CPU/256
    TIMSK1 = _BV(OCIE1A);  // interrupt on output compare A
}

ISR(TIMER1_COMPA_vect)
{
    // OK in test code, don't do this in production code.
    Serial.println(micros());
}

void loop(){}

The output is as follows;

1000048
2000048
3000048
...
58000048
59000048
60000048  // 60 seconds


1.54 e-ink without driver i wan’t to know if is possible to use  this raw e-ink display  with arduino. if it’s possible to directly connect cables from this ribbon cable to arduino without any driver pcb and control it with 3 or 4 wire SPI.
the pinout of the display is on the 6th page

Kind of yes and kind of no.

It requires external circuitry, but that circuitry isn't a "driver board" in the traditional sense.

An e-Ink display requires high voltages to charge the electrostatic cells. Traditionally that would be provided using an external "driver" circuit - a boost voltage converter.

However this display has that boost converter built in - though it doesn't have all the components, because they just won't fit.

You need to provide the diodes, switching MOSFET, and inductor, etc as shown on page 18 of the datasheet.  Nothing less will do.


Using Arduino To Control Boot Sequence of PC I want to know if it is possible to use an arduino to tell a pc which os to boot to. I know It is possible to turn on the pc by wiring it to the motherboard pins with the power switch, and I know the arduino I have (http://www.amazon.com/SainSmart-ATmega328P-Development-Compatible-Arduino/dp/B00E5WJSHK/ref=sr_1_1?ie=UTF8&qid=1436368217&sr=8-1&keywords=sainsmart+uno+r3) can act as a mouse or keyboard. Can that be done before the pc has booted however?

So it might depend on how you implement it. With an Arduino Uno, your options for creating an HID device are limited to either reprogramming the 16u2 (which will require an ISP) or using a software USB implementation (like V-USB). If you go with the first method I'm pretty sure that will work as it will be a native USB connection. As for the second method, I'm not sure how well V-USB responds to having the USB host turning on while it is running. The best thing to do is just try it and see how well it works.

The bigger challenge you will run into is being able to select your PC operating system. Because this will be a one way connection, there is no way of knowing what state the computer is in and whether or not it is time to press a key yet or not. This means you will have to be timing things fairly accurately, which can be tricky unless you are careful. The internal oscillator is not very accurate (but probably still accurate enough) and interrupts used for communicating with USB can block the main loop. That is not to mention any variations the computer might have in its boot process.

A good alternative method would be to set up a bootloader on your PC that can be controlled via a serial port. GRUB2 is a popular one that does support a serial console. All you would need to do is add a level adjuster to adapt the Arduino UART to RS232, then set up the code to wait for the GRUB prompt and then send the command necessary to select which OS you wish to use.


Arduino Pro Mini is burned by 12v. Can I save it? I have this Arduino Pro Mini clone (ATmega328) 5v.
I gave it exactly 12 volts through the RAW power input, but it instantly got hot and started fuming. Fumes were coming out of the area close to the black S4 thingy.
I don't know why, because I thought it can accept up to 12v through that input.
Now when I give it 5v only the middle led is lighting up and it's not connecting to the USB-UART interface anymore.
Is there any chance to save it?

1. Your microcontroller is probably/maybe fine; your tiny little voltage regulator is dead; here's why:
Sergio, yes, you can probably/perhaps save it: your Arduino (the microcontroller--ie: processor at least) is likely just fine, assuming the linear regulator smoked and failed open, meaning it did NOT pass through the raw input voltage to your ATmega328 mcu. It's the linear voltage regulator that is fried! That's this circled component below:

So, desolder that part and throw it away and you can continue using the Arduino just fine. Just power it with a regulated 5V directly to VCC is all and you'll be fine. I've done exactly this on some parts I exploded or smoked the regulator on (see below), and they continued working just fine.
IMPORTANT: if this is a safety-critical part, or a product, throw away the whole Arduino just in case.
Details on the fixes:

Desolder the voltage regular (circled in the image above, and shown desoldered on my Pro Mini in the photo below) and throw the desoldered voltage regulator away.

Power the board now through Vcc with anything between 3.3V and 5V (recommended: a regulated 5V into Vcc, such as the 5V line coming straight out of your USB hub).

Reflash the bootloader with a USBasp programmer (shown in 2nd of the two photos below).

Upload a new blink sketch via the external USB serial UART to blink the built-in LED13. This works fine on my Pro Mini below shown with exploded and desoldered regulator:
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);                       // wait for a half-second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(500);                       // wait for a half-second
}

Unplug the USBasp programmer when done, and continue development with just the external serial UART plugged in.

Here's some photos of my Arduino Pro Mini with exploded voltage regulator that I desoldered. I found it today. The Arduino still works fine! I desoldered the regulator around the year 2014 or so, but just re-flashed the bootloader, uploaded the code, tested it, and took these photos today:
Image 1: Arduino Pro Mini used as a data-logging altimeter in ~2014; photo from today. The voltage regulator exploded (read below), so I desoldered it. Both the power LED (top center of board), and LED13 (bottom-left of board) are ON. The power LED comes on automatically so long as you are powering the board through Vcc and GND from your USB port through your USB UART adapter, and the LED13 is blinking ON here due to the blink sketch above AND by powering the board with Vcc and GND from the USB serial UART to the Pro Mini. Note that the LED13 would NOT light up properly with just the USBasp plugged in, even when it was properly powered and programmed by the USBasp. I think it's because the USBasp was interfering with that pin. Plugging in the external serial UART to the Pro Mini's Vcc and GND fixed that, allowing LED13 to function properly as well while the Pro Mini ran the blink sketch above.

Image 2: External USB serial UART (in the USB hub top port), USBasp programmer wired to program the bootloader (in the USB hub under the USB UART), Pro Mini (bottom left) with power LED ON and LED13 (bottom-left of board) OFF.

On the surface, you didn't do anything wrong! You plugged 12V into the correct pin (RAW, which is the battery-in or voltage in line), and that is within the voltage limits of this part. BUT, what you neglected to consider is the power dissipation capability of this footprint or size of a part. The power dissipation capability is soooo low that realistically, 12V is too much, and will destroy the part.
6 years ago or so I made a couple little data-logging altimeters with the Arduino Pro Mini, connected 12.6V (a fully-charged 3S LiPo battery) to the RAW pin, and 15 seconds later: pop! They exploded! Literally, that little voltage regulator exploded into bits with 12.6V in. After that, I never put more than 8.4V in (a fully-charged 2S Lipo battery), and all was well. Since I was powering it from my main RC plane's 3S LiPo motor battery, this was accomplished by just tapping off of 2 of the 3 cells in the battery by plugging into the correct points on the battery's balance lead. So, I was able to use the same battery but just use 2 of its 3 cells instead of all 3 of them.
These regulators are just so tiny that they can't take much heat is all, and since they are linear regulators, all excess voltage is burned off as heat. Here's a couple example power dissipation calculations to make the point:
Imagine you are drawing 100mA total (0.1A) from this regulator. With 12V plugged in, you have to burn off 12V - 5V = 7V in that regulator chip.
Power_dissipated = Current*Voltage = I*V = 0.1A * 7V = 700mW

700mW is HUGE! Pop! Explosion! Dead voltage regulator chip.
But, if you feed it just 8V this same chip would have to burn off only 8V - 5V = 3V of excess voltage:
Power_dissipated = Current*Voltage = I*V = 0.1A * 3V = 300mW

That's 300mW/700mW = 43% as much power, or 57% less power. These numbers are just for example purposes, but you get the point.
Solution? 1) switch to Arduino Nanos, and/or 2) use a much lower input voltage (ex: 8~9V instead of 12V!). Nanos have MUCH bigger and beefier voltage regulators, and Nanos cost like $1 more when buying the Chinese clones.
2. How to calculate 1) how much power your regulator can dissipate without burning up, and 2) how much current you can therefore draw for different raw input voltages to the voltage regulator:
(Also: I wrote an article on my website covering more of these power, current, and voltage specs--see link here and at bottom.)
By the way, looking at the Pro Mini schematic here, I see that the original board used a MIC5205 linear regulator. The Chinese clone you have certainly uses a different regulator, but let's look up the MIC5205 datasheet for benchmarking purposes. A google search for "mic5205 datasheet" leads me here: https://ww1.microchip.com/downloads/en/DeviceDoc/20005785A.pdf. The device is rated up to 150mA current and up to +16V input voltage, but you must consider power!
The equation for that is hidden on pg 5 here:

Power_dissiplation_max =  P_D_max = (T_J_max – T_A)/theta_JA

theta_JA = thermal resistance from Junction to Ambient = 220 degC/W

T_A = ambient temperature = let's say, 40 deg C (104 deg F)

T_J_max = max junction (internal chip) temperature = +125 degC

So, we crunch the numbers:
P_D_max = (125C - 40C)/220 C/W = 85C / 220 C/W = 0.386W = 386mW max
power.

Final result: this tiny, linear voltage regulator, assuming absolute max junction temperature of +125 C (257 F) [HOT HOT HOT!--not good] and ambient air temperature of 40C (104 F) can dissipate 386mW max power before you risk making it go "pop"!
So, assuming you power it with 12V, how much current can you draw?
Voltage drop across the regulator = V_D = Vin - Vout = 12V - 5V = 7V

Power dissipation in the regulator = P_D = current * voltage drop = I*V_D

Solve for I:
I = P_D/V_D = 0.386W/7V = 0.055A = 55mA current!

With 12Vin and 5Vout, any more than 55mA current draw goes "pop" or smokes the chip!
With 8Vin, however, you could draw:
V_D = 8V - 5V = 3V
I = P_D/V_D = 0.386W/3V = 0.129A = 129mA current

With 8Vin and 5Vout, any more than 129mA current draw goes "pop" or smokes the chip!
So, use a lower input voltage and you can draw much more current! How low can you go? Don't go lower than 5V + dropout voltage. The datasheet on p3 for this regulator shows a max dropout voltage of ~350mV, so stay > 5.35V input to get a regulated 5V output.

That's all for this MIC5205 chip, though. Note that other voltage regulators may have dropout voltages as high as 2~3V, so you'd have to have an input voltage of at least 7V or so to ensure a regulated 5V output. I can't see the numbers well enough on your chip to google for its actual Chinese or whatever datasheet to do the calculations for your chip, but you can use my example calculations above to redo these calculations for any datasheet or part.
Other reading:

Google search for "sot 23-5 power dissipation"

Microchip Application Note AN792: A Method to Determine How Much Power a SOT23 Can
Dissipate in an Application

I also wrote an article on my personal website on 6 Jan. 2014 called "Arduino Power, Current, and Voltage Limitations", here, for more info. on these limitations.


Arduino non-blocking software PWM LED fader not working I am trying to write a simple software PWM to fade some LEDs because I don't have enough PWM I/O Ports.

The code evaluates how long you want the LED to fade, and breaks it down into a number of steps. During each step, it will evaluate the period the LED should be on.

I have the following code:

class Led{
  public:
    Led(int pin);
    void setup();
    // void updateFadeDirection();
    void updateBrightness();

  private:
    int _pin;
    unsigned long _currentTime;
    unsigned long _startTime; // Very beginning of fade period
    unsigned long _fadePeriod; // How long to fade on and off
    int _fadeStep; // current fade step i.e. 1/255
    int _fadeSteps; // How many steps to take until full brightness
    int _fadeDirection; // low to high or high to low?
    float _T_on; // Amount of time to turn LED on
    float _T_fadeStep; // Amount of time per step increment of brightness
    unsigned long _stepTime; // Start of current step period

    bool _evaluated;
};

Led::Led(int pin){
  _pin = pin;
}

void Led::setup(){
  pinMode(_pin, OUTPUT);
  _startTime = micros();
  _fadePeriod = 2*1000000; //microseconds(us)
  _fadeStep = 50; // start at 0 brightness here
  _fadeSteps = 100;
  _fadeDirection = 1;

  _T_fadeStep = _fadePeriod/_fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness
  _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on

  _stepTime = micros();
  delayMicroseconds(200);
}

void Led::updateBrightness(){
  _currentTime = micros();

  if(_currentTime - _startTime < _fadePeriod){
    if (_currentTime - _stepTime > _T_on){
      digitalWrite(_pin, LOW);
    } else {
      digitalWrite(_pin, HIGH);
    }

    if(_currentTime - _stepTime >= _T_fadeStep){
      // _fadeStep++;
      _stepTime = _currentTime;
      _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep;
    }
  }
  else{
    digitalWrite(_pin, HIGH);
  }
}

Led LED0(0);

void setup() {
  LED0.setup();
}

void loop() {
  LED0.updateBrightness();
}

The current behaviour when powered on is the single LED will be turned off, then will turn on after 2 seconds.

In particular, it never seems to enter the else part

  if (_currentTime - _stepTime > _T_on){
    digitalWrite(_pin, LOW);
  } else {
    digitalWrite(_pin, HIGH);
  }

The problem is that the LED will never hit HIGH until the outer else is triggered.

I believe it has to do with _T_on being an int and the timestamps being unsigned long and me not casting it.

The expected behaviour is 2 seconds of dimmed (50%) light, and then a full 100% when it hits the outer else.

As @ott-- has mentioned, because of the int datatype, _fadeStep/_fadeSteps will always evaluate to 0.

Here's the updated code along with some timing tweaks:

float fadeSteps = 150; // How many steps to take until full brightness

class Led{
  public:
    Led(int pin, float fadeStep=0);
    void setup();
    // void updateFadeDirection();
    void updateBrightness();

  private:
    int _pin;
    unsigned long _currentTime;
    unsigned long _startTime; // Very beginning of fade period
    unsigned long _fadePeriod; // How long to fade on and off
    float _fadeStep; // current fade step i.e. 1/255
    int _fadeDirection; // low to high or high to low?
    unsigned long _T_on; // Amount of time to turn LED on
    unsigned long _T_fadeStep; // Amount of time per step increment of brightness
    unsigned long _stepTime; // Start of current step period

    bool _evaluated;
};

Led::Led(int pin, float fadeStep){
  _pin = pin;
  _fadeStep = fadeStep;
}

void Led::setup(){
  pinMode(_pin, OUTPUT);
  _startTime = micros();
  _fadePeriod = 2000000; //microseconds(us)
  _fadeDirection = 1;

  _T_fadeStep = _fadePeriod/2/fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness
  _T_on = (_fadeStep/fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on

  _stepTime = micros();
}

void Led::updateBrightness(){
  _currentTime = micros();
  if (_currentTime - _stepTime > _T_on){
    digitalWrite(_pin, LOW);
  } else {
    digitalWrite(_pin, HIGH);
  }

  if(_currentTime - _stepTime >= _T_fadeStep){
    _fadeStep += _fadeDirection;
    _stepTime = _currentTime;
    _T_on = (_fadeStep/fadeSteps) * _T_fadeStep;
  }

  if(_fadeStep >= fadeSteps-1) {
    _fadeDirection = -1;
  } else if(_fadeStep <= 1) {
    _fadeDirection = 1;
  }
}

Led LED0(0);
Led LED1(1,fadeSteps/5);
Led LED2(2,2*fadeSteps/5);
Led LED3(3,3*fadeSteps/5);
Led LED4(4,4*fadeSteps/5);

void setup() {
  LED0.setup();
  LED1.setup();
  LED2.setup();
  LED3.setup();
  LED4.setup();
}

void loop() {
  LED0.updateBrightness();
  LED1.updateBrightness();
  LED2.updateBrightness();
  LED3.updateBrightness();
  LED4.updateBrightness();
}

Some refactoring is needed to be more modular, but will fade (using software PWM) LEDs asynchronously on every digital OUT port on an attiny85. Can also set the starting brightness so that you can make an LED fading chaser.


Getting the "Device has problem: 0x0a: CM_PROB_FAILED_START." error code 10 while installing device driver for Arduino Uno After uninstalling and reinstalling Arduino IDE, my Arduino Uno is not recognized by my PC. When I connect it to my PC all lights are glowing in my board but my PC is not showing anything connected to USB.

When I tried to install drivers manually I'm getting the error device cannot start code 10. I have used the default drivers for Arduino, which I downloaded with the IDE. I tried installing them manually. I don't have any idea about chipset interface whether it is CH or FTDI. I have looked at all the possible solutions but my problem wasn't solved.

Error code 10 mean Bad Environment.  I would guess that you are using the wrong driver, probably 64 bit on a 32 bit OS, etc.

This does not look like a Arduino fault, it looks like a windows Driver fault, so unlplug the board, reboot the PC logon as admin and download the latest drivers for you device and see if that fixes it.  You might be able to get better help on a Windows admin forum I think.


Arduino read from Server periodically I have an arduino attached with a RGB-Shield. I want to query my server for the RGB values periodically. I basically got it working using the Ethernet Shield but it takes too long to get the value (~500ms}. I really want to read the values from my server really really fast in an endless loop.

Can you give me any hints on how I can improve my code?

#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,1,151);
IPAddress ip(192, 168, 1, 177);
EthernetClient client;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Ethernet.begin(mac, ip);
  }

  delay(1000);

  if (client.connect(server, 80)) {
    client.println("GET /rgb.php HTTP/1.1");
    client.println("Host: 192.168.1.151");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();

    ... read from Server

  }

  if (!client.connected()) {
    client.stop();
    if (client.connect(server, 80)) {
      client.println("GET /rgb.php HTTP/1.1");
      client.println("Host: 192.168.1.151");
      client.println("Connection: close");
      client.println();
    }
  }
}

You could try with a direct TCP connection (in this way you skip the HTTP layer) but you need to prepare also a small TCP server (in any language comfortable to you) that accepts the client connection, sends the data, waits the ACK and close the connection.