LEDs: difference between common anode and common cathode? What is the difference in using a common anode and common cathode of the 7 Segment in interfacing with the Arduino? How can you change the code if we need to add another 7 Segment display?

How can you change the code to have a counter in backwards (from 0 to 9)?

const int ANODE = 2;

const int LED1 = 3;
const int LED2 = 4;   // pin for led 2
const int LED3 = 5;   // pin for led 3
const int LED4 = 6;   // pin for led 4

// now bottom row

const int LED5 = 7;
const int LED6 = 8;
const int LED7 = 9;
const int LED8 = 10;

int DELAY = 0;

void setup() {
  pinMode(ANODE, OUTPUT);  // common anode is obviously an output

  pinMode(LED1, OUTPUT);   // led are output for low will be on
  pinMode(LED2, OUTPUT);   // led 2 is output
  pinMode(LED3, OUTPUT);   // led 3 is output
  pinMode(LED4, OUTPUT);   // led 4 is output
  pinMode(LED5, OUTPUT);   // led 5 is output
  pinMode(LED6, OUTPUT);   // led 6 is output
  pinMode(LED7, OUTPUT);   // led 7 is output
  pinMode(LED8, OUTPUT);   // led 8 is output
}

void loop(){

  if (DELAY == 300){
    delay(100000);
  }

  digitalWrite(ANODE, HIGH);

  digitalWrite(LED1, HIGH);
  digitalWrite(LED2, HIGH);
  digitalWrite(LED3, HIGH);
  digitalWrite(LED4, HIGH);
  digitalWrite(LED5, HIGH);
  digitalWrite(LED6, HIGH);
  digitalWrite(LED7, HIGH);
  digitalWrite(LED8, HIGH);

delay(1000);

  digitalWrite(LED1, LOW);
  delay(500);
  digitalWrite(LED1, HIGH);
  digitalWrite(LED2, LOW);
  delay(500);
  digitalWrite(LED2, HIGH);
  digitalWrite(LED3, LOW);
  delay(500);
  digitalWrite(LED3, HIGH);
  digitalWrite(LED4, LOW);
  delay(500);
  digitalWrite(LED4, HIGH);
  digitalWrite(LED5, LOW);
  delay(500);
  digitalWrite(LED5, HIGH);
  digitalWrite(LED6, LOW);
  delay(500);
  digitalWrite(LED6, HIGH);
  digitalWrite(LED7, LOW);
  delay(500);
  digitalWrite(LED7, HIGH);
  digitalWrite(LED8, LOW);
  delay(500);
  digitalWrite(LED8, HIGH);

  delay(100);

  DELAY = DELAY + 150;
}

A 7-segment is a packaged set of 8 LEDs (7 number-segments & 1 decimal point). Common anode means that the anode (positive) side of all of the LEDs are electrically connected at one pin, and each LED cathode has its own pin. So turning on any particular segment will involve running a current from this common anode (positive) pin to the particular cathode (negative) pin for the desired segment.

Common cathode means that the cathodes of all of the LEDs are common and connected to a single pin. The anode for each LED has its own pin. So driving one of these means running a current from the particular anode (positive) pin for the desired segment to the common cathode pin.

The way that you are diving the 7-segment involves using a separate pin to drive each segment, so you use 8 pins of the Arduino to drive the display. You will run out of digital pins if you try to add a second 7-segment. There are a couple of ways to address this. One is to add a 7-segment driver, like the CD4511. This limits you to being able to display only numerical digits, but uses only 4 pins of the Arduino per 7-segment.

Another, more versatile way is to add a serial-in to parallel out chip (74HC595, for example) to drive the 7-segment. This requires only two pins from the Arduino (data & clock), and they can be chained to have multiple 7-segments driven from those same 2 pins.

You can easily test this in 123D Circuits, check this out:
https://123d.circuits.io/circuits/1019227-7-segment-circuit

Click start simulation and then click on the buttons to light up the corresponding segment.


Problem Uploading to the Arduino Nano board ]2I am using an Arduino Nano board. It has an ATmega 328P processor. For running the codes I use Arduino 1.8.6 Software. The issue is that when I am uploading my sketch to the board it shows me the following errors:

 Using Port                    : COM7
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x9b
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x9b

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I have turned on the show verbose output option turned on.

Also, sometimes the following errors pop up:

collect2.exe: error: ld returned 255 exit status

Using library SoftwareSerial at version 1.0 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.14.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\SoftwareSerial
exit status 1
Error compiling for board Arduino Nano.

I have referred the following links to solve my issue:

collect2.exe: error: ld returned 5 exit status
Why I can't upload my programs to the Arduino board?

I am making an application wherein I have to control two DC motors via Bluetooth module HC-05

In one of the troubleshooting questions, the solutions contained the possibility of the bootloader not being installed where the problem can be verified by pressing the reset button and checking the bootloader LED to blink. Can someone help me with this?

Also, there are two processors shown for ATmega328P:

The ATmega328P
The ATmega328P (old bootloader)

I tried using then both options for uploading the sketch but still, the errors pop up.

I have also downloaded and installed the latest FTDI drivers from their site.

A common solution is to actually switch the board type to the Arduino Uno. It is a known problem but I have yet to see any other viable fix.


How to convert this sketch to keep only one if-else statement? int ldrPin = A0;
int rainPin = A1;
int smokePin = A2;
int greenLED = 6;
int redLED = 7;

// you can adjust the threshold value
int thresholdValue = 500;
int LightSensorThreshold = 500;
int RainSensorThreshold = 500;

void setup() {
  pinMode(ldrPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);

  pinMode(rainPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);

  pinMode(smokePin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  int lightSensorValue = analogRead(ldrPin);
  Serial.print(lightSensorValue);

  if(lightSensorValue < LightSensorThreshold){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

  int rainSensorValue = analogRead(rainPin);
  Serial.print(rainSensorValue);

  if(rainSensorValue < RainSensorThreshold){
    Serial.println(" - It's wet");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - It's dry");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

  int smokeSensorValue = analogRead(smokePin);
  Serial.print(smokeSensorValue);

  if (smokeSensorValue < thresholdValue) {
    Serial.println(" - Smoke");
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, HIGH);
  }
  else
  {
    Serial.println(" - No Smoke");
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, LOW);
  }
  delay(100);

}

First find the duplicated code.

E.g. the fragment

  int lightSensorValue = analogRead(ldrPin);
  Serial.print(lightSensorValue);

  if(lightSensorValue < LightSensorThreshold){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

is repeated three times.

Then find within the duplicate code fragments, the differences, which are:

the pin number
the value to check against.
the two texts

Then make a new function containing one duplicated code fragment, and replace the differences, by variables which you pass in the function as arguments:

void checkSensor(int pin, int sensorLimitValue, char* okText, char* warningText)
{
  int sensorValue = analogRead(pin);
  Serial.print(sensorValue);

  if(sensorValue < sensorLimitValue) {
    Serial.println(okText);
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  else {
    Serial.println(warningText);
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  delay(500);
}

And call respectively:

checkSensor(ldrPin       , LightSensorThreshold, " - light"   , " - dark");
checkSensor(rainSensorPin, RainSensorThreshold , " - it's wet", " - it's dry");
checkSensor(smokePin     , thresholdValue      , " - Smoke"   , " - No Smoke");

I switched the green/red values, because I assume when the value is lower than the limit, the green LED should be on, and otherwise the red LED.

Btw, why not use smokeSensorThreshold instead of thresholdValue to keep it consistent with the other duplicated code fragments?

Sure:

Change these int's to byte, none have values more than 255:

int ldrPin = A0;
int rainPin = A1;
int smokePin = A2;
int greenLED = 6;
int redLED = 7;

Take these out of setup(), analog input pins don't need this:

pinMode(ldrPin, INPUT);
pinMode(rainPin, INPUT);
pinMode(smokePin, INPUT);

Take out the duplicates of these lines, pinMode() and turning them off (if LOW is off) only needs to be called once for each

pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);

Get rid of two the Serial.begin(9600) lines, calling it once is enough.

Within loop(), get rid of the int's. Those variables were already globally declared, you don't need to re-declare them as type int.


How do I figure out if my board is approaching end of life? I have a uno that I have been using for 3 years now. I will be using it again in a rather critical project in which failure on the part of the board could be rather expensive and dangerous. So, I would like to be sure that the board is not approaching end of life or going to fail anytime soon. Is there any reliable way to figure out how long the board will function without failing or reduction in performance?

Unfortunately, there isn't much way to really determine "wear" in the context of solid-state electronics.

Probably the things that are most likely to fail are the electrolytic capacitors and the connectors.

First, if you're using an ATmega CPU for something that could possibly injure someone CONTACT ATMEL AND TALK ABOUT SAFETY PRECAUTIONS. The ATmega CPU used in most of the arduino models is not rated for use in such situations.

In EVERY datasheet:

  Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.

Now, realistically, this is probably mostly lawyer repellent, but you should still take appropriate precautions.

Really, while there isn't anything on a common arduino board that really wears out except the connectors, why are you trying to save $30 at a potential huge cost? Just buy a new board.

I'd also strongly reccomend you chose a board with a SMT ATmega328P, since that removes the IC socket contacts from the list of concerns. If possible, also remove the pin-headers, and solder wires to the board directly. Try to minimize connectors, since they are frequent points of failure.

Edit : People who down voted my answer, Ohh common don't be too much foolish
  ! for that you need to be an electron and go through the circuit
  itself to check everything is ok or not :)

Plug the board into a USB port on your computer and check that the green LED power indicator on the board illuminates. Standard Arduino boards (Uno, Duemilanove, and Mega) have a green LED power indicator located near the reset switch.

An orange LED near the center of the board (labeled “Pin 13 LED” in the image below) should flash on and off when the board is powered up (boards come from the factory preloaded with software to flash the LED as a simple check that the board is working).

If the power LED does not illuminate when the board is connected to your computer, the board is probably not receiving power.

The flashing LED (connected to digital output pin 13) is being controlled by code running on the board (new boards are preloaded with the Blink example sketch). If the pin 13 LED is flashing, the sketch is running correctly, which means the chip on the board is working. If the green power LED is on but the pin 13 LED is not flashing, it could be that the factory code is not on the chip. If you are not using a standard board, it may not have a built-in LED on pin 13, so check the documentation for details of your board.

Online guides for getting started with Arduino are available at for Windows,  for Mac OS X, and for Linux.


What not to do to an Arduino I may have been working with my Arduino UNO board improperly,
because now it fails to upload sketches (says some programmer is not responding)
and when I press the cute little restart button, the green LED doesn't do its blink anymore. I am aware what that means, but what I really wonder is how should I properly care the board. I probably will have no other chances to buy more arduinos so this information follows to be of a great importance.

As an example I would give, is touching the arduino board with bare hands risky, how much shock-tolerant it is, what if I mistake some pins, are there pins that cannot be mistaken, what will happen if I declare a pin as an output, but use it for input and the contrary, is loading a PWM program onto TFT touch screen shield unhealthy and so forth and briefly - how should I properly care the arduino board.

it is okay to use for simple experiments directly. But while you choose to opt for a complex tasks read the details about all the components and their wiring techniques.
specifically try to check soldering is done correctly or not while connecting the wires to any component or to other wire. wrong soldering may damage your parts and arduino as well.
Be careful while using power supply, more when it comes to use multiple sources.
read carefully before you do anything. Dont be afraid just be careful.

What not to do to an Arduino

Don't pour coffee on it, don't sit on it, don't swim with it and definitely don't sleep with it, to name a few.....

Seriously, the key is to recognize what the arduino is not designed for. It has limited current drive, it is not ruggedised, it is not meant to work in harsh climate, etc.

To out in inaccurately, if it is not in an air conditioned environment, don't use it.


How to get Transmission package Timestamp from ESP8266 I am trying to make an Indoor positioning system using ESP8266 as a beacon, how do I get the transmission package timestamp from router to ESP8266 and vice-versa?

Thank you in advance for any advice

You can use timestamp from NTP client and attach it

Install NTPclient library from Arduino library manager
This library uses WiFiUdp library to connect to the NTP server, so download that too

Then you can just update the time every time your sending/receiving something and log it as and how you see fit!


ATmega 2560 with Arduino bootloader running issue I have designed a board based on an ATmega2560 chip and I burned the bootloader by following this tutorial.

Now I am able to load Blinky and other programs using an FTDI cable. But the issue I am facing right now is the controller runs Blinky fine if I leave the FTDI connected there. If I disconnect the FTDI cable and power-cycle the board it is not running Blinky. If I connect the FTDI, right away it starts blinking.

It looks like something is wrong with my RESET pin connection? Here is what my RESET circuitry looks like:

I also have tried by removing D1 diode but no luck !

The issue was there was some noise on RX Pin of the chip and because of that when it is powered on in bootloader it was stuck at that place. And it was working good with FTDI because RX gets proper connection with my FTDI.

Solution:- Connect 10K pull-down on RX pin resolved this problem.

Or get rid of C6, I have never used that in a design.


Adding an LCD to Uno but not enough pins left I am an absolute beginner and wanted to build a simple home automation system using DTMF module using this guide. My problem is out of 12 pins most of them are getting used in DTMF module(5) and the relay module(4). So how do i add an LCD display to it?

You are using 8 GPIO pins for your existing modules. That leaves 12 left for an LCD (assuming you aren't using the serial port).

An LCD can work from as few as 6 pins (4 data, E and RS) - WR can be tied LOW and RESET can be tied HIGH, and the remaining 4 data pins left floating (or tied low).

That still leaves you 6 pins to do other things. Or 4 if you (advisedly) steer clear of using pins 0/1 for anything.

If some of the pins aren't used at the same time there are ways to reuse them.

Otherwise use a serial shifter or o.o expanders to drive the LCD. 2 to 3 pins max. Even 1 pin is possible if you tolerate lower speed of update.


Strange Output from DS1307 RTC I'm using a DS1307 RTC (https://www.adafruit.com/product/3296) and an Arduino mega microcontroller trying to simply set and read the time of the RTC. However, whenever I try to output anything to the Serial Monitor, I get stuff like this:

The code and the wiring is fairly straightforward which is why I'm confused. I'm just directly attaching the Vcc, GRND, SCL and SDA pins of the clock to the Arduino and using a slightly modified version of the example code as a part of the RTC library Adafruit supplied.

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

RTC_DS1307 rtc;

void setup () {
  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(57600);
  rtc.begin();

  rtc.adjust(DateTime(2017, 11, 17, 20, 33, 0));

}

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

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

    Serial.println();
    delay(1000);
}

So I know I'm doing something wrong but I'm not sure what. Any help would be hugely appreciated.

Change the baud rate to 57600, it specifies at:
    Serial.begin(57600);


Is there any way I can light up a candle with an Arduino? I want to make a candle flame light up triggered by a microcontroller. Is it possible? I only want to light it up. Not turn it down. Moreover, this is for a one-time use so the candle burning down and becoming shorter is not a problem.

A simple solution is too use nichrome wire which when a current is passes through it will heat up. You could wrap some of this wire around the wick on the candle and then power it either straight from your arduino or you could include a capacitor.
This is much safer than some of the other methods which use potentially dangerous high voltages.

I tested the nichrome wire approach and it works! See following video clip. 2 Ohm resistance and 19V for 1 second.  https://1drv.ms/v/s!AvcBubMtAczvifYZwoESAhUodOoqRA

Is it possible?

Not only is it possible, I will also provide all the code you will never need to light it up reliably:

While (!candleislit())
Lightupcandle();

That's all you need too light up a candle.


Optmizing print code when writing to file, and reducing print time First things first, I have found some solutions to this problems but they all involved for printing to serial monitor. I am trying to take the information from the sensors and write them to an sd card. Here is my code so far:

//-----Writes Data to SD Card-----//
if(!Data) {
    u8g.firstPage();
    do {
       drawFileError();
    } while( u8g.nextPage() );
    while (1);  // don't do anything more:
}

dcounter++;
if (dcounter=1){

    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
    Data.print(strutcDate + "  ");
    Data.print(strutcTime + "  ");
    Data.print(strgpsStatus + "  ");
    Data.print(strmodeIndicator + "  ");
    Data.print(strlatitude + "  ");
    Data.print(strlongitude + "  ");
    Data.print(strspeedOverGnd + "  ");
    Data.print(strcourseOverGnd + "  ");
    Data.print(t);
    Data.print("  ");
    Data.print(f);
    Data.print("  ");
    Data.print(h);
    Data.print("  ");
    Data.print(hi);
    Data.print("  ");
    Data.print(press_pKa);
    Data.print("  ");
    Data.println(str);
    Data.close();
} else{
    Data.print(strutcDate + "  ");
    Data.print(strutcTime + "  ");
    Data.print(strgpsStatus + "  ");
    Data.print(strmodeIndicator + "  ");
    Data.print(strlatitude + "  ");
    Data.print(strlongitude + "  ");
    Data.print(strspeedOverGnd + "  ");
    Data.print(strcourseOverGnd + "  ");
    Data.print(t);
    Data.print("  ");
    Data.print(f);
    Data.print("  ");
    Data.print(h);
    Data.print("  ");
    Data.print(hi);
    Data.print("  ");
    Data.print(press_pKa);
    Data.print("  ");
    Data.println(str);
    Data.close();
}

two questions: is it possible for me to reduce this chunk of code into something smaller? is there a way to decrease print time?

Edit: Ahh I see, the problem with my code is that the last few values are floats.Any way to shorten those as well, or do i need to do it individually? I do agree about the adding string parts.

First of all, the only difference between the two parts of the "if" statement is that, the first time, it prints the header. Instead of that code, you could do this:

//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.print(strutcDate + "  ");
Data.print(strutcTime + "  ");
Data.print(strgpsStatus + "  ");
Data.print(strmodeIndicator + "  ");
Data.print(strlatitude + "  ");
Data.print(strlongitude + "  ");
Data.print(strspeedOverGnd + "  ");
Data.print(strcourseOverGnd + "  ");
Data.print(t);
Data.print("  ");
Data.print(f);
Data.print("  ");
Data.print(h);
Data.print("  ");
Data.print(hi);
Data.print("  ");
Data.print(press_pKa);
Data.print("  ");
Data.println(str);
Data.close();

Like already mentioned, you can append strings with the + operator. This would be the final code then:

//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
Data.close();

FYI, it doesn't seem like you should close the stream every iteration at the end since you only open it the first time.

Maybe this helps with speed. It will however use more memory, so use with caution.

Data.println(Header);
Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
Data.close();


Saving Arduino output to a text file in append mode I used the code below to save output from an Arduino Uno to a text file.

The problem is whenever I run the code the old data in the text file is deleted.

I don't want the old data to be deleted, what should I change?

import processing.serial.*;
Serial mySerial;
PrintWriter output;
void setup() {
   mySerial = new Serial( this, Serial.list()[0], 9600 );
   output = createWriter( "data.txt" );
}
void draw() {
    if (mySerial.available() > 0 ) {
         String value = mySerial.readString();
         if ( value != null ) {
              output.println( value );
         }
    }
}

void keyPressed() {
    output.flush();  // Writes the remaining data to the file
    output.close();  // Finishes the file
    exit();  // Stops the program
}

There are a couple of ways to append to a text file.

You can either read the entire file in a temporary variable, then append the new data to it and then write to file.

you can implement using printWriter instead like mentioned here:
https://processing.org/discourse/beta/num_1267767630.html

Let me know if it works.

Load configuration data from the SPIFF file, return 0 if OK

SPIFFS open function needs path and mode:
mode = "r", "w", "a", "r+", "w+", "a+" (text file) or "rb", "wb", "ab", "rb+", "wb+", "ab+" (binary)
where r = read, w = write, `a = append

means file is open for update (read and write)

b means the file os open for binary operations

Returns 0 if OK else:
-1 = No SPIFFS file system
-2 = File does not exist
-3 = File too short
-4 = Checksum does not compare


Measuring high frequencies (300kHz) with arduino I'm designing a frequency generator with ICL8038, which would output sine, square and triangle waves, which would reach frequency such as 300kHz.

I've already designed a circuit around the ICL8038, but I'm unsure how to measure the frequency, to show on LCD display.

I'm leaving down a schematics I've drawn.
A.Duty is going to the analog input of arduino, which will show the duty cycle between 2% and 98%. This will be going to a voltage divider to make a proportional input for the arduino analog input.

The "frequency pin" would be connected directly from the BNC connector from the casing, which means, that the input can be triangular, sine or square.

Just to mension, in case it makes any kind of difference, I'm planning to use just Atmega328 with 16MHz quartz and 2 capacitors, not exactly as Arduino UNO or NANO.
But the Atmega will have a arduino bootloader on it.

By the time asking about ICL8038, I've got also few questions about the IC:

You connect the FM Bias(pin 7) and SWEEP (pin 8) together to create sweep on the output of any kind of signal, whichever it is? This is fixed time constant or should I add some kinda coapacitor there?
What exactly does Tcap (pin 10) does? I've read through the datasheet but couldn't understand it's meaning.
How would I get proper voltage range every time, when I would change the input voltage of the ICL8038? (it has wide range of output signal, proportionall to the input; it goes from 36V to input, 28V max output)
For power supply would be proper LM317 as adjustable power supply (since it has low power consumption) and just use a potentiometer to adjust input of the ICL8038 and monitor the OUTPUT levels?
PIn 13 and PIn 14 are NC (not connected). Can I just connect them together and connect them to GND?

As if anybody knows for any "better" IC as this one is, please let me know.
I'm already going to have to buy it from China (this gives me doubts about the capabilities), I'd rather just order one from Europe or US.

To sample a 300kHz signal you need to sample at at least 600,000 samples per second (see Nyquist-Shannon Theorem).

The Arduino can sample at an absolute maximum of 125,000 samples per second.

A normal Arduino will not be able to sample the analog input fast enough to even remotely have a clue what the frequency is - let alone what shape the signal is (for that you would have to be sampling in the millions of samples per second).

You will need a much more powerful board than an Arduino to do it.

The other option is to feed the signal through a comparator (an op-amp with infinite gain) to convert the signal into a square wave. You can then use simple frequency counting to get the frequency (count the pulses within a given time frame - maybe 1 second).

As for the rest of your questions, you would be better off asking those on Electrical Engineering.


How to stole/read data from an output serial port? (Sorry, I'm not a native English speaker)

I have a chip with Serial Input, Serial Output, and a Clock (used by both serials). I want to read the output with an Arduino or ESP-32.

The device I want to read is: https://statics.cirrus.com/pubs/proDatasheet/CS5460A_F5.pdf

How can I do this? I don't have too much expertise in serial communication.

Do I need anything else?

I would appreciate any help.

This device seems to communicate via SPI. Google for "serial peripheral interface" and learn how it works. You will then be able to know what to do with the information in chapter 4 of the datasheet.


Is it possible to detect host usb device connected to arduino? and how? let's say that I've connected an arduino uno to a pc, or to a mobile phone via usb .. how can I detect the device type and the running operation system if it's possible?

You can't, using stock firmware. And with custom firmware it's still very difficult.

The USB communication chip on the Uno has no out-of-band means of telling the main MCU that it is connected to a host. You might be able to rewrite the communication firmware on the R3 to tell the main MCU over serial that it is connected, but the firmware on the main MCU will need to be written in such a manner that it will anticipate this.

If you want this to work then you should consider using one that has a native USB connection, such as the Leonardo. You will then be able to query the USB facility directly to know whether or not you are connected to a host.

I did not try to go further, but I know there is some information passing on Serial1 when you plug a device.

void setup() {
  Serial.begin(115200);
  Serial1.begin(250000);
}

void loop() {
  if(!Serial1.available()) {
    Serial.println("OFF");
    delay(500);
  }
  else {
    Serial.println("ON");
    Serial1.end();
    delay(500);
    Serial1.begin(250000);
  }
}

Maybe you can try to see if depending on the device, information is persistent, in which case you should be able to detect a specific device / kinf of device ?
I'll look at it tomorrow, maybe will have more code to show...


send more than one integer on serial between Mega and nodeMcu i have 2 integers i want to send them from Mega to nodeMcu
i get them to talk to each other
by this one on Mega :-

#include <DHT.h>

#define DHTPIN 2      // Selecting the pin at which we have connected DHT11
#define DHTTYPE DHT11 // Selecting the type of DHT sensors

DHT dht ( DHTPIN, DHTTYPE ) ;

        void setup() {
      // initialize both serial ports:
      Serial.begin(9600);
      Serial1.begin(9600);
      dht.begin ();

    }

    void loop() {
      //==========// DHT part
   humidity = dht.readHumidity ( ) ;  // Declaring h a variable and storing the humidity in it.
   temp = dht.readTemperature ( ) ; // Declaring t a variable and storing the temperature in it.
  // Checking if the output is correct. If these are NaN, then there is something in it.
   if ( isnan ( humidity ) || isnan ( temp ) ) {
     Serial.println ( " Sensor not working " ) ;
   }
   else
    Serial.println(humidity);

//========// Send to wifi
 if (Serial1.available()) {

    itoa(humidity,str1,10);
    Serial1.write(str1,2);
    itoa(temp,str2,10);
    Serial1.write(str1,2);
    }

and this on on nodeMcu :-

#include <SoftwareSerial.h>

SoftwareSerial swSer(14, 12, false, 256);
char str1[10],str2[10];
int i,j;

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

  Serial.println("\nSoftware serial test started");

}

void loop() {
  while (swSer.available() > 0) {

    Serial.println("Humidity is");
    for (i=0; i<3; i++){
    str1[i]=(swSer.read());
    }
    Serial.println (str1);
    Serial.println("Temp is");
    for (j=0; j<3; j++){
    str2[j]=(swSer.read());
    }
    Serial.println (str2);

  }

}

But i  get the  result on nodeMcu not in right order (sometimes humidity printed in place of temperature and verse vise and sometimes i get no.2

can some one help me please to figure what is wrong ?

I'd suggest some kind of character before each int so that the receiver knows which one it is getting.


Using Due (SAM3X8E) native USB port for programming? I would like to make my own version of the Arduino Due.

What I can't find the answer to is;
Can I program a blank SAM3X8E using the native USB port from within the Arduino IDE, or do I first need to program some bootloader or similar?

My board will not have the Mega16U2 which is normally used for programming.

The SAM3X8E comes with a bootloader in ROM.

Memories

256 to 512 Kbytes embedded Flash, 128-bit wide access, memory accelerator, dual bank
32 to 100 Kbytes embedded SRAM with dual banks
16 Kbytes ROM with embedded bootloader routines (UART, USB) and IAP routines
Static Memory Controller (SMC): SRAM, NOR, NAND support. NFC with 4 Kbyte RAM buffer and ECC

Since this bootloader does all that the Arduino IDE asks of it, and has a freely available cross-platform command-line upload tool (bossac) the IDE just uses that. No need to invent the wheel when the wheel does everything you need and even comes with a tin of axel grease.

While technically it is possible to use your own bootloader in conjunction with the existing one (use the existing one to install yours, and then use yours to upload sketches) it requires in-depth knowledge of both the chip and GCC linker ("ld") scripts to set aside a block of memory for your bootloader to reside in and relocate the compiled code around it properly. Too much work when the bootloader that already exists does what you want.

However other chips either don't have a bootloader (like the M0 in the Feather) or don't have one that works as desired (like the DFU bootloader in the ATMega32U4) so a custom bootloader is used on those.

The IDE itself is pretty dumb. It just has a configuration file that says "Execute this command with these parameters to upload the HEX file". It neither knows, nor cares, what the bootloader at the other end of the connection is, nor how it works. As long as there is a command-line executable to do the work it just hands over to it.

Microchips needs some kind of bootloader to be able programmed over USB. Arduino boards cames with default bootloader loaded (from Arduino company at least, net necesarry from Chine, probably without, if you byu just the chip from manufacturer), so on official boards it is all done for you to have aesy life.

Being able to properly communicate over USB is not exactly easy task and there are many different protocols for sending program to bootloader, which is then resposible to put the program at flash memory at proper place and give it controll later.

Also keep in mind, that there are other ways, how to put program in memory and that not all devices using some microcontroler are even meant to be programable by user over it. (For example they may idetyfy themself as keybords, mouses, joysticks and such to computer and be closed to reprogramming by manufactor of such device. Arduino community is only small part of industry, which uses the same chips for totally different tasks).


Error while saving data in text file I created a function that saves the timestamp in a text file, but it saves unreadable. Full of invalid characters, example: Ÿ@Â   O   ƒº!¥ Ÿ@Â   O   ƒº!¥ Ÿ@Â   O   ƒº!¥ Ÿ

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

RTC_Millis rtc;
File txt;
const char * getCurrentTimestamp()
{
    char dateBuffer[40];
    DateTime now = rtc.now();
    sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());
    return dateBuffer;
}

void saveLog()
{
  txt = SD.open("dados.txt", FILE_WRITE);
  txt.print(getCurrentTimestamp());
  txt.close();
}

void setup() {
  pinMode(53, OUTPUT);
  SD.begin(4);
  Serial.begin(9600);
  rtc.begin(DateTime(F(__DATE__), F(__TIME__)));
}

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

My code is very simple, do not understand where I went wrong. if I copy the following code snippet for saveData() function and save the dateBuffer variable, everything works normally.

char dateBuffer[40];
DateTime now = rtc.now();
sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());

how to save the timestamp correctly in the file through the function getCurrentTimestamp() ?

Your function, getCurrentTimestamp() saves the date string in an automatic variable - it is on the function's stack frame which gets freed as soon as that function returns. Either Serial.println() or savelog() is overwriting it.

The proper way to do what you're trying to do is to make the buffer live for the duration of both function calls. One way is to use a global buffer. Another is to declare the buffer in loop() and pass it to both functions.

As far as I know you should use

text.write(getCurrentTime());

That because (if I'm not wrong) you need to send it as ASCII characters so the text editor will be able to read them in the right way.


How can I filter out noise from ADC lines without delay or signal change? I'm working on a project with a joystick and I'm trying to keep everything a simple and low latency as possible. I am reading the pots with the onboard 10bit ADC on the ATmega 32u4 but may be upgrading to either a 16bit ADC or 24 bit ADC. How can I filter noise out of the signals?

The Atmel ATmega328 datasheet, section 24.6.1, recommends that you drive the analog input pin with an output impedance of 10 KOhm or less. Also, it recommends that you remove high-frequency components with a low-pass filter. (That low-pass is sometimes called an antialiasing filter).

The simplest possible low-pass filter is a resistor and a capacitor.

  +5V                        +5V
   |                          |
(sensor)---resistor---+---(Arduino)
   |                  |          |
   |            capacitor        |
   |                  |          |
  GND----------------GND--------GND

Contrary to popular belief, it is not possible to make an antialiasing filter in software.

For an initial low-resolution prototype, a quick rule of thumb is to pick the RC time constant at least 10 times as long as the time between samples.

So if you are sampling at around 1000 Samples/second (i.e., a sampling interval of 1 millisecond), then 100 Ohms of resistance and (roughly) 100 uF ceramic capacitor may be adequate.
(The RC time constant here is RC == 100 Ohms x 100 uF = 10 milliseconds).

Many joysticks already have a relatively high output impedance; you'll need to use a resistor with that much less resistance to compensate.
(Sometimes you don't need any additional resistance; but you still need that capacitor between the Arduino analog input pin and the Arduino ground pin).
(Many sensors have an output impedance more than 10 KOhm; people who use them are pretty much forced to use an op-amp chip to get clean signals).

Entire books have been written on signal filtering.
In addition, there are many other techniques for getting higher resolution analog signals, higher speed data collection, and trading off between them --
but they are probably overkill for reading the position of a joystick.

The noise from your joystick pots will drown out any resolution over eight bits regardless.  They were designed for the very crude game port on a pc and use a copper wiper on a slab of carbon.  Not a terrible recipe for a noise generator.


Soldering headers screwed up Trinket? Last week I purchased a couple of Trinkets from Adafruit (5v micro-USB). The first thing I did was solder the headers to one of them. I did the whole setup process w/ the Arduino IDE and didn't have any issues, until I actually tried uploading the "Blink" example.

When I plug in the Trinket, I get the pulsing red light, but when I try to upload during that, I get:

avrdude: error: usbtiny_send: Input/output error (expected 64, got -5)
avrdude: verification error, first mismatch at byte 0x0004
         0x1d != 0x36
avrdude: verification error; content mismatch

avrdude: error: usbtiny_transmit: Input/output error

Then, if I press the reset button, I can't get it to "pulse" again. The red light just dimly turns on and stays constant.

I tested the other Trinket I ordered (that has not been soldered yet) and it works perfectly fine.

So, did I somehow screw up something when soldering the headers? Or do I have a faulty Trinket?

For reference, here's the trinket in question...

There are what appear to be burn or melt marks on the 5 pin component labeled QTSO and on the diode near the USB pin. That could be a sign of damage due to soldering, reverse polarity, or excessive current draw through the voltage regulator (a short circuit).

Based on the fact that the light stays on solid when the reset button is pressed,  it sounds like it could also a different issue. First, turn on verbose output in the arduino IDE and post the full output when you try to upload.

Next, try disconnecting everything except the USB cable while uploading the program. If that does not fix it, it is most likely that the bootloader is corrupted. This has happened to me on multiple occasions for no apparent reason and it is pretty easy to fix.

If repairing the bootloader does not fix this, it is most likely that one or both of the components mentioned above are damaged.

On this side it doesn't seem like there's a solder bridge, although it's possible there is one on the other side if you were heavy handed on the solder.

Since you did the verification with the other unit this can't be a software or usb cable issue.

So indeed it's coming from the trinket itself. I think your best bet is to desolder the pins and check the upload again. If it's failling, try flashing a new bootloader. And if it's still not working then I guess either it was faulty from the start or you did damaged a component during the soldering.


Uno - measure the voltage, NOT connecting GND I'm trying to use an Arduino Uno, to measure the Voltage over a Resistor in a circuit. I guess the usual way would be to connect GND to one side of the Resistor and the AD0 Pin to the other end, and scale the (0..1023) to (0..5V).

The problem is however, that connecting the GND to one side of the Resistor affects the circuit. Since the GND of Arduino is also connected to a Servo Driver (and other stuff), Some of the power that was supposed to be consumed by my Resistor, is now consumed by the parallel circuits.

Is there any way to measure the Voltage over the resistor without using GND?

If I understand the description correctly, neither side of the resistor is at ground potential.  There's a wide gamut of methods of dealing with this, for example using a differential ADC unit, or using an instrumentation amplifier ahead of a single-ended ADC.  But perhaps the simplest method is to use two ADC channels, one attached to each end of the resistor, with ADC ground connected to some common reference point.  Measure both voltages and take their difference .

Why you are using AD0 pin for analog read? use A0-A7 for Arduino mega and A0- A5 for arduino uno case for reading of analog values. For more detail study the voltage devider and you will understand the problem more easily. As i understand there is no need to use ground.


How to Write a function or Loop or program to receive fixed number of Integers or characters over Serial? I am want to receive a 5 character hexadecimal input from user over serial port of arduino Uno.

int count = 0;                                    // count = 0
char userInput[5];

void setup()
{
  delay(1000);
  Serial.begin(19200);                            // begin serial port with baud rate 9600bps

}
void loop()
{
  if (Serial.available() > 5)
  {
    Serial.read();
  }

  else if (Serial.available() < 4)
  {
    Serial.read();
  }

  else if (Serial.available() == 5)
  {
    for (int i = 0; i < 5; i++)
    {
      userInput[i] = Serial.read();
    }

    Serial.print("User Input - ");
    Serial.println(userInput);
  }

  delayMicroseconds(10000);
}

But I want to discard the input if user inters less than 5 characters or more than 5?

Since the Serial.flush() have a different meaning now, I can not clear the buffer if user enters less than or more than 5 characters and the characters gets added to next input.

e.g. If I upload above program and entered input in following sequence:

abcde
abcd
abcd
abcd
abcd
abcdef
abcde

I got the following output:

User Input - abcde
User Input - dabcd
User Input - dacbd
User Input - bcdef
User Input - abcde

Two invisible characters appear in output which are not visible but when I copied the output from serial monitor but these characters appear when I copy paste the output into Text Editor.

So How can I modify the program to receive only 5 hex character input from user (Which user will input from Hex Keypad)? And if user enters more or less character I want to clear the input buffer for next user input so that characters from previous input doesn't get added to next one.

As noted in the comments, since your prototype is receiving data from the serial port, you need some way for the user to indicate to the program that they are finished entry, since a 4-character entry is a necessary point along the way to a 5-character entry.

What you are doing now, by checking if Serial.available()>5 is letting the serial buffer hold 6 characters before you read from it (note: 5 is not >5), but then your else statement:

else if (Serial.available() < 4)
{
  Serial.read();
}

Clears out the buffer (Serial.read() removes one character from the buffer), so you will never get to 5 characters anyway, unless all 6 characters come in between runs of loop(), which is not likely at 19200 baud.

Not to mention that while data is sitting in the buffer, you don't know what it is and can't act on it. It is better to use the buffer as intended, which is to allow the Arduino to collect serial data, even while your program is working on other things, and then grab any pending data from the buffer as the program loop()s.

You have declared the userInput[5] array to hold user input, but note that if you only declare it at 5 chars long, it cannot hold the null-character terminator that is standard for C-style strings. It would be better to declare this as:

char userInput[6];  // Holds 5 user characters, plus null terminator.

In your loop(), you should copy out the contents of the buffer into your userInput, check the length or for a termination character, such as a carriage return or newline (i.e., pressing 'Enter' on the serial terminal.) and act accordingly. Here is an example, showing just the relevant bits for the user input and hiding the rest in [...]:

char userInput[6];  // Holds 5 user characters, plus null terminator.

void setup() {
  userInput[0] = '\0';  // Initialize string to empty
  Serial.begin(9600);
}

void loop() {
  uint8_t processInput = 0;   // Set to 1 if we have complete entry
  while (Serial.available()>0) {
    char input = Serial.read();
    if (input=='\r' || input=='\n') {
      // Have received a terminating character,
      // Flush the rest of the buffer
      while (Serial.available()) {
        Serial.read();
      }

      processInput = 1;

    } else {
      int s_len = strnlen(userInput, 5); // Get current length of userInput
      if (s_len<5) {
        userInput[s_len++] = input;      // Append character
        userInput[s_len] = '\0';         // Null-terminate string
      } else {
        // User has entered more than 5 characters and no terminating
        // character; here is where you can decide to clear the userInput
        // and start over, or just drop the first character and care
        // about the most recent 5, etc. Here, we will clear the input
        // and start over; The 6th character is dropped/ignored and
        // user input starts again. It is as though the 6th character
        // entered is like pressing Enter, but it does not process
        // the incoming data, beacuse 6 characters is an invalid input.
        userInput[0] = '\0';
        s_len = 0;
        processInput = 0;
        // Invalid input
        Serial.println("Error: invalid data");
      }
    }
  }

  if (processInput) {
    Serial.print("User input - ");
    Serial.println(userInput);

    if (strnlen(userInput, 5)==5) {
      // Do something **here** with the input string!!

      // Reset input string
      userInput[0] = '\0';
    } else {
      // Invalid input
      userInput[0] = '\0';
      Serial.println("Error: invalid data");
    }
    processInput = 0;
  }
}

Note, this code is not fully tested and may contain bugs. In particular, I did not intensely check if the while (Serial.available()) {} properly handles a lot of extra data.

One final note, you don't need the delay() with this code.

EDIT:

I tried the sample code above and it had a couple of bugs, one of which was that after a successful 5-digit entry, the input string was not reset to empty. I have now updated the code and it's a valid, working program to receive and process a 5-character input on the serial port and to toss an error if fewer than 5 or more than 5 characters are entered. Entry is terminated with a carriage return or newline (enter key).

I wrote following program, it receives 5 character input from user and if user enters input more than 5 characters then program store only 1st 5 characters and if user inputs less than 5 characters long the it rejects than input altogether..

char userInput[5];
void setup()
{
//delay(1000);
Serial.begin(9600); // begin serial port with baud rate 9600bps
}

void loop()
{
if (Serial.available() < 5)
{
   Serial.read();
}
else if (Serial.available() >= 5)
{
      for (int i = 0; i < 5; i++)
      {
        userInput[i] = Serial.read();
      }
     while (Serial.available() > 0)
     {
       Serial.read();
     }
Serial.print("User Input - ");
Serial.println(userInput);
}
delay(100);
}


Can anyone help be get readings off of my potentiometer with a push of a button? Hi I'm trying to get my Arduino Uno code to work with a in a specific way where if I push a button, the Arduino will read the raw potentiometer value once and if I don't push it nothing happens.
https://imgur.com/M7qGvtC
int switchState = 0
int switchPin = 2
int potPin = A0;

void setup() {
pinMode (potPin, OUTPUT);
pinMode (switchPin, INPUT);
Serial.begin (9600);

}

void loop() {
switchState = digitalRead(2);
if (switchState == High) {
Potval = analogRead(potPin);
Serial.print("potval:");
Serial.Println(Potval);
delay(200);
}

else {
(switchState == LOW);
while (Potval);
}
}

I had a very similar issue an it is that you aren't setting up your button as an INPUT_PULLUP. When you press the button, you are sending 5V or ground through it depending on your circuit. But then it won't reset on release. That is why either you can put a physical resistor as the schematic shows here:

or you can simply change the button initialization to INPUT_PULLUP.

I believe you are getting lots of readings when the button is pushed but nothing when released. This link should solve your problem.


Have I bricked my Arduino Uno? Problems with uploading to board I can't upload sketches to my Arduino Uno.

Have I "bricked" it?
What steps can I take to work out what is wrong?
What can I do to fix it?

It probably isn't bricked

I've got quite a few Arduinos, and over the last few years have only ever "bricked" one, and I think that was by zapping it with static electricity. Unfortunately that particular one had a SMD (surface mounted) processor chip, so it isn't easy to try swapping it with another chip.

Stay calm, and try the following steps ...

Example board

An "Arduino Uno" is not just one thing that might fail. It has multiple major components, and possibly only one has failed (if any). See this reference photograph:

Major components are:

Atmega16U2 processor - this handles the interface to the USB connection
Atmega328P processor - this is the "main" processor which has your sketch on it
Voltage regulator - this converts incoming power from the power jack to 5 V
Power LED (green) - marked "On"
Indicator LED (yellow) marked "L" - connected via an op-amp to digital pin 13
Rx and Tx LEDs (yellow) - these indicate if the USB chip (Atmega16U2) is receiving or transmitting

Note that the Rx and Tx LEDs are not connected directly to digital pins 0 and 1 on the board (marked Rx and Tx). They only illuminate if you are doing serial communications via USB, not if you have something (like a GPS) plugged directly into digital pins 0 and 1.

Also note that since the "L" LED is connected via an op-amp, it may illuminate if pin 13 is set to an input in your sketch. This is normal. It doesn't mean that something is erroneously sending data.

Check the power

USB power

Plug the board into your computer with the USB cable and check that the green "On" LED lights up.
Use a multimeter and a couple of jumper leads to test between the 5V pin and the GND pin (arrowed at the bottom). You should get a reading of around 5.0 V (I got 5.04 V on mine).

(You can buy a cheap multimeter for around $10 if you don't have one, but you are better off getting a better one for around $50 - check all the electronics web sites and stores.)

Also test between the 3.3 V pin and the GND pin - you should get 3.3 V.

If you do not get 5 V with the USB cable plugged in make sure the other end is connected to your computer. Also try a different cable.

Power jack

If you are using, or planning to use, the power jack (marked "power in" on the photo) disconnect the USB, and plug in a power supply - which should be 7 to 12 V DC with positive on the center pin.
Measure the 5 V and 3.3 V pins as above. You should still see the same voltages on them.

If you get 5 V with the USB connected, but not with the power supply then the voltage regulator (marked on the photo) is probably damaged. Or, possibly the power supply has failed. Try a different power supply to confirm which it is.

Check the power-on LED flash

If you have the Optiboot bootloader (the Uno normally ships with that) then if you press and release the Reset button, or unplug and plug the USB or power cable back in, the "L" LED should flash quickly 3 times. The "on" and "off" times are 50 ms each, the three flashes should be over within about 1/3 of a second.

If it doesn't, you may have a problem with the bootloader, or the main processor chip (Atmega328P).

Try uploading a sketch

Important: If you are having trouble uploading sketches remove any connected devices (like shields). Also remove jumper wires plugged into the board sockets. In particular, there should be nothing plugged into digital pins 0 and 1 (Rx and Tx) because that will interfere with communicating with the uploading computer.

Choose one of the simple example sketches (eg. Blink) and try to upload it. This is what you should see:

The "L" LED should flash 3 times. This is because the main chip is being reset by a command from the uploading process.
The "Rx" LED should flash quickly. This is the instructions from the uploading process trying to activate the bootloader.
The "Tx" LED should flash quickly. This is the processor acknowledging the uploaded data.

You may see the above, even if the uploading process fails. This could be because the wrong board type is selected.

If only the "Rx" LED flashes, it could be because of a problem with the bootloader, or the main processor chip (Atmega328P). Someone is knocking, but no-one is at home!

Check the board type

If the LEDs flash, but you get a message like this:

avrdude: stk500_recv(): programmer is not responding

Check the board type:

If you have the wrong board type selected it will probably send the wrong uploading instructions, and time-out or otherwise fail. If you are like me and have different boards lying around it is easy to forget that the last upload you did was for a different board type.

Check the comm port

If the LEDs don't flash at all, you may have the wrong comm port selected.

Check the comm port:

Try a different PC / Mac if possible

Try your Arduino on a different PC/Mac if you have one to hand. This can narrow down whether or not you have an issue with the particular computer you have plugged it into, or computers in general.

Do a loopback test

Disconnect all shields and other wires
Remove the board from the power
Connect a jumper wire from RESET to GND (orange wire in photo)
Connect a jumper wire from Rx to Tx (white wire in photo)

Wiring:

Plug in the USB cable, and start up a terminal program - such as the Terminal Monitor in the Arduino IDE. Type something and send it (eg. hit Enter in the Terminal Monitor).
Everything you type should be echoed back.

If everything is echoed back: That confirms you have the right comm port, the USB cable is OK and the USB interface chip (Atmega16U2) is probably OK.

If nothing is echoed back, check:

You have the correct comm port.
Try a different cable. Some cheap USB cables only have power wires and not data wires.
Check the device driver for the Arduino is installed. You probably don't need to do this if that board worked previously on this computer, but it can be worth doing if this is the first time you plugged this board into this computer.

Test the Atmega16U2 chip

If your board fails the loop-back test, and you are certain the USB cable is OK, then you can test the Atmega16U2 chip itself. There is an ICSP (In Circuit Serial Programming) header on the board, adjacent to the Atmega16U2 chip, and near the USB socket.

Disconnect the power first (unplug the USB cable and any power cable).

Then you can connect the ICSP header via 6 jumper wires to a known good Uno, as shown in the photo:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the Atmega16U2 chip is marked with a small white dot, near the "F" in "AREF". Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".

Connect up:

Good board         Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

Double-check your wiring.

Then on the "known good" board install the "Atmega_Board_Detector" sketch as described on the Atmega bootloader programmer page. The code is at GitHub - nickgammon/arduino_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Detector".

Once installed, open the serial monitor, set it to 115200 baud, and you should see something like this:

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x94 0x89
Processor = ATmega16U2
Flash memory size = 16384 bytes.
LFuse = 0xEF
HFuse = 0xD9
EFuse = 0xF4
Lock byte = 0xCF
Clock calibration = 0x51
Bootloader in use: No
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 4096 bytes starting at 3000

Bootloader:

3000: 0x4B 0xC0 0x00 0x00 0x64 0xC0 0x00 0x00 0x62 0xC0 0x00 0x00 0x60 0xC0 0x00 0x00
3010: 0x5E 0xC0 0x00 0x00 0x5C 0xC0 0x00 0x00 0x5A 0xC0 0x00 0x00 0x58 0xC0 0x00 0x00
3020: 0x56 0xC0 0x00 0x00 0x54 0xC0 0x00 0x00 0x52 0xC0 0x00 0x00 0xEE 0xC4 0x00 0x00
...
3FE0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
3FF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

MD5 sum of bootloader = 0xD8 0x8C 0x70 0x6D 0xFE 0x1F 0xDC 0x38 0x82 0x1E 0xCE 0xAE 0x23 0xB2 0xE6 0xE7
Bootloader name: Arduino-dfu-usbserial-atmega16u2-Uno-Rev3

First 256 bytes of program memory:

0: 0x90 0xC0 0x00 0x00 0xA9 0xC0 0x00 0x00 0xA7 0xC0 0x00 0x00 0xA5 0xC0 0x00 0x00
10: 0xA3 0xC0 0x00 0x00 0xA1 0xC0 0x00 0x00 0x9F 0xC0 0x00 0x00 0x9D 0xC0 0x00 0x00
20: 0x9B 0xC0 0x00 0x00 0x99 0xC0 0x00 0x00 0x97 0xC0 0x00 0x00 0x48 0xC4 0x00 0x00
30: 0x0C 0xC4 0x00 0x00 0x91 0xC0 0x00 0x00 0x8F 0xC0 0x00 0x00 0x8D 0xC0 0x00 0x00
...

However if you get a message like this:

"Failed to enter programming mode. Double-check wiring!"

That would appear to indicate that your ATmega16U2 is not working.

Test the ATmega328P chip

Disconnect the power from the "known good" Arduino Uno and rewire the ICSP jumpers as per this photo, to connect them to the "main" processor on your Uno:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".

The wiring is the same as before, except you are connecting to the other ICSP header - the one at the end of the board, furthest from the USB socket.

Good board       Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

Once connected, open the serial monitor, set it to 115200 baud, and you should see something like this:

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 512 bytes starting at 7E00

Bootloader:

7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
...

MD5 sum of bootloader = 0xFB 0xF4 0x9B 0x7B 0x59 0x73 0x7F 0x65 0xE8 0xD0 0xF8 0xA5 0x08 0x12 0xE7 0x9F
Bootloader name: optiboot_atmega328

First 256 bytes of program memory:

0: 0x0C 0x94 0x35 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
10: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
20: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
30: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
...

In this case it confirms that the main processor is working, and has the Optiboot bootloader on it.

Things you can fix

Failed voltage regulator

This isn't easy to replace, but it is only needed if you use the power jack. If you run from USB then it is not required. Alternatively you could arrange for a 4 to 5 V supply (eg. 3 x AA batteries) and connect them to the 5 V socket on the board directly.

Failed ATmega16U2 chip

This is only required for uploading sketches via the USB port, and serial debugging. It isn't particularly easy to replace because it is a SMD (surface mounted device). However you can manage without it.

You can upload sketches via the ICSP header, if you purchase a ICSP programming device.

Examples of such devices plugged into the ICSP socket:

(Those photos were taken of a Ruggeduino, but the concept is the same).

You can also get an FTDI cable, like this:

Connect it to your board's serial ports like this:

FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

Now you can upload sketches directly to the main processor, bypassing the USB chip.

You can also use my Atmega chip stand-alone programmer to upload .hex files - this lets you copy the .hex file for a sketch onto an SD card, and then program the board via the ICSP header.

Failed ATmega328P chip

The main processor can be replaced fairly easily if it is mounted in a socket. Get a replacement chip from somewhere like Adafruit for around $US 6. Alternatively, try eBay. Try to get a chip which has the Optiboot bootloader already on it, to save hassle.

Carefully prise the existing chip out of the socket, and install the new one, taking note of the location of pin 1. Pin 1 has a notch on the chip, and its correct orientation is noted on the first photo in this post with a yellow dot (closest to the edge of the board). You will probably need to straighten the legs slightly. Hold the chip by the ends and gently push down onto a flat surface, like a desk, until the are pushed inwards a bit. Try to not touch the metal pins, you may zap them with static electricity.

ATmega328P responds but has no bootloader

I have a sketch at Atmega bootloader programmer which will replace the Optiboot bootloader. The wiring is the same as for the chip detector sketch. The code is at GitHub - nickgammon/arduino_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Programmer".

Install the sketch on your "known good" Uno, and connect it to the target board with the wiring shown earlier.

Open the Serial Monitor on your "good" Uno and you should see this:

Atmega chip programmer.
Written by Nick Gammon.
Version 1.35
Compiled on Jul  9 2015 at 15:06:58 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...

Type "U" for the Uno (Optiboot) loader.

Using Uno Optiboot 16 MHz loader.
Bootloader address = 0x7E00
Bootloader length = 512 bytes.
Type 'Q' to quit, 'V' to verify, or 'G' to program the chip with the bootloader ...

Type "G" to program the chip.

You should see:

Erasing chip ...
Writing bootloader ...
Committing page starting at 0x7E00
Committing page starting at 0x7E80
Committing page starting at 0x7F00
Committing page starting at 0x7F80
Written.
Verifying ...
No errors found.
Writing fuses ...
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Done.
Programming mode off.
Type 'C' when ready to continue with another chip ...

This takes about one second. Now the bootloader is installed.

Watchdog timer problems

The watchdog timer (off by default) can be configured to reset the processor after a certain time. The intention is to recover from a "hang" for a processor deployed in the field. However if the timer is set for a short period (like 16 ms) then the processor can reset again before the bootloader has a chance to do anything.

The symptoms are that you cannot upload any new sketches. Some modern bootloaders (like Optiboot) take steps to stop this problem as one of the first things they do. However others do not.

This can be difficult to recover from, because once the sketch runs, you have the problem of it resetting, and if you have the problem you can't replace the sketch. People often report that they have to burn a new bootloader to recover. However that is only because, as a side-effect, burning a bootloader erases the current sketch.

There is a way of recovering. Take these steps:

Power off the board completely (remove the USB cable).
Hold down the Reset button, and keep it held down (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting, and thus activating the watchdog timer
Still holding down Reset, reconnect the USB cable.
Start uploading a sketch that does not have this problem (eg. Blink)
Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).
It should now upload OK - as the sketch which activated the watchdog timer never started.

Problems with the Mega2560 upload

I mention this here, even though this post is really targetting the Uno board, because it is quite common.

Some versions of the Mega2560 bootloader look for "!!!" in the incoming upload from the PC, and if they see that, drop into debugging mode. This causes the upload to fail.

Example code:

Serial.println ("Furnace overheating!!!");

Solutions:

Install a more recent bootloader. My "bootloader uploader" sketch mentioned earlier in this reply should install a bootloader that does not have that issue.

Or (more simply):

Do not use "!!!" in your sketch.

Problems uploading to the Leonardo / Micro / Esplora etc.

Boards with the ATmega32u4 as their main (and only) processor can be trickier to upload to. This is because the same chip has to handle uploads and also run your code.

There is a small window of opportunity, after the board is reset, when it looks for a new sketch to be uploaded. The technique for uploading to these boards is:

Compile your sketch without errors.
Start the upload
As soon as the IDE reports "Uploading" press and release the Reset button.

You only have a second or so to do this, before the old sketch starts running. Don't be discouraged if you have to repeat this process a couple of times. That is normal.

References

Solving problems with uploading programs to your Arduino
Sketch to detect Atmega chip types
GitHub site with chip detector / bootloader programmer
Atmega bootloader programmer
Atmega chip stand-alone programmer to upload .hex files
Engbedded Atmel AVR® Fuse Calculator
Arduino Uno Rev3 pinouts photo

I have bricked 2x ATMega328P on my Arduino Uno board due to static (I think).
The static seems to have killed the TX pin and hence the program can't be downloaded using the USB cable.
The easiest solution is to replace the microcontroller. You can buy a new ATMega328P DIP programmed with the Arduino bootloader (such as this one from Adafruit) and you are ready to go again.
Alternatively, you can still program the ATMega328P's by using the Atmel Ice or AVRISPmkII programmer or by using another Arduino as an ICSP programmer. When you do, all but the Tx pin work fine.


Arduino Uno not able to handle 2-dimensional array Now the code I'm writing in Arduino (Using Arduino) uses multiple 2-dimensional arrays. Now when I print some thing using the Serial Monitor it prints it correctly but when I declare and initialize the 2-dimentional array it won't print it.

Code:

void setup()
{
  Serial.begin(9600);
  int image_width = 56;
  int image_height = 96;

  int image_result[image_width][image_height];
  for (int i=0; i<image_height; i++) {
    for (int j=0; j<image_width; j++) {
      image_result[j][i] = 5;
    }
  }

  Serial.print("code works");
}

Now in this case "code works" does not print but when I remove the array declaration and initialization code works is printed. What is the problem?

Do 2 dimensional arrays work differently in Arduino or is it a space issue?

2D arrays work fine on arduino, but you run out of space very quickly.

An uno has 2 kilobytes of ram; your array has 56*96 = 5376 2-byte elements.

I would guess that you are writing over some critical memory value with a 5 at some point causing the program to fail.

This is what I fed my Uno:

#define IMAGEWIDTH 56
#define IMAGEHEIGHT 96

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

  int i, j;
  int image_result[IMAGEWIDTH][IMAGEHEIGHT];

  for (i = 0; i < IMAGEWIDTH; i++) {
    Serial.print("\nIMAGEWIDTH ");
    Serial.print(i + 1);
    Serial.println(":");
    for (j = 0; j < IMAGEHEIGHT; j++) {
      image_result[i][j] = i + j;
      Serial.print("image_result[");
      Serial.print(i + 1);
      Serial.print("][");
      Serial.print(j + 1);
      Serial.print("]: ");
      Serial.println(image_result[i][j]);
    }
  }
  Serial.println(F("\nDone!"));
}

void loop() {
}

This will run over the whole array, while printing progress over Serial, which then print "Done!" once it is. I suggest changing:

#define IMAGEWIDTH 56
#define IMAGEHEIGHT 96

To lesser values, unless you have a few good minutes at hand.


Connecting ESP8266 with Arduino Uno - WiFi shield not present I have an Arduino Uno and ESP8266. I want to connect and control an LED from a web server. I made a connection referring to this:

I uploaded the WifiWebServer code to the Arduino, and applied my router's credentials.

char ssid[] = "Router SSID";      // your network SSID (name)
char pass[] = "Router's WPA Password"; `

I'm getting a "Wifi Shield not present" message from the Serial Monitor. I even tried giving external 3.3v power supply to my ESP8266 module, but no change. What am I missing here? Can someone help me fix this issue?

You can program and upload code to ESP8266 using Arduino programming environment, reusing code and libraries with small changes. Check https://github.com/esp8266/Arduino for more information.

For most tasks ESP8266 may substitute Arduino board completely. It has more flash, more RAM and integrated WiFi, and is faster (80MHz).

Here is how to send commands to an ESP8266, without using an FTDI Programmer (NOTE: the IC used is LM117 (5V to 3.3v) IC for level shifting.)


Can I program the Arduino without having an actual board with the able to emulate a COM connection to the computer? I have ordered my Arduino, but it is not going to arrive until 2 months, and I would like to be able to emulate a COM connection to the emulated Arduino. I am writing a program that listens on the com port, and would like to test it.

The program needs to run on Windows, and emulate a COM connection, and a breadboard with a LED, and motors on it.

You could use the Simulator in Atmel Studio or something like Virtual Breadboard which looks good

The Atmel Studio simulator might take a bit of work to simulate your devices but if you have 2 months then maybe that's okay :) If you want to use the simulator in Atmel Studio then you might also find the Arduino plugin for Atmel Studio useful.

I think there are quite a few other solutions if you search google.

To verify communication via COM port (to send messages as well as to receive) you can use arduino emulator from wokwi.com
with the Wokwi arduino emulator, it is easy to do the changes, add input devices as well.
To create a COM port
You just need to have a
Serial.begin(9600);
Serial.println("Text message");

you will be able to see the virtual serial window in the bottom right where you can see the messages printed out as well as you will be bale to key in the serial data you want to send to Arduino.


Value appears to change sign suddenly When slot == SLOT_1 is true, speed_value is positive but when slot == SLOT_2 is true, speed_value becomes negative.

I printed the value of speed_value immediately after the statement speed_value = -speed_value and it shows a positive number. How did speed_value changed sign when it enters the slot == SLOT_2 argument?

case ENCODER_BOARD:
  if(port == 0)
  {
    uint8_t slot = readBuffer(7);
    int16_t speed_value = readShort(8);
    speed_value = -speed_value;

    if(slot == SLOT_1)
    {
      Encoder_1.setTarPWM(speed_value);
    }
    else if(slot == SLOT_2)
    {
      Encoder_2.setTarPWM(speed_value);
    }
    else if(slot == SLOT_3)
    {
      Encoder_3.setTarPWM(speed_value);
    }
    else if(slot == SLOT_4)
    {
      Encoder_4.setTarPWM(speed_value);
    }
  }

int16_t readShort(int16_t idx)
{
  valShort.byteVal[0] = readBuffer(idx);
  valShort.byteVal[1] = readBuffer(idx+1);
  return valShort.shortVal;
}

uint8_t readBuffer(int16_t index)
{
  if(BluetoothSource == DATA_SERIAL)
  {
    return buffer[index];
  }
  else if(BluetoothSource == DATA_SERIAL2)
  {
    return bufferBt1[index];
  }
  else if(BluetoothSource == DATA_SERIAL3)
  {
    return bufferBt2[index];
  }
}

All the code are taken from here and I am not the owner. I myself still studying how these whole code works. I am hoping someone out there who have experience with these kind of implementations be able to help me out.

I think I understand what's going on from here. That's why speed_value appears to change sign suddenly when entering the if...else... statement. But why speed_value == -speed_value is necessary is yet to be answered.


Keeping track of the number of rotations of a stepper motor Using the stepper.h library in Arduino IDE, how can we control the number of rotations the motor has to move?

you can keep track of number of rotations by calculating the time


Prevent function inlining I'm trying to shrink the compiled code size, and I have noticed that the compiler inlines functions a lot, even the ones I have not marked "inline", but I can't manage to turn that off.

It looks like the compiler uses the -Os flag by default (optimize for low program size), because when I add it, the resulting program size is the same.

I tried adding "__attribute__((noinline))" to the functions but it makes no difference. Any idea how to prevent function inlining?

I'm using Visualmicro on Visual Studio Community 2017. Arduino 1.8.8. Arduino Uno board.

As I wrote in the comments, I can't recreate this problem again. So I apologize for wasting everyone's time. But I still find it weird how the -Os flag works. I assumed it meant smallest possible size. But I now think it means "fairly small, but also make it run fast". Look at the code below, and how using the noinline attribute makes the code smaller. I added the -Os compiler flag to be sure, but I think it is already on by default.

class InlineClass
{
public:
    void __attribute__((noinline)) testFunc(int arg1)       // 570 bytes
    //void testFunc(int arg1)               // 602 bytes
    //inline void testFunc(int arg1)        // 602 bytes
    {
        _var1 = arg1 + 1;
        _var2 = arg1 + 2;
        _var3 = arg1 + 3;
        _var4 = arg1 + 4;
        _var5 = arg1 + 5;
    }

private:
    volatile int _var1 = 0;
    volatile int _var2 = 0;
    volatile int _var3 = 0;
    volatile int _var4 = 0;
    volatile int _var5 = 0;
};

void setup()
{
    InlineClass ic;
    ic.testFunc(1);
    ic.testFunc(2);
    ic.testFunc(3);
    ic.testFunc(4);
    ic.testFunc(5);
}

In my "local.h" file - macros & other definitions I tend to use a lot, just such as one you're asking about - I keep this one:

// Don't compile this function inline
//   '__NOINLINE void foo(void){ ... }'
#ifdef __GNUC__
#define __NOINLINE  __attribute__ ((noinline))
#else
#define NOINLINE error 'NOINLINE' not defined for this compiler
#endif

which both gives me a fairly simple way to invoke no-inlining, and a warning if I try to use it with a compiler for which I haven't defined its use. You don't really need the macro; you could use the gcc-dependent syntax - I just favor a simpler (and portable) symbol that could be defined for any compiler's no-inline syntax.


Turning LED On/Off by using SIM808 with Arduino Mega I am trying to turn an LED on/off by using GSM 808 module. Here #a0 = LED off and #a1 = LED on. I have used lcdShow function to display characters in LCD display. But nothing appears on display. What is wrong in this code?

#include <SoftwareSerial.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
//I2C pins declaration
LiquidCrystal_I2C lcd (0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
SoftwareSerial SIM808 (10, 11);
char inchar;
const int LED = 2;

void setup ()
{

    Serial.begin (9600);
    SIM808.begin (9600);
    delay (10000);
    SIM808.print ("AT+CMGF=1\r");
    delay (100);
    SIM808.print ("AT+CNMI = 2,2,0,0,0\r");
    delay (100);

    lcd.begin (16, 2);
    lcd.backlight ();

    delay (1000);

    pinMode (LED, OUTPUT);
    digitalWrite (LED, HIGH);
}

void loop ()
{
    if (SIM808.available () > 0)
    {
        inchar = SIM808.read ();
        if (inchar == '#')
        {
            lcdShow (inchar);
            delay (10);
            inchar = SIM808.read ();
            if (inchar == 'a')
            {
                lcdShow (inchar);
                delay (10);
                inchar = SIM808.read ();
                if (inchar == '0')
                {
                    lcdShow (inchar);
                    digitalWrite (LED, LOW);
                }
                else if (inchar == '1')
                {
                    lcdShow (inchar);
                    digitalWrite (LED, HIGH);
                }
            }
        }
        SIM808.println ("AT+CMGD = 1,4");
    }

}

void lcdShow (char i)
{
    lcd.setCursor (0, 0);
    lcd.print (i);
    delay (5000);

}

Firstly your code was really poorly formatted, making it difficult to see what it did.

After reformatting my best guess as to why you LCD is blank is that the SIM808 is does not have any data available.  print something in the else statement.

Next it could be that the LCD is not working, print something out in setup().

You might also want to add a delay to loop() to prevent the Arduino spamming your SIM808.


Programming other Atmel chips(excluding Atmega 328 and 168) How can we program any other chips of Atmel using Arduino Nano as a Arduino ISP ? Excluding the Atmega 328 and 168.

Since you say:

  Excluding the Atmega 328 and 168.

I'm going to assume that you already understand the general process for using your Nano as an ISP.

The Arduino IDE includes the Arduino AVR Boards hardware package which provides hardware definitions for specific configurations of:

ATmega328P
ATmega168
ATmega2560
ATmega1280
ATmega32U4
ATmega8

If your hardware matches the configuration of one of the Arduino AVR Boards then you only need to select that board from the Tools > Board menu.

It is also possible to program many other Atmel microcontrollers or alternative configurations of the microcontrollers included with the Arduino AVR Boards hardware package with your Nano but you will first need to install the 3rd party hardware package that contains the definitions for the part you want to program. You can find a fairly comprehensive list of these hardware packages here:

https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls

Once you have found the hardware package that contains the necessary definitions you will need to install it. For this you have two options:

Boards Manager

The easiest installation option Boards Manager. Most Arduino hardware packages allow this type of installation (and certainly all of them on the above list):

Copy the Boards Manager package index URL.
File > Preferences > Additional Boards Manager URLs > paste URL > OK
Tools > Board > Boards Manager
Wait for downloads to complete.
Scroll down until you see the entry for the hardware package you want to install. Click on it.
Click "Install".
Wait for installation to finish.
Click "Close"

Manual Installation

Another option is to manually install the hardware package. For a simple package this would involve:

Download the hardware package
Copy the contents of the downloaded file to {sketchbook folder}/hardware. You can find the location of your sketchbook folder at File > Preferences > Sketchbook location.
Restart the Arduino IDE if it's running

After installation you will only need to select the correct board from the Tools > Boards menu. In some cases selecting a board may also add custom menu items to the Tools menu that can be used to adjust the configuration of the board (part, clock, BOD, etc.).

  using Arduino Nano as a Arduino ISP

Note that the correct term is Arduino as ISP. There is a programmer named ArduinoISP that is completely different from the Arduino as ISP. The confusion is increased by the sketch used on the Arduino as ISP being named ArduinoISP.

Use a programmer. Atmel makes quite a few. Dragon is what I use from time to time. 3rd party ones are also available.


Error with Arduino/Processing Serial Communication I am relatively new to both Arduino and Processing and I have been working on a code that utilizes serial communication between the two. My Arduino code is reading and printing values from a piezo sensor and then sending the values to Processing, which sketches certain shapes based on the values. The code has worked previously, but for some reason it is no longer working. Everything compiles, but when I run the Processing code the sketch window is empty and remains empty. A few times the "error, disabling serialEvent()" showed up, but I just unplugged my Arduino board, closed out the programs, and restarted everything. The error no longer shows up, but my Processing sketch is still not displaying on the screen. Can someone please let me know what is wrong with my code? I really appreciate the help.

Arduino Code:

int ledPin = 13;
int knockSensor = A0;
byte val = 0;
int statePin = LOW;
int THRESHOLD = 5;
int sensorReading = 0;

void setup() {
 pinMode(ledPin, OUTPUT);
 Serial.begin(9600);
}

void loop() {
 sensorReading = analogRead(knockSensor);

  if(sensorReading > 0){
   Serial.println(sensorReading, DEC);
   delay(100);
  }
}

Processing Code:

import processing.serial.*;

Serial port;

int centerX = 550;
int centerY = 400;

float val;
float ellipseX;
float ellipseY;
float ellipseW;
float ellipseH;
float ellipseXX;
float ellipseYY;
float ellipseWW;
float ellipseHH;
float lineX;
float lineY;
float lineXX;
float lineYY;

void setup(){
  background(255);
  size(1100,800);
  frameRate(10);
  smooth();

  String portname = "/dev/tty.usbmodem1411";

  //String portname = Serial.list()[0];
  port = new Serial(this, portname, 9600);
  println(Serial.list());
  //port.bufferUntil('\n');
}

void drawEllipse(float val)
{
  if(val > 0 && val < 50)
  {
    ellipseX = random(540,560);
    ellipseY = random(390,410);
    ellipseW = val + 10;
    ellipseH = val + 10;

    stroke(0);
    fill(random(255), random(200,255));
  }
}

void drawLines(float val)
{
  if(val > 50 && val < 70)
  {
    lineX = random(500, 600);
    lineY = random(360, 440);
    lineXX = random(500, 600);
    lineYY = random(360, 440);

    stroke(0);
  }
}

void drawEllipse2(float val)
{
  if(val > 70 && val < 120)
  {
    ellipseXX = random(460, 640);
    ellipseYY = random(330, 470);
    ellipseWW = val + random(20);
    ellipseHH = val + 10;

    stroke(0);
    fill(random(50, 100), random(50, 100), random(50, 100), random(220, 255));
  }
}

void serialEvent(Serial port)
{
  String inString = port.readStringUntil('\n');

  if (inString != null)
  {
      val = Float.parseFloat(inString);
  }

  drawEllipse(val);
  drawLines(val);
  drawEllipse2(val);
  println(val);
}

It seems like you need to do some basic debugging:

Put a println() in setup. If this does not appear, you have a major problem talking to the Arduino board.
Put a println() statement in the loop() that prints out the sensor reading. That should separate hardware problems from software defects.

Try using this code and run it on your Arduino

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

void loop() {

Serial.print('hello world');
}

After uploading the code open the serial monitor and see if it shows the string 'hello world' and make sure that the baud rate of the serial monitor is set on 9600. If nothing shows this could mean that there is something wrong with your Arduino board.


USB device not recognised - windows 8.1 I'm a beginner with Arduino and i have acquired the Arduino UNO R3 board. i have followed the instructions on arduino website in order to install the board, however it fails and still remains as an unrecognised device.

consequently, arduino IDE reports that COM1 is not found, and the 'ports' menu is grayed out.

steps i have tried:

1) install the Arduino 1.0.5 IDE
   - the installation failes near the end when installing the arduino board
2) install the Arduino 1.5.7 BETA IDE
- the installation is successful but arduino device is still unrecognized.
3) i have tried manually installing the drivers by letting windows search in the arduino IDE installation folder/drivers/
- it reports that the best driver is already installed - "usb unrecognized device"
4) i have tried installing the drivers by manulally loading the .inf files from the IDE installation folders, and installing all the serial converter A/B/C/D in the list - all failed to install.

i have done all the above for both IDE 1.0.5 and 1.5.7b with windows installer And zipped files, under administrative rights in windows 8.1

How do i get this to work?

The issue was resolved by changing my USB cable. the cable in the kit was new and seemed to supply power to the arduino board, but windows was unable to identify the board using that cable. maybe the data wires were damaged.
 in any case, i changed the cable and everything worked smoothly.

if you're using USB, it should be connected to COM3 not com1


Making MCUs Arduino Compatiable I have recently just built a custom arduino using the schematics found on their website. As awesome as this little processor is, I need more power. I have been thinking of making my own MCU, but wanted to know if it is possible to make them compatible with the arduino software. It would be very nice to not have to rewrite my existing programs.

If so, how would I go about doing that? If this is not a possibility (or just not a good idea for any reason), which language should I learn to start programming these upper level MCUs.

If I do have to start using a different language, what kind of software do I use to upload the code to these processors? And do they have the common features like Serial Monitor and Serial Plotter like the Arduino IDE does.

You are speaking of porting. The arduino environment is built around a set of libraries and commands that are designed to abstract the low level access to a simpler high level language. In order to make arduino code work on a new microcontroller, you would have to rewrite and recreate the libraries using the low level access of your target microcontroller.

For example, Energia is a port of the Arduino libraries to the Texas Instruments MSP430 line of microcontrollers. Since not all features are the same, some code does not just drop in directly but additional code or libraries could be added to fix that. Even the Arduino IDE, the program used to write code and program the arduino was ported.

It would not be a trivial thing to port an entire library base.

As to your other questions, you would code your new microcontroller in any language it's programmer and compiler can use. Likely C or C++. Arduinos are typically programmed in C++. You should look into the manufacturer of your MCU to find out what software to use, and what libraries they offer. They likely do not offer something like the serial monitor right out of the box.

I have been thinking of making my own MCU, but wanted to know if it is possible to make them compatible with the arduino software.

You can always make your own mcu. In general, you will have an easier time to make it compatible if the hardware aspect of your my is similar to that of an avr.

If not, software enabled hardware works as well, usually with a performance hit.


Control multiple WS2812B strips with different leds count First of all, my English is not that good so sorry if I made any mistake.

I'm using the WS2812FX, an awesome WS2812 effect library base on Adafruit NeoPixel library to make a small controller for the lightning in my bedroom.

The question here is how do I use this library to control multiple WS2812b led strip with different leds count, like one strip with 30 leds the other with 55 leds but the effect will just cycle through each individual led of each strip.IF somehow I can add one more output pin to this.

Example : There is an effect call "Larson Scanner" will light up one led then it run from the first led to the last led and go back, I want it to do the same on both strips, on the 30 leds strip it goes from first led to 30th led then go back & on the 55 leds strips it goes from first led to the 55th led at the same time.

Hope you guys understand what I'm asking :(

Link to the library : https://github.com/kitesurfer1404/WS2812FX

The WS2812 chip requires highly timing dependent pulses to work, as I describe on my page about Neopixels. We are talking about pulse widths of 350 ns.

I suggest it would be impossible to add another strip "if I can add one more output pin to this". It's not a question of adding pins, it's being able to output pulses that fast. You can't do it, at least not on the AVR Arduinos, and I doubt that the ones with faster chips would do it either.

What you could do is connect the various strips together so it is really one long strip (assuming they aren't too far away from each other). The different strips could usefully have their own power supplies, but the data and ground would need to go from the Arduino into the first strip, then out to the second one, and so on.

Something like this:

As for synchronizing the strips, well that is just programming. If you want the first LED on the 30-LED strip to light at the same time as the first LED on the 55-LED strips, then you actually would need to light LED #1 and LED #31 at the same time.

Possible alternative

Actually what might work would be to send to strip #1 first, and then strip #2 after changing pins. That means you would have to interleave the sends. For example to make a pixel seem to run backwards and forward on two strips you make it move one pixel on the first strip, then one pixel on the second strip, and so on.

I'm not sure if the library you mentioned supports that, since the LED count is in the constructor. It looks like it might, as you can change the number of LEDs and the pin number.

You might be able to make two instances of the library object (with different names), initialize them both, and then interleave the sends between them.

I had the same question!
=> Use an arduino per LED strip :)
and, if it is necessary to interconnect them to synchronize them
In short, work around the problem

translated by Google :(


What power supply should I use? I am building a robotic arm using 8 servo motors. I am wondering about what voltage my external power will need to be to control all of them at 6v. I am wanting to use a rechargeable battery.

I am wondering about what voltage my external power will need to be to control all of them at 6v

Well that would be 6V then wouldn't it?

You're asking the wrong question. The question you should be asking is:

  How much current will I need from my 6V power supply?

And the answer is:

Add up the total current required by all of the devices and that is the minimum current the PSU has to provide

On top of that you need to consider how long the supply should last. The average current need to draw from the batteries, multiplied by the number of hours you need it to run for, is the minimum capacity of battery you need.

For instance, if you need to draw an average of 500mA for 6 hours then you need (0.5*6 =) 3Ah (or 3000mAh) batteries (or better).

You should use a Voltage Regulator for a stable Voltage Output.

First you should know your maximum Current consumption. Lets say for example maximum 2A.

You want the Voltage of the Servos stable, so they dont jerk around when there is a voltage drop or change. Because of this reason you should use a Voltage Regulator. For this example, choose one which has a Output of 6V 2A.

For the most of the Voltage Regulators you will be safe if you calculate an extra of 2V for the Voltage Drop. The Voltage Drop Value is specific for every Voltage Regulator Model. You can find this Value in its Datasheet.

So you would need a Power Source, for example a rechargeable NiMh battery with 8V(6V+2V), which can supply 2A. Not all batteries in the world will be able to give you 2A, but like all of the NiMh batteries should.

You can find the exact circuit for your Voltage Regulator in its Datasheet, which most likely also will have some (optional) capacitors in it.

In Summary:

Your needed Voltage (6V)
Your maximum needed Current (for example 2A)
Find one Voltage Regulator with 6V and 2A Output
Find out its Voltage Drop Value
6V + Voltage Drop Value = minimum battery voltage
Be sure the battery can support the maximum current (2A)
Design your circuit with the help of the Voltage Regulators Datasheet
Calculate if you need a heat sink for your Voltage Regulator


Can we write text file to SD card that can also be read in windows? I tried to use Arduino SD Library, I was able to run Datalogger and Dumpfile sample application to verify that the bits and bytes are written perfectly in the SD card.  When I tried to read from windows, everything is null. Is there an Arduino library that can write text file compatible to windows text format?

Notepad in Windows will show the raw data in a file - in all its hideous glory. However, there are things to make sure of:

Make sure that what you write to a file is ASCII characters. By that I mean do not simply write a byte or word value, convert it to a string first:

byte value;
...

value = Sensor.read(); // Return a value from 0-99
Card.write(value);

The above code will write a byte of 0 to 99 to the file - but you probably don't want that! The byte 32 is a space; 65 is the capital letter A; and 97 is the lower case letter a. Say what?

Every byte is represented by a different character in Notepad, so you need to convert the byte 97 into TWO bytes - first the byte (character) 9, and then the byte (character) 7. How do you do that?

One easy way is to use the following:

byte value;
char buffer[8]; // Define once for temporary use

...
value = Sensor.read();
sprintf(buffer, " %d", value); // Store value in buffer as chars - with a leading space
Card.write(buffer);

The above will write one (or more) characters into the file depending on the value you want to print. If your existing data was just a series of 0 bytes, your old code would have been nothing but NULLs. This will (at least) print 0 0 0 0 0 0 0 0 0 0


What will happen if I keep my arduino on for 24 hours? Please tell me that if I keep my arduino uno on for 24 hours with a adapter, will it get harmed?

I have several home-brUnos and a genuine Mega 2560 that are now, or have, run 24/7 for periods of weeks to months, powered by either a USB port or a USB-type wall charger. All of them supported (or still do) a string of 2 or 3 DS18b20 digital thermo sensors and a WiFi or Bluetooth radio. None of them slept during those jobs and they all still live and continue work as well as they always have.

It won't be harmed.

However, if the code crashes, it wont reset itself, so if the code crashes, the purpose of running you Arduino 24/7 will defeat itself.