How to control a DC Motor with absolute encoder using Arduino and Motor Driver? I am a beginner in Arduino, I have only basic knowledge and a big appetite :)

I'm working on my cable-cam project. I've made all the mechanical parts by myself, bought all electricity parts through eBay, and everything works fine so far. With the basic RC controller I steer forward / back and I also have a speed potentiometer.

Now there is a question of security:
Since cable-cam runing on a rope fastened to two hubs/buildings/trees/piers,
up to 40 mph.
I would like to have the opportunity to program two points through which the cable-cam cannot overdrive, so that it would not go to the end of the rope and break itself.

THE concept: cable-cam is driven to point A and is marked. Then it is driven to point B and also marked. When the cable-cam reaches point B, it stops and can not go further, but it can go back to point A. And vice versa. Something like a "operation range control points" that can be programmed. Something like this: end points with Hall sensor

THE idea: on a non-powered wheel (for avoiding slippage and incorrect reading of data on the encoder), I'll set an absolute encoder to measure axis rotations and thus calculate the distance in both directions. The encoder would then be connected to the Arduino that would send the ESC signal to stop the engine when it reached that point, A or B. Stopping should be soft, not at the moment. The speed of the cable cam can be significant, so abrupt stoppage would also be a problem.

So...am I pre-ambitious? I need help with code for Arduino.

Parts:
RC: Turnigy 9X
ESC:Syren 50A and it has an Arduino library,
and the encoder:Koyo TRD NA1024NW

This is a quite high-level question, so I will answer in general terms,
skipping the fine details. You can ask here more specific questions once
you are implementing the stuff.

Yours is a 10-bit absolute encoder. It can tell you its shaft position
with a resolution of 1/1024 revolution. It's way overkill for your
application. I suggest you connect only the four most significant bits
(pins 9 – 12), which will give you a resolution of 1/16 revolution.

It's better to read the four bits simultaneously. This can be done using
direct port
manipulation. I
would connect pins 9 – 12 of the encoder to pins 4 – 7 of the Arduino
respectively. As the encoder outputs are open-collector, you have to
enable the pullups in setup():

PORTD |= 0xf0;  // enable pullups on pins 4..7

and you can read the encoder simply as

uint8_t ecoder_value = PIND & 0xf0;

Notice that this will give you a result that is left-aligned. This way
you can treat it as an 8-bit Gray code.

Next step is to decode the Gray code. I let you research how to do that,
as you can probably find examples, or even ready-made libraries for
that.

Next, you have to extend the value to a wider bit length in order to
know the absolute position of the cable-cam. The encoder only tells you
where you are within a revolution, but it doesn't tell you how many
revolutions you did. The extension is done by comparing the current
encoder position with the previous one, taking the difference (which can
be positive or negative), and adding it to the previously computed
absolute position. Something like this:

int32_t absolute_position;

void update_absolute_position(uint8_t encoder_position)
{
    uint8_t old_position = absolute_position;  // extract LSB
    int8_t delta = encoder_position - old_position;
    absolute_position += delta;
}

Beware of the types of the variables. The type of delta, for instance,
ensures that the result of the subtraction is wrapped the correct way to
yield a number between −128 and +127. Thus, the sign will tell you which
is the shortest path (clockwise or counterclockwise) from the previous
to the current position.

Note also that you have to call this function frequently enough: more
than once per half revolution. Otherwise it won't know which direction
the wheel turned. If your loop() runs fast enough (you don't use
delay(), right?), you just have to call this function once in
loop(). Otherwise you would have to setup a timer interrupt to ensure
the updates are frequent enough.

Lastly, you have to define the limits:

int32_t left_limit = INT32_MIN;
int32_t right_limit = INT32_MAX;

// To set the left limit to the current position:
if (user_pressed_the_relevant_button()) {
    left_limit = absolute_position;
}
// and likewise for the right limit.

and condition the maximum speed on the distance to the closets limit.
Assuming you store the speed as a signed number (the sign being the
direction), you would constrain it to always be between a negative
min_speed and a positive max_speed, which could be updated as
follows:

// Slow down if close to a position limit.
if (absolute_position - left_limit < BREAKING_DISTANCE) {
    min_speed = map(absolute_position,
        left_limit, left_limit + BREAKING_DISTANCE,
        0, -ABSOLUTE_MAX_SPEED);
} else {
    min_speed = -ABSOLUTE_MAX_SPEED;
}
if (right_limit - absolute_position < BREAKING_DISTANCE) {
    max_speed = map(absolute_position,
        right_limit - BREAKING_DISTANCE, right_limit,
        +ABSOLUTE_MAX_SPEED, 0);
} else {
    max_speed = +ABSOLUTE_MAX_SPEED;
}
speed_to_apply = constrain(requested_speed, min_speed, max_speed);

Note that this makes the speed limit a linear function of the position.
You may want to look into easing functions to have a smoother breaking.


Precision voltmeter using Arduino I am newbie, I need to measure precise voltage in range 0.00-0.80V, two digits precision.

The voltage will not be greater than 1V-1.2V.

I wonder if I need divider or not, I am sure that voltage won't rise above 1.2V.

Can I connect the point to measure directly to analog input, or I still need to use divider? Please explain why.

A divider is used to (as the name suggests) reduce a higher voltage to a lower voltage.  Using a divider on a small voltage will only make it smaller and harder to measure.

To get the most out of your measuring you need to have the reference voltage as close to the highest voltage you want to measure as possible.  The highest voltage that can be applied is not dependent on the reference voltage, but the supply voltage, and as 1.2V is way less than 5V (or 3.3V on a 3.3V board) you have no worries there.

So you need to change the reference voltage - the voltage that the ADC uses as its upper measurement voltage.  That's simple enough, since many of the Arduino boards include an internal 1.1V analog reference voltage generator that you can switch to (see: analogReference())

So when you have switched to the 1.1V analog reference the ADC is capable of measuring 0-1.1V in 1024 steps.  That's 1.1/1023=0.00107V per bit of precision.

The formula is:

V = ADC / 1023 * Vref

So a reading of 1 would give you 0.00107V - a reading of 2 would be 0.00215V, etc.  That's plenty of resolution to meet your 2 decimal places requirement.

One thing to note though is that the internal 1.1V reference isn't that stable or accurate (or not even there on some chips).  If you need better stability and accuracy then it could pay to use an external voltage reference chip.  These are like a linear voltage regulator but are far more accurate and stable (and can't provide lots of current).  Pick one that is greater than your upper measurement voltage but as close to it as you can get (so just above 0.8V) and feed the output into the external ARef pin and switch the analog reference to the EXTERNAL mode.

You could use a voltage divider on the external ARef pin to provide a low reference voltage, but the stability and accuracy will be no better (and probably worse) than the internal 1.1V voltage reference, so there really is no point.


Ultrasonic Sensor(HC-SR04) recording random distance I am am trying to make a code which automatically controls relay on basis of ultrasonic sensor measurements. I am using a nodeMCU as a microcontroller rather than an arduino. The relay and the ultrasonic sensor is being powered from a 5V source and nodemcu from a 3.3V Source. I don't think none of the sensors are interfering with each other as all the sensors are kept at a distance. Due to the random values my relay is being latched without any reason.
Can someone please help me out with the problem. I don't want these values(above 3000) being shown in the serial monitor.
#define TRIGGER 5
#define ECHO    4
#define RELAY   0

void setup() {
  Serial.begin(9600);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);
  pinMode(RELAY, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  }else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}

These random values could be nothing but noise as your receiver may be sensing other source of ultra sound. In your case, the circuit is especially sensitive as the output powers a relay and any noise in the input side will cause the relay to "chatter". There are many approaches to filtering and smoothing out the signal. One method would be to implement a basic averaging algorithm where you take several readings and then average out the result. Compare this result with the threshold and the output should be smoother.
EDIT
Here is a rudimentry example, where I take multiple readings (nb_measurements measurements) and then take the average over it:
long getDuration() {
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  return pulseIn(ECHO, HIGH);
}

void loop() {
  float duration = 0, distance = 0;
  int nb_measurements = 10;
  for (int i = 0; i < nb_measurements; i++) {
    duration += getDuration();
  }
  duration = duration/nb_measurements;
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  } else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}

Due to the extra processing, this will be in theory slower than your previous code but in practice, you wouldn't perceive it as long as you keep nb_measurements at a reasonable value. There are more complex digital signal filtering algorithms, search around and you can find good documentation and libraries online.


Using two ultrasonic sensors together Using two ultrasonic sensors together, how can I enable one before the other?

You need to tell the sensor to send their pulse using the trigger line.  So triggering isn't a problem.
The problem is that you might get an echo returned on both sensors, but you know which sensor sent the pulse so you can ignore the return that was received by the 'wrong' sensor in your code.
So

While(1)
{
  SendPulse(SensorTx1);
  GetEcho(SensorRx1);
  SendPulse(SensorTx2);
  GetEcho(SensorRx2);
}

Is that what you mean?  If not please can you expand you question?


I would like to control 16 motors with a servo shield Ok so I've used nicks code and have the code running once ok.... I the noticed however I had a fast 180 sweep and then it returned under control of code. I then noticed the comments wrt pulselen of 1000 being zero degrees and using 1500 as 90 degrees.... Wow so I get a single movement which holds but it doesn't go 90 degrees...

I'm using an Adafruit servo shield.

I can make my servo move. However, I want to stop it at 90 degrees without it returning to 0 degrees each time.

What am I missing?

The code I've used is as follows:

void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
}

void loop()
{
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
  {
    pwm.setPWM(0, 0, pulselen);
  }
  delay(500);
}

The code in loop is called repeatedly. Thus it does this:

Go from SERVOMIN to SERVOMAX very rapidly (I measured 72 ms)
Pause half a second
Repeat the above

To make it pause at SERVOMAX you need to either not repeat the loop, or put it all in setup, eg.

#include <Adafruit_PWMServoDriver.h>
#include <Wire.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)
void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
  {
    pwm.setPWM(0, 0, pulselen);
  }

}

void loop()
{
}


Why can't I declare variables inside an if statement? I have a void function that helps me set the time on my arduino clock. I need to use the same function twice - once for the alarm and once for the actual time. The variables I am defining need to equal either alarmHours and alarmMinutes, or hours and minutes. This was my solution:

void setting(int i){
 if(i==0){
  int mi=alarmMinutes;
  int ho=alarmHours;
 }else if(i==1){
  int mi=minutes;
  int ho=hours;
 }
//more code later
}

I got an error saying that ho and mi are undefined.
I fixed this like this:

void setting(int i){

 int mi;
 int ho;

 if(i==0){
  mi=alarmMinutes;
  ho=alarmHours;
 }else if(i==1){
  mi=minutes;
  ho=hours;
 }
}

This solved the problem. Why couldn't I use the first option if I passed in a 0 or a 1 to the parameters of the function?

Declaring a variable inside a block means that they only exist within that block. Once the block is exited, they become inaccessible.


Stacking adc's when making an midi controller ( lots of potmeters) I'm making a midi controller with the Arduino uno. It contains approximately 50 analog inputs with potentiometers. I have enough MCP3008 adc's here but I have no idea how I connect 2 or more adc's to the Arduino so that I can read 50. How do you stack adc's?

These ADC's use the SPI protocol. Luckily the Arduino has one onboard.

With each ADC you get 8 channels (thus inputs). Since you need more than one SPI device (ADC in your case).

With SPI you can chain multiple SPI devices to your SPI port of the Arduino. To select which is active you use the Chip/Slave select signal. This is a separate GPIO you can define yourself. Read more about SPI to read details.

For 50 inputs you need 50 / 8, rounded up is 7 ADCs. This means also 7 CS pins. Thus in total you need 3 (for SPI) + 7 = 10 pins. I hope you have that many left.

About 'stacking', just put the ADC's on a breadboard and wire them according to the SPI protocol.

See also Arduino Reference SPI


Access denied when Uploading I went to upload my sketch to my Uno (r3), but unusually, the Upload Console returned this error:

avrdude: ser_open(): can't open device "\\.\COM4": Access is denied.

Just started seeing this, cannot upload.

There might be another device has already connected to that port. It could even be a terminal emulator which is left connected from last debugging session.

Otherwise, make sure that your UNO is really presented on COM4 by checking with "Device Manager". if not, change the port where it is available.


millis() in a millisecond stopwatch I'm making a stopwatch that will measure time between two points.

I want that stopwatch to have a millisecond accuracy.

After the start when someone touch the pad it will show like the time of the touch (15.359) 15 seconds and 359 millis.

I have an arduino uno board.
Everywhere I read it says that millis its not reliable, and in a feel tests it seems not very accurate. Also a lot of places say to use a RTC, but every RTC I found and read about it seem to use only second and not milliseconds. Others say to use a 32 KHz crystal, but I'm not sure if it will fix this. Could anyone give some ideas?

The Arduino will only record time, only that, start and get time and subtract and write on the serial and end.

Thanks!
update 1: thanks Mattia for the edit.

update2 : I was making some  math, and if the device is on for 8 hours, and i want millisecond precision i need something like 30ppb right?
Would this do the job?
http://www.digikey.com/product-detail/en/abracon-llc/AOCJYR-12.800MHZ-M5649LF/535-12624-1-ND/4989030

The resonator on the Arduino Uno is better than the internal oscillator of the Atmega328p, but still not very precise. Therefore, for accurate measurements, you need to use a better quality crystal. For instance @ 16 MHz. Once you set the correct prescaler in the Arduino, this should give you accurate millis() - as long as the crystal that you're using is accurate.


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


NodeMCU v1.0 high power consumption in deepsleep I am using a NodeMCU v.1.0 ESP-12 for a small project. It is powered by 3xAA batteries (4.5v) in Vin, but to reduce power consumption I need to put in in deepsleep every now and then.

Running this small sketch:

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

  // Wait for serial to initialize.
  while(!Serial) { }

  Serial.println("I'm awake.");

  Serial.println("Going into deep sleep for 20 seconds");
  ESP.deepSleep(20e6); // 20e6 is 20 seconds
}

void loop() {
}

I have measured a consumption of 8mA when it goes to deepsleep, and this is not acceptable for my purpose. In order to wake up from sleep I have connected pin GPIO16 (D0) to RST, and it works. I knew that NodeMCU should have only few µA of consumption in deepsleep. How can I fix this?

Consider the TI TPL5110 timer chip with power control MOSFET. Set the timer period with a resistor then the TPL5110 powers on the NodeMCU periodically. Deep sleep is not used. RTC RAM will be lost so use SPIFFS for persistent data.

Adafruit has a breakout board. Take a look in Adafruit's forum for user comments because it has a few limitations.


Why is my LCD 16*2 is not displaying any characters, although all the wiring is correct? Recently I have linked up a typical 16*2 LCD (Liquid Crystal Display) display to my Arduino Uno and have linked all the pins up.

Here is my connection:(LCD pin first)

1=GND, 2=+5v, 4=11, 6=12, 11=5, 12=4, 12=3, 14=2, 15=backlight positive, 16=backlight negative

#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis()/1000);
}

This is the code that is the default for the LCD, I didn't write it.

So I have done all this and when I turn it on the screen is blank and nothing is happening. Could anyone explain what I have done wrong?

Check out this tutorial on Adafruit. It will walk you through setting it up. In the tutorial they change the pins, which I believe is the issue here. Here is a snippet.

And change your pins:

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);


DFPlayer Mini with its standard library does not being initialized I have a DFPlayer Mini bought from AliExpress.
The player works correctly in standalone mode, but I am having troubles while using it with the following components:

Seeduino v4.0;
2GB Smartbuy MicroSD card.

When I try to use this standard sketch for Arduino to connect my Seeeduino V4 to the player:

if I set the serial like mySoftwareSerial(11, 10), the player's tiny LED turns on for 2 seconds, then it switches off, and after that, the board tells me the error message below (video here);
if I set the serial like mySoftwareSerial(10, 11), the player`s tiny LED switches on and remains being switched on, while the board tells me the error message below (video here):

DFRobot DFPlayer Mini Demo
Initializing DFPlayer ... (May take 3~5 seconds)
Unable to begin:
1.Please recheck the connection!
2.Please insert the SD card!

This module's image:

The circuit diagram:

simulate this circuit – Schematic created using CircuitLab
I have tried almost everything I could. I changed the filenames on my SD card, tried to use different pins, tried to use different wires..! I even tried to disconnect the speaker from the player!
I also had seen this message on the manufacturer`s forum:

I found that the solder joint on the TX pin was bridged to the SD card holder, effectively bridging the pin to the ground. Try a continuity test between the TX and ground. If they are connected you have a bad joint.
I was able to remove the excess solder and it worked fine after that. It's a medium difficulty soldering task.

Maybe, it`s my case?

Please check if the RX/TX pins are messed up. In my case, simply RX and TX wires' places' switching did help!


Connect my Arduinos to central server, despite different IP adresses Community,

A team of friends just built, with an Arduino UNO, a system where one can open a door lock from the internet.
The Arduino UNO has an Ethernet Module (ENC28J60). When the command prompts, the Arduino will let a solenoid receive 5v, which will open it and, therefore, open the door.

The novel thing is, this door-opening-arduino connects via the Internet to a central server, a webpage that 'centralizes' the door-opening process. So, in a certain URL, we'll get a screen which goes:

All these doors are in remote locations, connected to very different routers. Some of these routers will go 192.168.1.1, whereas others will go with the 0.1 ending.

So far, my friend has hard-coded the internal IP address 192.168.1.143 for identifying the Arduino, so, he's given up on DHCP.
Afterwards, he's chosen port 6560 to be the open port and connect the door to the Internet. (VPN is not a option).

So the public IP address and port 6560 are our way in into the door. This info is shared with his webpage, where commands can be given: 'open it'.

But with these hard-coding of the 1.143 IP and the router's different default addresses, we've had trouble. You know what I mean: sometimes, the whole code must be changed for our Arduino to connect to the router. Not even close to 'plug-n-play'.

My questions seems natural: how can we ensure the Arduino connects each time to the router, without any problems?
Most devices just connect: an IP camera in these routers will connect, and will never care which IP address the router has given it. If the router resets, things will be fine, and connection will restart.

So, why not DHCP? As far as my understanding goes, a problem my friend mentioned that would happen if he chose to use DHCP would be the communication between his Arduino and his online server: 'how can I know which IP I should speak with in order to open the door? By choosing the .143, I know which would should be'.
Another problem comes in with port forwarding. Apparently, by choosing the .143 and then using port 6560, we ensure that we can access via the Internet, because there's a standarized procedure: 'please open port 6560 for this IP'.

This is a bit cumbersome. Most devices just don't work this way. We want to be able to just plug it in, let our Arduino and the router get any IP, and by just opening port 6560, we're in. Pretty simple.

How can we ensure that:

Our Arduino just connects to the router, and
that communication between our Arduino and the centralized server
just flows?

Another friend suggested configuring each router so that a device with a certain MAC address (our Arduino) gets this IP* and this port forwarding. But what if the default address is 192.168.0.1 (instead of 1.1), for example? wouldn't we be facing a problem?

We're seeking a kind of plug-n-play thing, like most access control systems work. Hardware's ok, it's connection the thing that bugs us.

Any suggestions, advice, or plain responses are really welcome. I think we're just a step away from our commit, which is creating a reliable connection for these doors. It may be just a line of code, or a config trick. Thank you for your time.

(you'll soon notice we're not that savvy on routing and switching, so If we got our premises completely wrong, don't hesitate to correct us)

Your problem is two-fold, and neither are easy for an Arduino to overcome.

First you have the problem that the router's internet-facing IP address is (unless you have a special arrangement with your ISP) liable to change at any time. You need to keep your sever up to date at all times with what that IP address is, and the only real way of doing that is for the router, or something behind the router, to connect with your server so it can update its IP address.

Secondly you have the port forwarding. The router has to know where to forward the port to. That means that either the IP address of the Arduino has to be static, or the Arduino has to somehow tell the router to do the port forwarding.  The simplest method is just to allocate a static IP address as you have done. The alternative is to use UPnP to instruct the router "I need you to forward this port through to me" - assuming the router understands UPnP. The hardest part of that though is getting the Arduino to speak UPnP. I am not aware of any UPnP libraries for the Arduino.

So keep the static IP address for the Arduino, it is simplest. One thing to note with manually allocating an IP address though is that it is vitally important you allocate it outside the IP address range of the DHCP server. Otherwise it is possible that the DHCP server could then allocate the IP address to someone else, and you'd then get a conflict. Most routers allow you to choose the range of IP addresses so you may want to go in and check that the DHCP server isn't able to clobber the IP address you have chosen.

To help solve the first problem some routers provide a "DDNS" (Dynamic DNS) facility, whereby they will periodically connect to a DDNS service to update a DNS record with the public IP address of the router. Not all provide it and those that do usually only provide access to a couple of DDNS services, so check your router to see if it does support it and if there is a suitable one for your needs there. If there is you can configure that and then, instead of connecting to the IP address of your router for issuing commands you instead connect to the DDNS domain name allocated to your router.

However, there is one much simpler option that solves all the problems in one go: reverse the communications.

Instead of the server connecting to the router to forward the port through to the Arduino to issue a command, it is far simpler (though I will admit not as responsive) for the Arduino, from whatever IP address it happens to be on, to just connect to the server itself and ask it for any pending commands.

If you have the ability to run your own software on the server you could even create your own small TCP server which the Arduino connects permanently to. The server can then send commands down that TCP connection just as if you were working with an Arduino directly connected by serial.

In both those situations it doesn't matter what IP address your router is on. You don't need to do any port forwarding. The Arduino can be on any IP address on your network.

And further more you have more security - no one could connect to your Arduino through the internet and cause havoc.


How to build and run AUnit tests I found this example on how to create a project with AUnit tests: https://www.thecoderscorner.com/electronics/microcontrollers/embedded-testing/getting-started-unittesting-arduino/
According to it and projects I have found on github my project structure should look like this:
Application
    src
        SomeComponent.cpp
        SomeComponent.h
    tests
        TestSomeComponent
            TestSomeComponent.ino
    Application.ino

But when I try to run TestSomeComponent.ino with Arduino IDE or VSC with Arduino plugin it does not see contents of src folder. I am assuming that it is treated as a separate sketch. What is a proper way to build and run tests?
[edit]
Some context (not sure what matters):

Our target board is ESP32 DevKit v1
Optimally if our developers could run tests on Windows and Linux machines
I have not gotten yet to continuous integration. I will start automating once I have any test building and running

[edit 2]
I have tried command line tools. Got AUniter running and tried like this (hoping for some automagic done by tools):
me@mypc:~/workspace/Application/Application/tests$ auniter.sh test esp32:/dev/ttyUSB0 TestSomeComponent/

I have tried any sane path combination in include path directive, for example:
#include "SomeComponent.h"
#include "app/SomeComponent.h"
#include "../../src/app/SomeComponent.h"
#include <SomeComponent.h>
#include <app/SomeComponent.h>
#include <../../src/app/SomeComponent.h>

But I keep getting this:
TestSomeComponent:4:42: fatal error: ../../src/app/SomeComponent.h: No such file or directory

I eventually switched to PlatformIO. It took me less than half an hour to rearrange sources, fix some compiler issues, build and flash my device.
Tests work really well. You just need to keep tested sources in lib folder. I even got GoogleTest package so I can use gmock in my tests.


Mysterious RX pulses on UART connect on OS X Arduino Due Arduino IDE 1.6.8, Arduino Due, Mac OS 10.11.3

I am seeing eight mysterious pulses on the RX line when I connect to the serial port using multiple client libraries (Python, JavaScript as well as the built-in Serial Monitor in the IDE). About 78-79us apiece, sampled at 1MS/s with a Logic Pro 16.

These eight pulses when interpreted at 57600 baud will jam the Firmata firmware. And they happen on every connection.

This is using a new install of the Arduino 1.6.8 IDE and with multiple sketches (the normal "Blink" sketch will reproduce this also).

Repro steps on my machine:

Install any sketch
Start a logic analyzer if you want to catch it
Go to Serial Monitor. I have mine configured for 57600 baud, Newline line ending, but it doesn't matter
If you want, close and repeat step 3
Note pulses each time you connect to the serial port

Any suggestions for diagnosing this? It sounds like it's serial driver-level in some way.

Short:

Looking at the ATMEGA16U2 firmware (https://github.com/arduino/ArduinoCore-sam/blob/master/firmwares/atmega16u2/arduino-usbserial/Arduino-usbserial.c) I find that, when you configure/change settings of the USB emulated serial port, the USART is resetted. This happens even when you open the Arduino Serial Monitor (it must configure the serial speed, etc.). This causes your spike.

Long:

Look at function:

void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)

There you'll see that after some lines, it resets the USART, by zeroing its registers:

/* Must turn off USART before reconfiguring it, otherwise incorrect operation may occur */
    UCSR1B = 0;
    UCSR1A = 0;
    UCSR1C = 0;

At page 168, of the current ATMEGA16U2 datasheet, you'll find that, by setting  UCSR1B's bit 3 (TXEN1), you enable the transmitter,  overriding the normal port operation (i.e. it becomes output). Quoting the datasheet:

  Writing this bit to one enables the USART Transmitter. The Transmitter
  will override normal port operation for the TxDn pin when enabled. The
  disabling of the Transmitter (writing TXENn to zero) will not become
  effective until ongoing and pending transmissions are completed, i.e.,
  when the Transmit Shift Register and Transmit Buffer Register do not
  contain data to be transmitted. When disabled, the Transmitter will no
  longer override the TxDn port.

Therefore, by writing UCSR1B = 0; you no longer override the TXD1 pin, which will act as input.

The ATMEGA16U2 TXD is connected to the ATSAM3X8E's RX line. In normal operation, with the UART enabled, that line stays high if no data is being transmitted. If you disable the UART, that particular line is no more driver to 1. Since the initialization code does not set the pull-up on that pin (and neither it's configured as output), the pin becomes a floating input, and any leakage to GND or even the input impedance of your probe (which is between your pin and GND), will slowly bring the logic level to 0.

To override this, problem, you should either:
1) Modify ATMEGA16U2 firmware, by setting that PIN as OUTPUT, with value 1.
2) Modify ATMEGA16U2 firmware, by enabling the pull-up on that pin.
3) (suggested) Enable the pull-up on the RX line on the ATSAM3X8E.


Serial.write is synchronous I have a good experience of the real(/critical)time world, but I'm new with Arduino.
I noticed that Serial.write is synchronous. If the buffer size is >64 (the USART size) it lasts the time of the physical transmission minus 64char.
It is obvious with simple tests as : Serial.write (char64) comes back in 1 millisec if the USART buffeur is empty and comes back in 64*10/baudrate if USART buffer is full.
Does anyone has written an asynchronous Serial.write?
If not who can help me to write it? That is to say have the docs on the USART, the interrupts and soon? Basically, the point is to fill the buffer, get an interrupt when it is free to fill it again.

Thanks for contacting me.

Until the buffer is full, Serial.write is asynchronous.  You just have to avoid filling the buffer up.

Fortunately, there is the function Serial.availableForWrite() which returns the number of bytes available in the buffer. You can use that to see if there's room in the buffer for what you want to send, and if there is then send it (i.e., just placing it in the buffer).

By re-writing the UART handing to call your own interrupt routine to send a byte as and when needed you are basically doing exactly the same as the Arduino's HardwareSerial class is doing - just with your own buffer instead of the one in the HardwareSerial class.

There is no hardware buffer in the Arduino. It only has a single byte shift register for sending UART data. Any buffering has to be done in software, so either you implement that yourself, or use the existing buffering, or only ever generate and send one byte at a time, which is fairly useless.

If you really want to re-write it then all the information you need is in the datasheet for the MCU on your chosen development board.

The terms "synchronous" and "asynchronous" when applied to situations like this are better replaced with "blocking" and "non-blocking", since "synchronous" and "asynchronous" when applied to serial communications imply different styles of data transmission, not software implementation.


How to detect which wire is live and which is neutral with Arduino? I'm building a project with relays controling other devices. I would like to be sure that relays are controling live and not neutral line. I am in Europe so user can plug to power outlet both ways so live/neutral can be reversed easily. I would like to know when power plugged in "correct" way and break master relay otherwise.

There is no "correct" way with european plugs. Live and neutral are interchangeable. If you want to be sure you switch the live pin you will need to switch both pins together.

A DPDT or DPST relay (Double Pole, Single/Double Throw) is the simplest option.

There is no way of knowing which pin is which since they both have exactly the same current flowing through them (if they didn't your RCD would trip...)


What should I learn next in arduino? This what I have learned :

digital inputs and outputs

Analog inputs and outputs

Line follower ir sensor

Pir sensor

Ultransonic sensor

Ir transmitter and reciever

Lcd

Key pad

Dc motor

Stepper motor

Servo motor

Interrupts

Timers

Watchdogs

 Arduino with raspberry pi

This topics a made with it some projects so the question is what is next to learn about arduino ? What should be my next steps ??

You say you have learned these things but were you using a motor shield for the DC motor?  How's about building your own H-bridge. And how many types of stepping motors do you now know how to control?  What about micro stepping? And what about graphical LCDs. Do you know how to make custom characters?

As your list is hardware-centric, I would next task you to learn how to write in C++ and create a library for others to use.  Learn what it means to abstract the hardware down to a few simple function calls.  How to create a class which contains an Arduino library for, say, the graphical features of a particular LCD.


Is my arduino board broken? Last night I had my arduino connected to pc and mc connected to 9 volts in the same time then today I tried to connect my arduino to pc and i removed any connection i just wanted to display a string it i used this code

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

   void loop() {

    Serial.print("NO FORMAT");
     }

its not showing anything in serial montor I tried to blink led no output still

And  i have another arduino i used the same code it showing the message in serial monitor is my previous board broken ? thank you for help when i tried to click the reset button in arduino the orang led built in is not blinking

I assume that PWR LED is turned on?
If on USB connection PWR LED is off and on 9V connection it turns on you should check fuse. It is on the right side of USB connector and is protection only from USB voltage source.

If it works you should check level of voltages or try connect usbasp and then using avrdude check if it is connecting normally.

Few ideas for voltage levels:

Voltage on "main" ATMega328 (You can check it through ISP header)
Voltage on Arduino's chip which is ATmega16, or CH340 if you have chinese one (or something like that). It should be the same as on main Arduino, but to be sure...
Voltage on reset

You need around 5 volts to be sure that it works properly because of construction of arduino's board.

If you still have no answers, no voltages you should check Arduino's schematic for more information: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

If there is electrically everything all right and you did not check with usbasp (or other AVR-compatible programmer) I believe that next step is to check bootloader on your board.


Weird arduino bug, using microphone and relay I made a clap light switch to control my room lights and ground LEDs, and it works perfectly but when ever I have both the LEDs and the lights on it kinda stops working.
I use two claps for the lights and three for the LEDs.
Does anyone know what could be wrong? here is my code.

/* DEFINE PINS */
const int buzzer = 2;
const int micPin = 0;
const int relayLED = 9;
const int relayLights = 8;

const int sampleWindow = 50;
const int N = 50;

unsigned int sample;

boolean lights = false; //lighs on or off
boolean leds = false; //leds on or off

double soundArray[N]; //array to check claps

int i = 0;
int clapsCount = 0;

void setup() {
  pinMode(relayLED, OUTPUT);
  pinMode(relayLights, OUTPUT);
  digitalWrite(relayLED, HIGH);
  digitalWrite(relayLights, HIGH);
}

void loop() {
  /* gets 50 constant sound sample and resets */
  if (i<N) {
    soundArray[i] = getVolts();
    i++;
  } else {
    i = 0;
  }
  if (i == N-1) {
    clapsCount = clapCount(soundArray);
  }

  /* if 2 claps detected do this */
  if (clapsCount == 2) {
    if (lights == false) {
      turnOnLights();
      lights = true;
    } else {
      turnOffLights();
      lights = false;
    }
    playSound();
    clapsCount = 0;
  }

  /* if 3 claps detected do this */
  if (clapsCount == 3) {
    if (leds == false) {
      turnOnLeds();
      leds = true;
    } else {
      turnOffLeds();
      leds = false;
    }
    playSound();
    clapsCount = 0;
  }
}

int clapCount(double soundArray[]) {
  int claps = 0;
  for (int j=0; j<N; j++) {
    if (soundArray[j] > 3.0 && soundArray[j] < 3.5) {
      claps++;
    }
  }
  return claps;
}

void turnOnLights() {
  digitalWrite(relayLights, LOW);
}

void turnOffLights() {
  digitalWrite(relayLights, HIGH);
}

void turnOnLeds() {
  digitalWrite(relayLED, LOW);
}

void turnOffLeds() {
  digitalWrite(relayLED, HIGH);
}

/* gets mic volts */
double getVolts() {
  unsigned long startMillis= millis();  // Start of sample window
  unsigned int peakToPeak = 0;   // peak-to-peak level
  unsigned int signalMax = 0;
  unsigned int signalMin = 1024;
  // collect data for 50 mS
  while (millis() - startMillis < sampleWindow)
  {
    sample = analogRead(micPin);
    if (sample < 1024) {
       if (sample > signalMax) {
          signalMax = sample;  // save just the max levels
       }
       else if (sample < signalMin) {
          signalMin = sample;  // save just the min levels
       }
    }
  }
  peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
  double volts = (peakToPeak * 5.0) / 1024;  // convert to volts
  return volts;
}

void playSound() {
  tone(buzzer, 1000);
  delay(100);
  tone(buzzer, 500);
  delay(100);
  noTone(buzzer);
}

Edit:
When I do both two claps and three claps, both lights turn on and no matter how many times I clap none of them turn back off.

Edit 2:
Components I am using are, a simple buzzer, and microphone called MAX4466 and a 5v relay with two outputs.

I've looked through your code and can't see anything obvious that is causing the problem, so I have refactored it a bit in the hope that the problem becomes more obvious.

/* DEFINE PINS */
const int PinBuzzer = 2;
const int PinMic = 0;
const int PinRelayLED = 9;
const int PinRelayLights = 8;

const int sampleWindow = 50;
const int MaxSamples = 50;

// Simple enumeration to clarify which state is on and off.
enum EOnOff { Off, On };
EOnOff lights = Off; //lights on or off
EOnOff leds = Off; //leds on or off

double soundArray[MaxSamples]; //array to check claps

void setup()
{
    pinMode(PinRelayLED, OUTPUT);
    pinMode(PinRelayLights, OUTPUT);
    digitalWrite(PinRelayLED, ConvertOnOff(leds));
    digitalWrite(PinRelayLights, ConvertOnOff(lights));
}

void loop()
{
    for (int sample = 0; sample < MaxSamples; ++sample)
    {   // Get the samples
        soundArray[sample] = getVolts();
    }
    switch (clapCount())
    {   // Analyse the samples
    case 2:
        lights = ChangeRelay(lights, PinRelayLights);
        playSound();
        break;
    case 3:
        leds = ChangeRelay(leds, PinRelayLEDs);
        playSound();
        break;
    }
}

/// Count the number of 'claps' in the sample data
int clapCount(/*clap array is global*/)
{
    int claps = 0;
    for (int sample = 0; sample < MaxSample; ++sample)
    {
        if (soundArray[sample] > 3.0 && soundArray[sample] < 3.5) /* Why 3.5?? */
        {
            ++claps;
        }
    }
    return claps;
}

/// Convert an EOnOff value to a HIGH or LOW value.
// OFF = HIGH
int ConvertOnOff(const EOnOff& state)
{
    return state == Off ? HIGH : LOW;
}

/// Change a relay to the given state.
/// Return the new state.
EOnOff ControlRelay(const EOnOff& state, const int& relayPin)
{
    EOnOff result = state == On ? Off : On;
    digitalWrite(relayPin, ConvertOnOff (result));
    return result;
}

/* gets mic volts */
double getVolts()
{
    const unsigned long startMillis = millis();  // Start of sample window
    unsigned int signalMax = 0;
    unsigned int signalMin = 1024;

    unsigned int sample;
    // collect data for 50 mS
    while (millis() - startMillis < sampleWindow)
    {
        sample = analogRead(PinMic);
        if (sample < 1024)                  // ?? Should this be 1024 or signalMin?
        {
            if (sample > signalMax)
            {
                signalMax = sample;  // save just the max levels
            }
            else if (sample < signalMin)
            {
                signalMin = sample;  // save just the min levels
            }
        }
    }
    const unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
    const double volts = (peakToPeak * 5.0) / 1024.0;       // convert to volts
    return volts;
}

void playSound()
{
    tone(buzzer, 1000);
    delay(100);
    tone(buzzer, 500);
    delay(100);
    noTone(buzzer);
}

What I have tried to do is to reduce the number of lines of code.  If there are less lines then there should be less bugs :)

You used a bool to record the on off state, I changed that to an enumeration because that adds a bit of clarity, and when working with mains voltages I like things being clear.

I changed your while loop into a for loop, I think it looks cleaner.  This was also the reason I changed your if statements into a switch statement.

The guts of the if statements have been removed and placed in a function ChangeRelay(), it returns the new state of leds or lights.  I could have gone with a reference to make state an in out parameter, but decided a return was simpler.

ClapCount() and GetVolts() are relatively unchanged apart from a bit of const'ing of variables to make things easier to read.  Also you might have noticed I, j and N have all been removed, because single letter variable names are my nemesis, who knows what q means and why r and t are being added to it to make z?

ControlRelay lets you route all you relay switching through one function, if there was a copy and paste bug in your code (which I don't think there was) then they will either all work or not work now.

There is a big difference between "my" code and yours, you won't be able to switch both on at the same time because the switch statement won't let you.  So in a way you problem is solved.  If you really wanted to you could add:

case 5:
    lights = ChangeRelay(lights, PinRelayLights);
    leds = ChangeRelay(leds, PinRelayLEDs);
    playSound();
    break;


SoftwareSerial with ESP8266 I am communicating with ESP8266 using SoftwareSerial of Arduino UNO. I can successfully send AT commands and get response when communicating through the terminal. But if i programmatically send particular AT commands there is no response.
For eg:
I type AT in serial monitor I get OK
But if i send the following through SoftwareSerial pins

mySerial.println("AT");

there is no response.

Can anyone tell what will be the solution as to how to send AT commands explicitly.

The sketch is

#include<SoftWareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  mySerial.begin(9600);
  mySerial.println("AT");
  delay(100);
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
}//setup

void loop()  {
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
  while (Serial.available()>0 ) {
    mySerial.write(Serial.read());
    delay(100);
  }
}//loop

I am using Sparkfun Level Shifter to get 3.3V from 5V. The wiring is straightforward. ESP8266 Vcc and CH_PD to 3.3V; GND to GND; Tx to Arduino 2(Rx) directly; Rx to Sparkfun 3.3V RXO LV side and Arduino 3(Tx) to RXI HV side) so that when Arduino transmits it gets stepped down to 3.3V and ESP8266 receives it. The wiring should be correct as it is working perfectly when AT commands are sent manually.

I tried everything of sending mySerial.write("AT/r/n"), mySerial.print("AT") mySerial.print("\r\n"), etc but nothing seems to work.

Is it that there is some problem with SoftwareSerial. But then how is it working if i send AT commands manually through terminal ?

I have been playing with an ESP8266 over the last couple of days with similar results. My conclusion was that it is very timing dependent.

If you build in (fairly large) delays into your code then you will find it works better. The delays are effectively what you are doing as you type in each new command.

I found, for example, that the AT+CWJAP (join access point) command takes quite a while, like 10 seconds or so.

Preferably don't use "actual" delays because they are blocking (unless you don't care about that). You could have a list of commands you want to send, and a system that pulls the next one out of the list when a certain time has elapsed.

If you use something like 5 to 10 second delays between commands you should get better results. At the very least, after sending one command, look for a confirmation string from the device (eg. OK, ERROR etc.).


cant figure out how to fix this compile error evrything worked for a bit and changed to much to get it working again. dont really understand the error.

[![C:\Users\bavob\AppData\Local\Temp\ccyfrkaL.ltrans0.ltrans.o: In function `loop':

C:\Users\bavob\Documents\Arduino\counte_up/counte_up.ino:96: undefined reference to `num_Write(int)'

collect2.exe: error: ld returned 1 exit status

exit status 1
Fout bij het compileren voor board Arduino/Genuino Uno]1]1

  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }  // 9
};

int pin = 2;
int buttonState = 0;
const int button = 12;
int led = 13;
int randVal;
bool pressVal;
void num_Write(int);
void setup() {
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  pinMode(button, INPUT);
}

void loop() {
  buttonState = digitalRead(button);
  if (buttonState == LOW) {
    turnOff();
    pressVal = false;
  }
  else
  {
    if (pressVal == false)
    {
      randVal = rand() % 10;
      pressVal = true;
    }
    Serial.println(randVal);
    if (randVal == 0)
    {
      void zero(int number);
      num_Write(0);
    }
    else if (randVal == 1)
    {
      void one(int number);
      num_Write(1);
    }
    else if (randVal == 2)
    {
      void two(int number);
      num_Write(2);
    }
    else if (randVal == 3)
    {
      void three(int number);
      num_Write(3);
    }
    else if (randVal == 4)
    {
      void four(int number);
      num_Write(4);
    }
    else if (randVal == 5)
    {
      void five(int number);
      num_Write(5);
    }
    else if (randVal == 6)
    {
      void six(int number);
      num_Write(6);
    }
    else if (randVal == 7)
    {
      void seven(int number);
      num_Write(7);
    }
    else if (randVal == 8)
    {
      void eight(int number);
      num_Write(8);
    }
    else
    {
      void nine(int number);
      num_Write(9);
    }
  }
}

void zero(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}

void one(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}

void two(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void three(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void four(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void five(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void six(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void seven(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void eight(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void nine(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void turnOff()
{

}

You call function num_Write a lot, you create a forward declaration:

void num_Write(int);

But you forgot to create the implementation.

If you would have forgot the forward declaration the function would not be known at all (and you would get a compiler error). But with the forward declaration you let the compiler know the signature of num_write (so the return value and argument types).

When the linker wants to link all object (.o) files together it cannot find an implementation of the function num_write and you get this error. Hence ld is the linker.


Arduino stuck in PT_WAIT_UNTIL I am using the Protothread Library from Adam Dunkels.
It is supposed to wait 1 second and then continue. But instead it gets stuck there and everything after that line is not executed.
lastTimeBlink = millis();
PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);

Why does it get stuck there?
The entire code is uploaded here: https://pastebin.com/jRsuvn54
(The comments are on german)

By best attempt to provide something of an answer.
You have said:

PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);

That is not literally represented in your code, so I take your question to refer
to:
int dist2 = dist1.toInt();
...
PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > (dist2 * 1710));

or a similar section.
When you execute this PT_WAIT_UNTIL, dist2 contains whatever value you initialized it with in int dist2 = dist1.toInt();   Assuming the condition isn't met, you are exiting runCommand() by way of PT_WAIT_UNTIL's return PT_WAITING;
#define PT_WAIT_UNTIL(pt, condition) \
  do {                               \
    LC_SET((pt)->lc);                \
    if(!(condition)) {               \
      return PT_WAITING;             \
    }                                \
  } while(0)

The LC_SET here in PT_WAIT_UNTIL is being used to generate a label that can be jumped-to later:
#define LC_SET(s)                                \
   do {                                          \
     LC_CONCAT(LC_LABEL, __LINE__):              \
     (s) = &&LC_CONCAT(LC_LABEL, __LINE__);      \
   } while(0)

Later when you later call runCommand to resume the thread, you execute LC_RESUME by way of PT_BEGIN(pt);
#define PT_BEGIN(pt) { char PT_YIELD_FLAG = 1; LC_RESUME((pt)->lc)
...
#define LC_RESUME(s)        \
  do {                      \
    if(s != NULL) {         \
      goto *s;              \
    }                       \
  } while(0)

goto *s here is ultimately jumping to the label created by your use of PT_WAIT_UNTIL.
You are now back in PT_WAIT_UNTIL checking the condition with the line if(!(condition)).  That is, you are checking millis() - lastTimeBlink > (dist2 * 1710)  However, what you are probably (more on that below) doing here is reading junk off the stack.  dist2 was initialized on a previous execution of runCommand and its effective lifetime ended when you returned in PT_WAIT_UNTIL on that prior execution.  On this new execution dist2 is uninitialized because you have jumped over its initialization.  If you turn the warning level up in File/Preferences you should see something for this.
A number of things can happen at this point, most of them not good.  I can't say what the compiler's optimizer will do to this code for certain, but not much would surprised me.  It seems likely, just on familiarity with optimizing compilers and what your code looks like, that it is generating code to read dist2.  That may  sound like a given, but it isn't when you're doing something undefined.  It's possible dist2 has the value from a previous run where you're executing this function in a loop.  But it could also have value that makes dist2 * 1710 evaluate to a duration of up to nearly 50 days, causes PT_WAIT_UNTIL to return from runCommand for so long as you're testing.
Generally, if you're going to use these proto-threads you're going to have to be very careful in thinking about what's actually initialized and what just looks like it is.  If you have a PT_whatever between a non-static local variable initialization or assignment and code where it's used, that's something to examine.


Buttons for LED strip only work when held down I am trying to make a 24 button board that assigns different methods to each button. When a button is pressed, it should interrupt the method of the previous button and begin the new method. Currently, the button has to be held down in order to work. I'm not sure why since the methods should continue without being held down. All 24 methods are similar to the one posted below.

loop(){
  if (digitalRead(inPin(5)) == HIGH){
    fifthButtonTheatreChaseRedSlow(strip.Color(127,   0,   0), 100); // Red
  }

void fifthButtonTheatreChaseRedSlow(uint32_t c, uint8_t wait) {
  for (int j=0; j<100; j++) {  //do 100 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (int i=0; i < strip.numPixels(); i=i+3)
      {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();
      delay(wait);

      // give up if switches pressed
      if (digitalRead (inPin(1)) == HIGH ||
             digitalRead (inPin(2)) == HIGH ||
             digitalRead (inPin(3)) == HIGH ||
             digitalRead (inPin(4)) == HIGH ||
             digitalRead (inPin(6)) == HIGH ||
             digitalRead (inPin(7)) == HIGH ||
             digitalRead (inPin(8)) == HIGH ||
             digitalRead (inPin(9)) == HIGH ||
             digitalRead (inPin(10)) == HIGH ||
             digitalRead (inPin(11)) == HIGH ||
             digitalRead (inPin(12)) == HIGH ||
             digitalRead (inPin(13)) == HIGH ||
             digitalRead (inPin(14)) == HIGH ||
             digitalRead (inPin(15)) == HIGH ||
             digitalRead (inPin(16)) == HIGH ||
             digitalRead (inPin(17)) == HIGH ||
             digitalRead (inPin(18)) == HIGH ||
             digitalRead (inPin(19)) == HIGH ||
             digitalRead (inPin(20)) == HIGH ||
             digitalRead (inPin(21)) == HIGH ||
             digitalRead (inPin(22)) == HIGH ||
             digitalRead (inPin(23)) == HIGH ||
             digitalRead (inPin(24)) == HIGH)
               return;

      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

Not sure if it's a hardware issue or a software issue.

It's a software issue.  You are basically saying "If this button is currently pressed down then run this sequence once", rather than "If this button has transitioned from OFF to ON then set my current sequence to X"

You need to learn about the Finite State Machine and about switching from one state to another (or one selected sequence to another) when a button changes state not when it is in a state.

So basically the whole logic of your program is flawed and needs re-working.


Broken USB connection When I connected an external power supply to my Arduino Uno R3 (it was connected to PC via USB cable too), I heard Windows disconnected device sound and the device isn't visible since then (nothing happens when I plugin the USB). Cable is ok, because it works with the second Arduino. TX/RX LEDs don't blink anymore.
Following this guide, I checked two things:

I was able to flash ATMEGA328 with LED blinking program using external ICSP programmer and it worked
I was able to flash ATMEGA16U2 with the official firmware and it completed without any error

Is there anything else I can check? I'm not really desperate to fix it - I just want to know which component is broken.

Is it possible you connected the 12V to the 5 volt pin. This would probably blow the port on windows and destroy the arduino but it appears you got lucky with the arduino. Try something else not related to the Arduino stuff after powering down and restarting the windows computer. If that does not work the odds are high the Windows port is blown. If it now is working try again you may be all set.


Your sample values (that is, the speech[] array) range from 0x00 to 0xfe, using 99.6% of the total range of possible values.

Thus, there is no software solution to increase the volume, as you are only 1 bit away from the maximum output level (0xff is the max, and one less is 0xfe).

This requires a hardware solution. One easy way is to use a commercial audio amplifier or a powered speaker (a speaker with a built-in amplifier).


Arduino Yun doesn't link any library I'm writing code for a project with Arduino Yun. My project is quite simple: it takes a picture with a webcam and saves it in a PNG or JPEG file format. I've already installed the uvc driver for Arduino Yun and tested it with my webcam and the fswebcam application. The application saved pictures both in PNG and JPEG format successfully, so I went on and installed the C compiler, make and binutils for Arduino Yun and started to write my own application that would do the same thing (just taking a picture and saving it in PNG format). After writing the code to capture the pixels of the image, I decided to write them down in a PNG file format by using the libpng library available for Arduino Yun through luci web control panel. After installing the package, I included the png.h (using #include png.h) in my source code and wrote the code to write those pixels down in a simple PNG file (thanks to this tutorial: http://www.labbookpages.co.uk/software/imgProc/libPNG.html).
What's the problem? It just won't compile! I tried everything and all I got were "undefined reference to 'function name here'" errors. I thought that, maybe, libpng was buggy so I moved to libjpeg. No luck! I get the same errors over and over again. I really don't know what else I can do, I tried everything, it just seems that the Arduino Yun C compiler can't handle "external" libraries. I thank you in advance for any help you'll give me...

Here are the errors I get when I try to compile it using the libjpeg library:

/tmp/ccdzMFgN.o: In function `salvaImmagineJPEG':
    ScattaFoto.c:(.text+0x1d9c): undefined reference to `jpeg_std_error'
    ScattaFoto.c:(.text+0x1da8): undefined reference to `jpeg_std_error'
    ScattaFoto.c:(.text+0x1dc8): undefined reference to `jpeg_CreateCompress'
    ScattaFoto.c:(.text+0x1dd4): undefined reference to `jpeg_CreateCompress'
    ScattaFoto.c:(.text+0x1dec): undefined reference to `jpeg_stdio_dest'
    ScattaFoto.c:(.text+0x1df8): undefined reference to `jpeg_stdio_dest'
    ScattaFoto.c:(.text+0x1e2c): undefined reference to `jpeg_set_defaults'
    ScattaFoto.c:(.text+0x1e38): undefined reference to `jpeg_set_defaults'
    ScattaFoto.c:(.text+0x1e54): undefined reference to `jpeg_set_quality'
    ScattaFoto.c:(.text+0x1e60): undefined reference to `jpeg_set_quality'
    ScattaFoto.c:(.text+0x1e78): undefined reference to `jpeg_start_compress'
    ScattaFoto.c:(.text+0x1e84): undefined reference to `jpeg_start_compress'
    ScattaFoto.c:(.text+0x1ed8): undefined reference to `jpeg_write_scanlines'
    ScattaFoto.c:(.text+0x1ee4): undefined reference to `jpeg_write_scanlines'
    ScattaFoto.c:(.text+0x1f10): undefined reference to `jpeg_finish_compress'
    ScattaFoto.c:(.text+0x1f1c): undefined reference to `jpeg_finish_compress'
    collect2: ld returned 1 exit status

It's not the compiler, it's the libpng package (and other libraries too).  It only contains the runtime shared library (.so) files.  You can't use it for development.

I haven't yet found if it's possible to directly install a full development package or not - normally development for OpenWRT is done outside the low-powered chip using a cross-compiler environment on a PC.


Send AT commands to ESP8266 from Arduino Uno via a SoftwareSerial port GOAL

From Arduino UNO, send AT commands to ESP8266 via a SoftwareSerial port and receive results.

CURRENT STATUS

I either send AT commands and get nothing back (wiring scheme 1) or I send AT commands and get garbage back (wiring scheme 2).

Using the Arduino as a pass through (as explained in the tutorial listed in the resources section), I can send AT commands. I have found that I can communicate with the ESP8266 at 115200 baud.

This is the results of running AT+GMR:

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

WIRING SCHEME 1

!! I have the green wire attached to pin 3 on the Arduino Uno and the yellow wire attached to pin 2; not 1 and 0 as the picture suggests !!

WIRING SCHEME 2

Same wiring as above, but I have RX and TX reversed. The green wire is attached to pin 2 and the yellow wire is attached to pin 3.

CODE

This is running on Arduino Uno

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

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

  Serial.println("Started");

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

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

RESULTS FROM RUNNING SKETCH

Wiring Scheme 1

Started

Wiring Scheme 2

Started
�����

I have tested the ESP8266 via the instructions listed in the tutorial in the Resources I've Used section below. The ESP8266 works just fine when sending it instructions via the Serial Prompt.

RESOURCES I'VE USED
http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf

QUESTION

Does anyone know if what I am trying to do is possible? And if it is, what am I doing wrong?

Does anyone know if what I am trying to do is possible?

Absolutely possible :)

  And if it is, what am I doing wrong?

SoftwareSerial isn't capable of 115200 baud rate (despite "allowing" this as a setting).  Some reports suggest as high as 57600 is workable, though in my experience 9600 is best for reliability.  How to change the baud rate on the ESP8266 will depend on the firmware version.  I've had success with AT+IPR=9600.  You only need to run this command once (it's a persistent setting).  I'd suggest, based on your description, that this is the most likely culprit that's causing the "garbage" output you describe.

A couple of other notes:

The ESP8266 runs on 3v3, not 5v, so you shouldn't have it directly connected to the digital pins—you need to run through a logic level converter.  Running 5v can fry your ESP8266.
The Arduino's 3v3 output has insufficient current to support the ESP8266 reliably (50mA Arduino vs up to 300mA for the ESP8266 by some accounts)—try running the ESP8266 off a separate supply.  It probably won't affect simple commands like AT but when you try to connect to a network etc. it may cause unexpected device resets.
As noted by others, you need to send \r\n — so make sure your Serial window is set to send both (this is a drop-down in the serial window)


How to write code to make the LED’s ﬂash in the following sequence? How to write code like this sequence? What is the meaning of 4 decimal?
For this, we had to add a delay in the code

led_Pin_1 1 0 0 0
led_Pin_2 0 1 0 0
led_Pin_3 0 0 1 0
led_Pin_4 0 0 0 1

my code, It is working. But I need to convert this code to above sequence?

int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  digitalWrite(led_Pin_1, HIGH);
  delay(200);
  digitalWrite(led_Pin_2, HIGH);
  delay(200);
   digitalWrite(led_Pin_3, HIGH);
  delay(200);
   digitalWrite(led_Pin_4, HIGH);
  delay(200);
  digitalWrite(led_Pin_1, LOW);
  delay(300);
   digitalWrite(led_Pin_2, LOW);
  delay(300);
   digitalWrite(led_Pin_3, LOW);
  delay(300);
   digitalWrite(led_Pin_4, LOW);
  delay(300);
}

int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

int led_on = 0; // Start with first (led_Pin_1)

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(led_Pin_1, (led_on == 0) ? HIGH : LOW);
  digitalWrite(led_Pin_2, (led_on == 1) ? HIGH : LOW);
  digitalWrite(led_Pin_3, (led_on == 2) ? HIGH : LOW);
  digitalWrite(led_Pin_4, (led_on == 3) ? HIGH : LOW);
  delay(250);

  led_on = (led_on + 1) % 4;
}

led_on will start with 0 (pin 1), switching only that pin on. Some explanation:

(led_on == 0) ? HIGH : LOW

This means: if (led_on == 0), than the value will be HIGH, otherwise LOW. Resulting in only pin 1 going on, if led_on is 0, and in the next loop, only pin 2 oing on, because led_on is 1 etc.

led_on = (led_on + 1) % 4;

This increases the value of led_on, but when it reaches 4, it reverts back to 0.

I don't know about the delay times you need. I guess you want to change all LEDs at once, than wait.

You can make the 4 almost identical digitalWrite lines into a function as small improvement.

If you want to do more with the LEDs, than consider storing the leds into an array and use a for loop to iterate through them.


Can't display any number using 74HC595 I just started using elegoo UNO R3 and I have the problem displaying different numbers on the segment display using the 74Hc595. I have no problem with the uploads and the circuits are working fine. However, the segment  doesn't display any numbers besides 8. Is there a problem with the code or the wiring? any suggestion?

byte seven_seg_digits[10] = { B11111100,  // = 0
                          B01100000,  // = 1
                          B11011010,  // = 2
                          B11110010,  // = 3
                          B01100110,  // = 4
                          B10110110,  // = 5
                          B10111110,  // = 6
                          B11100000,  // = 7
                          B11111110,  // = 8
                          B11100110   // = 9
                         };
// connect to the ST_CP of 74HC595 (pin 3,latch pin)
int latchPin = 3;
// connect to the SH_CP of 74HC595 (pin 4, clock pin)
int clockPin = 4;
// connect to the DS of 74HC595 (pin 2)
int dataPin = 2;

 void setup() {
  // Set latchPin, clockPin, dataPin as output
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

// display a number on the digital segment display
void sevenSegWrite(byte digit) {
  // set the latchPin to low potential, before sending data
  digitalWrite(latchPin, LOW);

  // the original data (bit pattern)
  shiftOut(dataPin, clockPin, LSBFIRST, seven_seg_digits[digit]);

  // set the latchPin to high potential, after sending data
  digitalWrite(latchPin, HIGH);
}
   }

void loop() {
  // count from 9 to 0
  for (byte digit = 10; digit > 0; --digit) {
    delay(0);
    sevenSegWrite(digit - 1);
  }

  // suspend 4 seconds
  delay(0);
}

here is my circuit and the tutorial diagram:

You're not giving your eyes time to see the numbers change. If you were a pigeon you might just see some numbers flicker past very rapidly, but we mere humans don't have a hope of seeing them - not without introducing some delay.

void loop() {
  // count from 9 to 0
  for (byte digit = 10; digit > 0; --digit) {
    delay(0);  // <--- Number of ms to wait between each digit
    sevenSegWrite(digit - 1);
  }

  // suspend 4 seconds
  delay(0);  // <--- Number of ms to wait between counts.
}


MCU Type ATmega16U2 not avaliable in Eclipse AVR Plugin I am following this guide. Now I want to create the Create the "ArduinoCore library". But when I am creating a new project, I can not select ATmega16U2 as MCU type.

But my Arduino Due R3-E and UNO SMD R3 both use ATmega16U2.

What shall I do O_o???

The ATmega16U2 on those boards isn't intended to be programmable by the end-user. It's only there to help convert from USB to TTL serial, which lets your computer communicate with the board's main microcontroller. It replaces the FTDI chip which was used on some older boards.

In the case of the Uno, the main microcontroller is the ATmega328. For the Due, it's the AT91SAM3X8E. If you want to program them from the Arduino IDE, you can usually just select the board by name from the drop-down menu.


Alternative Way to Power Components on an Arduino I have very limited knowledge regarding electronics. Please help me cure my ignorance on the subject of robotics.

I want to power the Arduino Uno R3, US-015 ultrasonic sensor, and the L298N motor controller from a single power source (7.2v). However, I'm not sure if this diagram is correct. If it is functional, will it last that way?

If this diagram is deemed wrong, please suggest alternatives with one power source.

Advance thanks to those who would reply. Elaborate answers would be very much appreciated. :D

Edit: Since it's deemed incorrect, I'm going to power Arduino through the DC barrel jack and power the L298N motor controller through the Vin and the ultrasonic sensor from the Arduino 5v output. Is it wise to do this?

Using a motor controller to power an Arduino or analog peripherals is probably unwise as the source is liable to be noisy.

Better, probably, is to power the Arduino from the 7.2V supply via a noise filtering resistor into the Arduino's Vin terminal.
NBNBNB 7.2V input MUST be to Arduino Vin.

Use a small series resistor from 7.2V to Vin and a large filter cap at Vin to ground. Then power the sensor from Arduino 5 V output.

Voltage drop in series resistor from 7.2V to Vin must drop under 2V.
Rmz is <= Vdrop / Iload
For say 50 mA load Rseries = V/I = 2V max / 0.05 = 40 Ohms .
For 100 mA R <= 2/.1 20 Ohms.
So probably try about 22 Ohms to start.
If Vdrop is > 2V a smaller R is needed.
If Vdrop is << 2V increase R.

For the capacitor at Vin - the larger the better.
100 uF good. 1000 uF better.

Resistor power dissipation is I^2 x R.
So at even 100 mA Pres = 0.1^2 x 22R = 0.22W
A 1/2 Watt resistors would suffice.
A  1 W resistor would do no harm and would tolerate the heat better.

The 22 Ohm resistor and large capacitor form an RC (Resistor + Capacitor) noise filter.
This greatly reduces motor noise which appears on the 7.2V line.
This is very standard practice in real world installations like this.
An inductor based filter can be better but RC should suffice.


FreeRTOS : Create Tasks but don't start Scheduler I'm using FreeRTOs on Arduino for the first time. In my setup(), i would like to create my tasks but i have few more configuration to do after so i would like to create my tasks but don't start the scheduler immediately.
This is my code currently with xTaskCreate and vTaskScheduler, but my code start the task immediately when they are created :

   //Create Tasks
   s1 = xTaskCreate(TaskAcquisition, NULL, configMINIMAL_STACK_SIZE, NULL, 2, &Acquisition);
   s2 = xTaskCreate(TaskStockage,NULL,configMINIMAL_STACK_SIZE + 200, NULL, 1, &Stockage);

.... Some more config

   Serial.println(F("Config finished"));

  //Check errors
  if(fifoData==NULL || fifoSpace == NULL || s1 != pdPASS || s2 != pdPASS){
  Serial.println(F("Creation error"));
  while(1);
  }
  Serial.println(F("Fifo and Tasks created"));

  //starting
  vTaskStartScheduler();

  //if the scheduler start the code don't came here
  Serial.println(F("Ram issue"));
  while(1);

Thanks for your help !

You need to vTaskSuspend the tasks immediately after creating them.

Then when you need a task to run you vTaskResume it.


Controlling DC motor from Android device Ref: https://robotics.stackexchange.com/q/8526/11146

I want to build a simple android controlled robot

I will connect android phone<usb>arduino<wire>motor controller<wire>dc motor

I wonder why I have to write two programs (android java & arduino c++)?

How can I directly control the DC motor from android java program without writing arduino code?

The short answer is "you can't." For the Arduino to do anything useful it needs to have instructions telling it what to do. In your example the Arduino's job is to do something that the Android can't – turn on and off the DC motor. You could even use a wifi or Bluetooth connection from the Android to the Arduino to make it possible to avoid the hassle of the USB cable.

Your project requires a number of small hunks of code on the Arduino to:

Listen for commands from the Android.
Validate the commands received.
Turn on or off the motor.

Roughly speaking your loop() function might look something like this:

void loop() {
  // look for a command
  // validate the command
  if (valid && turn_motor_on) {
    motor_on();
  } else {
    motor_off();
  }
}

Fortunately the Arduino code can be very simple and there is a lot of example code to help you get started.


SoftWire Library Programming Questions for I2C with Digital Pins I am trying to use 3 TOF10120 Laser Sensors with one Arduino that all have the same, fixed I2C Address. I don't believe it is possible to change the I2C address of the TOF10120, but if I am wrong, please let me know (also, I need 3 different addresses). This being said, I am trying to use the SoftWire Library (https://github.com/stevemarple/SoftWire - very interesting library, but not great documentation) to help me to use my three sensors with Digital Pins. Does anyone have any experience with the SoftWire Library and how to get readings from a laser sensor?
I can provide the code I have, but it probably wouldn't be very helpful anyway. I am particularly curious as to how to use the DigitalWrite() and DigitalRead() functions for I2C with SoftWire.
Thanks for all the help in advance!

You can change the tof10120 to any i2c address between 1 and 254. you need to write the serial string 's7-xxx#' where xxx is the decimal address required (in string form). I wrote a simple python program for the raspberry pi to change my sensor addresses via the Rx Tx.


does eeprom_write_block function of avr.eeprom.h writes a NULL terminated string or we have to manually null terminate it http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html

I am trying to figure out that if we use eeprom_write_block function or eeprom_update_block function do we need to manually null terminate it?

I came across this tutorial on avr-freaks where in one comment it is said that you have to read the strings and null terminate them but there is no word about writing. Couldnt get anything the avr-libc manual as well.

UPDATE

I have reserved some parts of eeprom using EEMEM  and they are strings. I am not sure how long the string would be except that it would be smaller than a max value. Now When I would read the string back from the eeprom I would just be reading the maximum number of bytes as again I would have no idea of the size of the string. If the eeprom has a null value at the end of the string when writing to it, the read string will have that null at the correct place.

Situation

I am saving mobile numbers of users as:

uint8_t EEMEM users[numberOfUsers][maxChar4Number];

Now when I get a number parsed and then save it to eeprom

#define eepu(message, EEADDR, BLKSIZE) eeprom_update_block((const void *)message, (void *)EEADDR, BLKSIZE);

eepu(user, users[0], strlen(user)); //strlen(user) will be less than the maxChar4Number

This will write the number to eeprom. When I read the i would be reading maxChar4Number bytes and a number could have been shorter than that length.

Since one normally does not know how long a character string is, we need a way to convey this information.  One technique used to avoid confusion is to add a NULL character (which is a zero) to the end of the string.  Another is to explicitly state how long the string is.

In the case of the function eeprom_write_block() talked about here, we see that we are formally passing not only a pointer to the string but also the size of the string.