Sketch upload freezes during write I'm trying to upload a huge sketch to my Uno R2. It's compiling just fine but it fails to upload at 94% of writing to flash...

The program is so large because of a big array of data in a separate .h file:

#include <avr/pgmspace.h>
const unsigned char PROGMEM data[] = {
  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x80, 0x7f, 0x80, 0x7f, 0x80, (etc...)

A test sketch with just 12 bytes of data uploads fine, so the problem is either with the size or some weird bug triggered by some of the data.

Unless i'm missing something, this should technically work.

Command:

    /home/hatagashira/.arduino-1.6.5/hardware/tools/avr/bin/avrdude -C/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build8921209068074674980.tmp/program.cpp.hex:i

Output:

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/hatagashira/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         Setting bit clk period        : 5.0
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 3.3
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: reading input file "/tmp/build8921209068074674980.tmp/program.cpp.hex"
avrdude: writing flash (30110 bytes):

Writing | ###############################################    | 94% 5.10savrdude: stk500_recv(): programmer is not responding

My two arduino nanos did flash and run the program correctly. I suspect a problem with the uno's serial communication but unwilling to troubleshoot further (i only have one uno). I decided to switch to the nano for further prototyping.


What is pulseIn in programming Arduino? I have seen some tutorials on ultrasonic range detector sensor.

In that, what is the meaning of the word pulseIn?

pulseIn() is used to Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds or 0 if no complete pulse was received within the timeout.

The timing of this function has been determined empirically and will probably show errors in shorter pulses. Works on pulses from 10 microseconds to 3 minutes in length. Please also note that if the pin is already high when the function is called, it will wait for the pin to go LOW and then HIGH before it starts counting. This routine can be used only if interrupts are activated. Furthermore the highest resolution is obtained with short intervals.

Syntax

pulseIn(pin, value)
pulseIn(pin, value, timeout)

Parameters

pin: the number of the pin on which you want to read the pulse. (int)

value: type of pulse to read: either HIGH or LOW. (int)

timeout (optional): the number of microseconds to wait for the pulse to be completed: the function returns 0 if no complete pulse was received within the timeout. Default is one second (unsigned long).

Returns

The length of the pulse (in microseconds) or 0 if no pulse is completed before the timeout (unsigned long).

For additional information and example code, visit: https://www.arduino.cc/en/Reference/PulseIn, hope this help you to understand the meaning of pulseIn().


Accelstepper - how to switch from fullstep to halfstep in loop? I am using Accelstepper library to control a unipolar stepper motor. In my project, I would like to run the stepper in full-step mode when I need speed and in half-step mode when I need precision. As you know, the full-step/half-step selection is done in the very beginning of the sketch...

I found a workaround by creating two instances of Accelstepper for the same stepper. That is:

Accelstepper fast(FULL4WIRE, 2,3,4,5);

Accelstepper slow(HALF4WIRE, 2,3,4,5);

With this, when I call (skipping other details of the code) fast.run() the motor moves fast (full-step) and when I call slow.run() it moves slowly as it is in half step mode.

But;

When it comes to determine to current motor position, this workaround fails, since there are two different values returned by the two functions: fast.currentPosition() and slow.currentPosition(). So this workaroud becomes useless.

My first question is: is there a way in Accelstepper to switch from full-step to half-step and vice versa in the execution(let say in the loop)? If so, the second question can be skipped.

The second: XX.currentPosition() function returns the value of a variable, namely "_currentPos" which is calculated in Accelstepper.cpp file. As I understand, there become, as many _currentPos values as Accelstepper instances. In my case, one for fast and another for slow, and somehow they are kept and calculated individually without any confusion. Is there a way to access (extern?) and set this variable from the sketch, by referencing the specific Accelstepper instence? Briefly, is there a way to copy one motor position to another?

Many thanks.

The documentation notes a setCurrentPosition() function.

void AccelStepper::setCurrentPosition ( long position )

  Resets the current position of the motor, so that wherever the motor happens
  to be right now is considered to be the new 0 position. Useful for
  setting a zero position on a stepper after an initial hardware
  positioning move. Has the side effect of setting the current motor
  speed to 0.

  Parameters

  position The position in steps of wherever the motor happens to be right now.

Use the currentPosition() function to get the current position from either mode. You will have to decide whether you want "fast" steps or "slow" steps to be the actual count, and when you switch from one context to the other, grab the current position of the last used mode, and set a new position in the mode you will use next, possibly multiplying or dividing by 2 as needed.


uBlox Neo 6M GPS module not responding I started recently working with a uBlox Neo 6M GPS module (data sheet http://www.u-blox.com/images/downloads/Product_Docs/NEO-6_DataSheet_%28GPS.G6-HW-09005%29.pdf). I connected it to an Arduino Uno as shown:

GPS  Arduino
VCC-- 3.3V
RX -- D11
TX -- D10
GND-- GND

I tried this example code from TinyGps++ (of course, changing the pins and the gpsbaud to 9600, which is the gps' default).

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 10, TXPin = 11;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup() {
  Serial.begin(115200);
  ss.begin(GPSBaud);
  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop() {
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0)
    if (gps.encode(ss.read()))
      displayInfo();
  if (millis() > 5000 && gps.charsProcessed() < 10) {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo() {
  Serial.print(F("Location: "));
  if (gps.location.isValid()) {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  } else {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid()) {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  } else {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid()) {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  } else {
    Serial.print(F("INVALID"));
  }
  Serial.println();
}

However, I do not get the GPS LED to blink, as well as my Arduino's RX LED, so the module is not transmitting any data. This is the output from the code:

A simple demonstration of TinyGPS++ with an attached GPS module
    Testing TinyGPS++ library v. 0.92
    by Mikal Hart

    Location: INVALID  Date/Time: 0/0/2000 00:00:00.00
    Location: INVALID  Date/Time: 0/0/2000 00:00:00.00

Thanks!

The Neo 6M takes a bit of time to fix when first powered on. If your board is fitted with a small battery it will most probably be flat and will take an hour or two to charge up. It is there to provide charge to the EEPROM and the onboard RTC.

Also check that the leads on the battery are not shorting.

You do not get a valid data sentence out of the GPS until the RTC can sync time.

The Error message that you got from Mike Hart routine first says that there is not enough data to do a FIX and second the Date Time is not syncing.


ISR Issue: Arduino Pro Micro I'm trying to do a small test where I am using the ISR on the Arduino Pro Micro it up from sleep mode. I'm using a Force Sense Resistor (FSR, a resistor that changes it's resistance depending on how hard you press it) with a voltage divider circuit with the output of the voltage divider connected to an analog pin and the digital interrupt pin. I'm not able to get the interrupt to trigger no matter what condition I have. I don't believe the Vout on the voltage divider is too low since the ADC registers values between 0 to 1000 (0V to about 4.8V) when the FSR is pressed. Is there anything wrong with my code that is preventing my test from working properly?
uint8_t LED = 9;
uint8_t wakeup = 2;
uint8_t enable = 0;

void Wakeup(void);

void setup() {
  // put your setup code here, to run once:
  pinMode(LED, OUTPUT);
  pinMode(wakeup, INPUT);
  attachInterrupt(digitalPinToInterrupt(1), Wakeup, RISING);
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  //Serial.println(analogRead(A2));
  if (enable == HIGH)
    digitalWrite(LED, HIGH);
  else if (enable == LOW)
    digitalWrite(LED, LOW);
  if (analogRead(A2) < 700)
    enable = 0;
}

void Wakeup(void) {
  enable = 1;
  Serial.println("Interrupt");
}

Don't do serial prints inside an ISR.

Your variable enable should be declared volatile as it changes inside an ISR. The compiler is entitled to cache the variable value if you don't do that.

You are inconsistent in your use of enable. You test for LOW or HIGH but set it to 0 or 1. Now they happen to be the same, but someone might wonder. If you are going to test for LOW or HIGH, then assign LOW or HIGH to it.

See my reference question How do interrupts work on the Arduino Uno and similar boards?.

I thought 0 and 1 were serial pins. I'm using digital pin 2

Not in the code you are not:
attachInterrupt(digitalPinToInterrupt(1), Wakeup, RISING);

Do you mean:
attachInterrupt(digitalPinToInterrupt(wakeup), Wakeup, RISING);

It's kind of confusing to have two names which differ only in case.


How arduino boards eliminate the need to press buttons to flash? I've come across many Arduino shields for various boards like the Uno, ESP8266, and ESP32 which sometimes have a button for flashing and other times they do not because the flashing is automatic.

When I upload a binary sketch to ESP32 directly through a separate Serial to USB converter, I have to make the button connections and press the buttons manually for the uploading process to work.

The manual button pressing flashing process for the ESP32 goes like this:

Hold the Reset button (IO0 to ground)
Hold the Flash button (EN to ground)
Release the Reset button (IO0 to float)
Release the Flash button (EN to 3.3v)
The board is now in flashing mode
Press "Upload" in Arduino IDE
Wait until the IDE log shows "Connecting..."
Wait until the sketch is fully uploaded
Press the Reset button (IO0 to ground then float)

Arduino boards like the WeMos Lolin32 board eliminate the button pressing process completely during the flashing process.

QUESTION: Which part of the hardware on the Lolin32 board makes the flashing process autonomous?

Here's the manual uploading schematic:

And here's the WeMos Lolin32 board, that eliminates the button pressing process completely when I upload a sketch:

I believe the answer will also apply to any other auto-flashing board out there.

I'm not familiar with this board, but according to this schematic:
https://wiki.wemos.cc/_media/products:lolin32:sch_lolin32_v1.0.0.pdf

U4 (one of the small 6-leg components) connects to IO0 (pin 25) on the ESP-32. The transistor inside U4 combines the RTS and DTR signals (from U6 USB-Serial converter IC, which will be the large IC marked SIL2104) to put IO0 in the correct state for flashing. The RTS and DTR signals can be set by the host (the computer doing the flashing).

Apologies for the lack of depth, but the short answer is components U4 and U6 on the board work together on the command from the host computer to put IO0 in the correct state for flashing.


Arduino as ISP with serial monitor for ATmega328 I have an ATmeg328 TQFP on a board (in system). I use an Arduino Uno as an ISP to programm the chip. However, i would like to use Serial Communication with the chip through the Arduino board.

Is this possible?
If yes, how can i realize this?

EDIT: i have the tx and RX pins not available. The chip is on a board. With through arduino board, I mean that I would like to use the miso mosi sck pins to do this.

Just burn the arduino bootloader to your tqfp. Then connect the tx and rx on the tqfp to the tx and rx on your arduino, and pull the reset line on the arduino low.

Downside is you have to do a manual reset on the tqfp before programming. If you have an Uno you could remove the atmega from the socket, and connect the reset on the uno to the reset on the tqfp.

Another option is to connect the TX on the tqfp to the TX pin on the Arduino using a resistor. But for this to work you have to modify the ArduinoISP sketch to make it release TX pin (UCSRnB &= ~_BV(UCSRnB);) and set it to input. And reverse it when data is received on the RX. Not trivial, and only works one way (tqfp to PC).


Using Bluetooth Dongle on Arduino I need to communicate my arduino by bluetooth but I'm living in a small town recently so I can't buy a bluetooth shield for my arduino.

Here is my question: Can I use a usb bluetooth dongle on my Arduino without a shield?
PS: There is no need to re-use that bluetooth dongle with usb again.

You'll most likely need a USB host shield (like this) for the Arduino to be able to communicate with the dongle, so that doesn't help. You may (this is a long shot) be able to crack open the dongle, look up some datasheets, and possibly find a serial interface inside that you could connect to Arduino... but like I said, it's a long shot.


What is the purpose of F() and FPSTR() in ESP8266WebServer -> FSBrowser? I found this code sample from the FSBrowser (Flash File System) example in the ESP8266WebServer library:
replyServerError(FPSTR(FS_INIT_ERROR));
replyBadRequest(F("DIR ARG MISSING"));

I was a bit confused at what F() and FPSTR() do, so I looked up the source (WString.h) and found this:
#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))
#define F(string_literal) (FPSTR(PSTR(string_literal)))

Which raised more questions. How does this code work and what does this added complexity gain over just using char* or String as is?
EDIT: Added Metrics
Here's the memory usage before and after I removed all 25 instances of F() from a file system class, measured by PlatformIO Project Inspector:

With F()
Without F()
Difference

RAM Used
29,488 bytes (36.0%)
29,792 bytes (36.4%)
+304 bytes

Flash Used
355,312 bytes (34%)
355,188 bytes (34.0%)
-124 bytes

Total (uncompressed)
359,472 bytes
359,344 bytes
-128 bytes

Adding F() decreases RAM usage by 1% and increases Flash by around half that. That's for a single class with 25 instances of F(). For a program containing 20x this code, the difference can be significant. However, you'll run out of RAM before you get there. The space savings will be limited to around 5-8%. Still not nothing.

The purpose of the PSTR() macro is to configure the string to be used directly from flash memory. The string is then not loaded to dynamic memory at runtime as it would be without PROGMEM specifier set by the macro.
The purpose of the FPSTR() macro is to cast a string to 'dummy' FlashStringHelper type to help compiler choose the right overloaded function if dynamic memory and flash memory version of a function is available. An example would be the print function.
The F() macro combines this two macros. It makes the string a PROGMEM string and casts it to FlashStringHelper.


Programming an ATtiny85 Recently I ordered some ATtiny85's from Jameco, and I've been trying to upload code to them through an Arduino Uno, following the instructions from this video on YouTube. I've been getting a lot of unexpected errors and I am now wondering if the chips I bought are the problem. Here are the specs from the Jameco website:

Flash (Kbytes): 8 Kbytes
Pin Count: 8
Max. Operating Frequency: 20 MHz
Power Supply: 2.7 - 5.5V
Operational Range: Industrial (A) (-40°C to 85°C)
CPU: 8-bit AVR
Number of Touch Channels: 3
Hardware QTouch Acquisition: No
Max I/O Pins: 6
Ext Interrupts: 6
USB Speed: No
USB Interface: No

Does the "USB Speed: No; USB Interface: No" mean these aren't programmable by my set up? Or is there is anything else I should know about these chips? Do I need to get new ones that are different?

Before you panic (try not to panic) and buy new chips, test the existing ones. See my page about detecting chip signatures which has links to code on Github for a sketch you can run on your Uno, to test the ATtiny85.

You can also upload code from a .hex file (which the IDE produces) by using a different sketch (same code link) from this page about a hex uploader and wiring like this (you also need an SD card adapter):

The first sketch and wiring should at least confirm your chips are OK. The second one is an alternative way of programming them.


avrdude: usbdev_open(): did not find any USB device "usb" I was programing the arduino and things were going great.
Then I plugged in another chip, and went to burn a boot loader.
(New chips) now, I get:

avrdude: usbdev_open(): did not find any USB device "usb"

when I try to upload code to old chips, I get:

avrdude: usbdev_open(): did not find any USB device "usb"

ten times.
I have tried reseting, and it doesnt do anything.
when I plug the device in,

dmesg shows that the device responds to my PC

[526199.130716] usb 3-1: new full-speed USB device number 7 using xhci_hcd
[526199.149422] usb 3-1: New USB device found, idVendor=2341, idProduct=0043
[526199.149427] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[526199.149430] usb 3-1: Manufacturer: Arduino (www.arduino.cc)
[526199.149433] usb 3-1: SerialNumber: 649343332353518022F0
[526199.149579] usb 3-1: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[526199.149766] cdc_acm 3-1:1.0: ttyACM0: USB ACM device

IDE settings:
board: Audruino Uno
serial posrt /dev/ttyACM0
Programer: AVRISP mkII

I also tried AVR ISP

in the command line, I tried:

   avr-gcc -DF_CPU=16000000UL -mmcu=atmega328 -o Balls.out Balls.c
   avr-objcopy -O ihex -R .eeprom Balls.out  Balls.hex
   sudo avrdude -V -F -c stk500v1 -p m328 -b 19200 -P /dev/ttyACM0 -U flash:w:Balls.hex

each time, I get:

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

How can I troubleshoot the Arduino Uno?
Is this thing broken?

Generated from IDE

Because this is a generic error, I'll answer it. I was getting this on STDERR when using the IDE:

  avrdude: usbdev_open(): did not find any USB device "usb"

This is because in the IDE I was using

Sketch → Upload Using Programmer [Ctrl + Shift + U]

However, I should have been using

Sketch → Upload [Ctrl + U]


D1 mini esp8266 error: esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header I am pretty sure this device worked yesterday. I tried to short GPIO0 to ground (flash), nothing.
I have a second ESP that uploads fine, but this one does not.
Is their another way to get this bootloader to open up? Or am I the owner of a brand new door stop?

I'm not sure if this will help EVERYONE, but I hope it at least helps someone.  I had the same issue with several different boards (3 Nano's, 2 NodeMCU ESP8266's, and 1 Uno).  I searched and searched for an answer and I kept reading about this pin or that pin being "pulled low" or "pulled hi" interfering with uploading sketches.  Well, since I couldn't find a solid answer anywhere I decided to disconnect all of the peripherals hooked to my board (except for powers and grounds) and Wah Laa!!!  The sketch uploaded like it was supposed to.  So, I believe if you just unhook all of the sending and receiving pins from all of your peripherals during upload, the sketch should upload just fine.  I hope this helps you.


Short battery life concern with Arduino Pro Mini I am using an Arduino Pro Mini with a L293D H-bridge driver to drive a bi-directional motor. The system takes input from a capacitive sensor which is constantly looking for a trigger. I don't have any low power optimization in the code. I was using Arduino UNO before which lasted for one day with a 9V battery. I switched to Arduino Pro Mini for longer battery life but the battery lasted for one day in that case as well.

Can anyone please help me understand what could be the possible reason for higher power consumption than normal for Arduino Pro Mini?

Thanks in advance for your help!

Niloy

A standard alkaline 9V battery has a capacity rating of around 500mAh (milliAmp-hours). That rating is probably based on a current consumption of around 10mA. However, if the current consumption is higher, the apparent capacity drops. At 100mA, most 9V batteries have a capacity rating of about 300mAh, and at 500mA current draw, the apparent capacity drops down to 170mAh.

This means, if you are drawing 100mA of current constantly, a 9V battery will last (0.3Ah / 0.1A) = 3h.

A typical Arduino pro mini will draw current at around 20mA.

500mAh / 20mA = 20h

This is not even counting the motor and driver.

A standard alkaline AA battery has a nominal voltage of 1.5V and a capacity of about 2000mAh, and 3 of them will provide a voltage between 4.5V (fully charged 1.5V x 3) and 2.7V (fully discharged 0.9V x 3)

With that voltage range, you could operate the Arduino pro mini in 3.3V mode, with no linear regulator, at a reduced clock frequency, such as 8Mhz, which will reduce power consumption even more.

Being able to put the chip in power-saving mode, and periodically check for necessary activity will help even more.

See http://www.gammon.com.au/power for a description of many practical methods.

That said, the Arduino is going to be a pretty small contributor to power draw compared to a DC motor, so your overall run time will heavily depend on how often the motor is turned on.


Why the MPU6050 gyroscope read write register value is 0x08 for a full scale of 500 degrees per second? I am trying to connect a gyroscope MPU6050 to arduino ATmega2560 and read its raw values from its 6DOF (gyro and acc).

I found the following code:

//Activate the MPU-6050
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x6B);                                                    //Send the requested starting register
  Wire.write(0x00);                                                    //Set the requested starting register
  Wire.endTransmission();                                              //End the transmission
  //Configure the accelerometer (+/-8g)
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x1C);                                                    //Send the requested starting register
  Wire.write(0x10);                                                    //Set the requested starting register
  Wire.endTransmission();                                              //End the transmission
  //Configure the gyro (500dps full scale)
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x1B);                                                    //Send the requested starting register
  Wire.write(0x08);                                                    //Set the requested starting register
  Wire.endTransmission();                                              //End the transmission

I am trying to break it line by line, to understand what is going on during the setup of the gyroscope.

According to MPU6050 datasheet, the I2C is at the register 0x68. The I2C helps us to access all registers and communicate with the master connected to. Which gives the following 3 lines:

Wire.beginTransmission(0x68);
Wire.write(0x6B);
Wire.write(0x00);

According the the sheet, the 0x6B is the register designed to enable and disable the gyroscope:

  This register allows the user to configure the power mode and clock
  source. It also provides a bit for resetting the entire device, and a
  bit for disabling the temperature sensor. By setting SLEEP to 1, the
  MPU-60X0 can be put into low power sleep mode. When CYCLE is set to 1
  while SLEEP is disabled, the MPU-60X0 will be put into Cycle Mode. In
  Cycle Mode, the device cycles between sleep mode and waking up to take
  a single sample of data from accelerometer at a rate determined by
  LP_WAKE_CTRL (register 108). To configure the wake frequency, use
  LP_WAKE_CTRL within the Power Management 2 register (Register 108). An
  internal 8MHz oscillator, gyroscope based clock, or external sources
  can be selected as the MPU-60X0 clock source. When the internal 8 MHz
  oscillator or an external source is chosen as the clock source, the
  MPU-60X0 can operate in low power modes with the gyroscopes disabled.
  Upon power up, the MPU-60X0 clock source defaults to the internal
  oscillator. However, it is highly recommended that the device be
  configured to use one of the gyroscopes (or an external clock source)
  as the clock reference for improved stability. The clock source can be
  selected according to the following table.

So why we set its value to 0x00 ?

And the same for setting up the gyroscope at register 0x1B where datasheets specify the full scale ranges as:

The code is setting the range of 500 dps, so why the coder set the register to 0x08 and not 0x01 where the FS_SEL[1:0] should contain decimals from 0 to 3 right ?

The i2c address is 0x68 or 0x69. Some modules with the MPU6050 have indeed 0x69, but most have 0x68.

When searching the datasheet for the word "sleep", this sentence is easy to find: "Note: The device will come up in sleep mode upon power-up".

When the MPU6050 powers up, the SLEEP bit is 1 and the sensor is in sleep mode. Therefor writing a 0 is to get it out of sleep mode. After that you can set the sensor as you want.

The FS_SEL[1:0] is a notation that is used a lot in datasheets. It is an indication that only two bits are used. It is not the bit-position in the register. Those bits are located at Bit3 and Bit4. To turn on the lower bit of FS_SEL, Bit3 has to be set to 1, thus a value of 0x08 is needed for the register.


DIY Watering - Required components I am looking as a first project after some simple project kits, to make a watering system for my indoor plants. I have seen  a few projects on instructables, so I went to look for components. I am not sure how to power the pump from the Arduino.

My idea is the following:

A bucket of water with a water pump inside. An irrigation system linked to the pump, which then goes to all the plants. The pump linked to arduino which turns it on and off based on a timer.

The components that I will be using are an Arduino uno and:

DV12 subversive pump
Irrigation watering kit

Also I guess I will need some tube to connect the pump to the watering kit.

I am not sure how to connect and power the pump (12V) with the arduino. The arduino it self will be powered by a USB on a wall socket.

I have some details about running motors etc. from Arduino pins at Driving motors, lights, etc. from an Arduino output pin.

Quite possibly what would work for you is a MOSFET - as Majenko suggested - connected up like this:

In this case you connect the positive side of your 12V supply for your pump to the pump, and the MOSFET sinks current to ground, when you require the pump on.

Don't forget the diode D1 which prevents damage from the inductive load of the pump generating high-voltage spikes.


Is it possible to program an Arduino Pro Mini using an Arduino Uno R3? I've recently received an Arduino Pro Mini as a gift, and I don't have an external USB programmer to program the Pro Mini. However, I do own an Arduino Uno R3, and I think it would be possible because they both have the same clock speed and micro-controller (16Mhz with an atmega328).

Is it possible to program an Arduino Pro Mini using an Arduino Uno?
If yes, how does one do so?

Just hook up the pins (RX, TX, reset, Power, and Ground) to the corresponding pins on your Uno.

You may have to take the ATMega328 out of your Uno for this to work.

Keep in mind that you need to hook it up to the correct power pin! If your pro mini is running at 3.3v then you must hook it up to the 3.3 pin on your Uno.

Check out the ArduinoToBreadboard page for a bit more info. Scroll down to "Uploading Using an Arduino Board". Although it shows you how to program an Arduino on a breadboard, the wiring is the same.


Feasibility of a Wi-Fi Positioning System In the project of guiding a sight disabled person in a known environment, we need to have a precise way of figuring out where the user is. Our current solution is to use WPS.

This is however our first project with Arduino, and we're not quite sure if we're going the right way about this. We're thinking of getting a compass component and such, but is there something we should know before advancing further in the project?

EDIT: Additional information.
The system is placed on the user, most probably strapped to the arm. The communication to the Wi-Fi beacons will be done from there, as well as the calculations.

The environment is supposed to be as complex as an exposition hall, but we can aim higher.

Budget range is around $100, Arduino itself excluded. A UNO is already provided to us.

I don't think that arduino is the right hardware for such a project. Better use a cheap android phone, there you have a stronger processor with more memory as well as a lot of sensors like compass, accelerometer, gyroscope and maybe in newer ones barometer, which you will need - also you have wifi. An arduino uno just comes without wifi and all the sensors. Also I guess a lot of persons already have a phone, so this will lower your project costs, because hardware is already available at most users. Last but not least I think you could use mobile phone vibrations to give feedback to the sight disabled users, oder sound commands like "go left" etc.


Adding null character to char array I have this code written and functioning that will write out the chars in cmd to a serial port for an input of ASCII text representing byte values.

void SendCTRL (String &input)
{
  //Adjust Data
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }

  //Send Data
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

As the majority of the byte values fed are constant, I'm trying to create similar output for the following code when I feed the function below only the byte values that change frequently:

void Create_Message(int Address, int Data)
{
  //Adjust Data
  Address--;
  byte SvAdd = 1;
  byte FuCode = 6;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
  unsigned int crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
  byte CrcHi = crc & 0xFF;
  byte CrcLo = crc >> 8;
  /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
  * to
  *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
  */

  //Send Data
  unsigned char cmd[9]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo};
  cmd[8]=0; //Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  lcd.setCursor(0, 1);
  for (int i=0; i< sizeof(cmd)/sizeof(cmd[0]); i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

I'm reading the Values written by RS485.write() and, in both cases, the data is good. However, for the 2nd section of code, the Arduino seems to write out the null-byte while it does not write the byte out in the 1st block. If I remove the allocation for the null-byte in the second code, it does not get a response from my device.

I'm guessing that the issue is that I am not setting my null-byte terminator correctly or otherwise missing something (I'm pretty new here XD )

Update: it seems like using sizeof(cmd)/sizeof(cmd[0]) to determine the send length interfered with data transmission when I set this to a constant the code works just fine.

In the second code example, the value of sizeof(cmd)/sizeof(cmd[0]) is 9, due to the declaration unsigned char cmd[9] ...

Thus, the for loop will write out 9 bytes, with indices 0, 1, ... 8.  Due to cmd[8]=0; earlier in the code, the last byte will be zero.  To prevent that, one might instead use the expression  sizeof(cmd)/sizeof(cmd[0])-1 in the for loop:

for (int i=0; i< sizeof(cmd)/sizeof(cmd[0])-1; i++)
   RS485Serial.write(cmd[i]);

Note, this doesn't explain why it should be so that “If I remove the allocation for the null-byte in the second code, it does not get a response from my device”, although practically anything can happen if you say cmd[8]=0; after allocating only 8 bytes of storage.


Arduino with 8 LEDs and a switch I have an assignment wherein we have 8 LEDs connected to an Arduino Uno which has a switch. These LEDs light up according to the johnson counter but every time I turn the switch off it should reset back to the start. An example is if I turned the switch off while the pin is at 8 going back to 1 , then when i turn it on it should be back to 1 again. I got the 1 to 8 reset part right but the 8 to 1, I'm having trouble solving.

Here is my code:

int pin;
int sw3 = 10;

void setup() {
  // put your setup code here, to run once:
  for (pin = 2; pin <= 9; pin++) {
    pinMode(pin, OUTPUT);
  }
  pinMode(sw3, INPUT);
}

void loop() {
  pin == 2;
  if (digitalRead(sw3) == HIGH) {
    for (pin = 2; pin <= 9; pin++) {
      digitalWrite(pin, HIGH);
      delay(200);
    }
  }
  else {
    digitalWrite(pin, LOW);
  }

  delay(200);

  for (pin = 2; pin <= 9; pin++)
  {
    digitalWrite(pin, LOW);
  }
  delay(200);

  if (digitalRead(sw3) == HIGH) {
    for (pin = 9; pin >= 2; pin--) {
      digitalWrite(pin, HIGH);
      delay(200);
    }
  }
  else {

    digitalWrite(pin, LOW);
  }

  delay(200);

  for (pin = 9; pin >= 2; pin--) {
    digitalWrite(pin, LOW);
  }
  delay(200);
  {
    if (digitalRead(sw3) == LOW) {
      digitalWrite(pin, LOW);
    }
    else {
      digitalWrite(pin, LOW);
    }
  }
}

Some fixes:

pin==2;  should only be 1 = here. == is a comparison.

pinMode(sw3,INPUT);  make this INPUT_PULLUP, to turn on the internal pullup resistor

if(digitalRead(sw3)==HIGH){  change this to LOW, and wire your switch/button to connect the pin to GND when pressed. The internal pullup will unsure the pin is HIGH when not pressed, and the button/switch makes it LOW when pressed. The pin is thus not allowed to 'float' and return a random HIGH or LOW.


Accelerometer Orientation (LIS3DH) Newbie here!
I’m trying to make a pocket level using an LIS3DH but I don’t know how to “reset” all the axis to start reading from a certain orientation since my LIS3dh won’t be mounted flat and will change often.
Ideally whenever the level starts it would start reading everything at 0 no matter the orientation.
I’m sure it’s just math, but it’s way over my head to begin to understand it.
Starting with the absolute basics I’m using the adafruit lib. I can easily get all the readings, and I understand they are acceleration forces. But how do I start them all from 0?
Initially I was thinking to take the very first reading and store it, then add or subtract the new readings from the originals based on if the new numbers are higher or lower than original (subjectively) but that only works in some instances which means that it wasn’t a good solution.
I don’t have specific code to share as I’m using the adafruit LIS3DH example.
Here’s a reading from the sensor of it not flat
X: -11408 Y: -3152 Z: 10560 X: -6.87 Y: -1.87 Z: 6.27 m/s^2
And here’s readings closer to a flat surface
X: -80 Y: 704 Z: 16176 X: -0.02 Y: 0.46 Z: 9.86 m/s^2

Consider taking on this project in sever steps.  Some you might do now and other later if necessary
First, accelerometers do not usually need alignment.  But if accuracy and reproducibility is important, a project may benefit from finding any offset a single accelerometer may need and finding any magnitude adjustments between the three accelerometers.  Using gravity rotate each accelerometer through their maximum negative and positive values.  Use these values to find an offset such that the absolute values are equal for each individual accelerometer.  Then select one accelerometer as the bases and find the appropriate coefficients to normalize the other two accelerometers such that the absolute values of all maximums and minimum are equal.  As hinted, this is one of the step you can skip until later if necessary.  If you need a more thorough explanation you can find it in section 2 of this STMicro document.
To find angles it would be best to consider the classic airplane example where pitch (nose up or down) and roll (rotation around the axis passing through the nose and tail).  Here is a good submersible Arduino project to consider. In this project the accelerometer Z axis is pointed down and the X to the side.  To find ROLL the author calculates the inverse tangent of the negative of the ratio of acceleration in the X direction over the acceleration in the Z direction.

The pitch calculation is a bit more involved.  This can be found by taking the inverse tangent of the acceleration in the Y direction over the square root of the sum of the square of the X plus Y acceleration.

That out of the way, now consider how to zero the angles out.  First decide on if you will adjust the roll or the pitch.  Let's consider the roll case.  Record the current roll angle and subtract it from the current calculated roll angle before displaying it as zero.  Now rotate your accelerometer such that you do it around the Y axis (remember, we are only considering the roll case and do not want to change the Y accelerometer's reading!).  If you have done the math correctly, the displayed angle will be the difference between when you started and finished your rotation.
All that out of the way, now consider what would happen if you rotated your accelerometer through a roll position where the acceleration in the Z direction falls to zero.  Your trigonometric inverse tangent function for roll would go to infinity!  In the physical world, where gimbals are used for air and space navigation, this is referred to as Gimbal lock!
What to do about Gimbal lock?!  Well, it's a story that starts in 1843 (yeah, that does sound odd doesn't it WRT air and space navigation).  In short, if you stop using classical trigonometry to convert acceleration to angle an start using Quaternions you avoid Gimbal lock entirely.  Quaternions use complex numbers to describe rotation in 3D space.  People who write 3D gaming programs absolutely love how Quaternions simplify their efforts.  This is another of those steps you don't have to do.  But doing so will make your project all the more robust.
(BTW, this is the STMicro LIS3DH data sheet.)


why of 2 identical micro-controllers, only one can connect to a given device? I am working with 2 identical (Arduino) Adafruit Feather M0 Bluefruit LEs. Only one of them can connect to a Universal Windows Platform app running on a  Windows 10 machine. The other connection fails with Unreachable status.

I am only trying to connect with one MCU at one time. Both MCUs are loaded with the same program which resets the Bluetooth Unit. Both MCUs can connect to an Android app. Neither board appear damaged.

Why could a UWP app be able to connect to one board but not another?

Other than a software issue, there is no reason it shouldn't work. Only thing may be identical Bluetooth names or ids. Clear the device from windows and try again.

I have some cheap Bluetooth obd 2 readers that all use the same Bluetooth mac address and name. I have to delete one from my android phone before adding the new one to connect to it.


Arduino LED backlight - should PWM be used with transistor or capacitor? I have implemented a PWM controlled LED backlight for the LCD in my Arduino Uno design. One LCD backlight pin is connected to +5V, the second to the ground via 220 Ohm resistor and MOSFET controlled from a PWM capable D9 pin.

Everything seems to work fine, I do not see any oscillation, but after some reading about PWM I am not sure if I perhaps should connect a 100 uF capacitor to smooth the voltage?

Is the MOSFET even necessary? It seems backlight is drawing about 5 mA - can I perhaps drive it directly from the D9 pin, using the resistor? (It seems another user in Do I need to use a resistor if I am using a potentiometer to control an LED's brightness? is controlling brightness without any of those.)

You don't need the MOSFET, you don't need the capacitor, you do need the resistor.

The pins on your Arduino can deliver up to 20mA comfortably, so in this case there is no need for the MOSFET. However, if you were to replace your backlight with a high power LED, your current setup will work just fine.

Without a capacitor, your PWM is a nice square wave. The cap will, depending on its capacity and the resistor in your circuit, turn that into a more rounded waveform, or very ripply DC. Whichever is the case, it will not benefit the (dimming of) your LED. With some bad luck it will even introduce flickering instead of preventing it!

The reason why you should still use the resistor is to prevent the LED from drawing too much current. Without it, it's simply a game between the LED and the Arduino pin to see who will burn first. Whoever wins, you'll end up with a destroyed backlight or fried Arduino. Adding a component costing a few cents can prevent that.


Comparing orientation data obtained using gyroscope and accelerometer Recently, I have been playing around with a gyroscope and accelerometer in the hopes of building a quadcopter. I have plotted some of the data the two sensors and I am noticing that the pitch from the accelerator lags significantly behind the gyroscopic pitch.

From some research, I understand that these two are not going to equivalent values due to the mechanisms of measurement, however is it common to have such large discrepancies (i.e a difference of 20 degrees or higher) between the two sensors or is this an issue with my conversion?

I have listed the graph and source code here. Any help would be appreciated!

Sincerely,
Anand

Normally the values from gyroscope will drift overtime. It is natural and depends on the parameters of your code. It could drift a few degrees per seconds and the data will be far way from the accelerometer in a few seconds.

I have seen that you have applied the complementary filter, so you don't need to worry about the single value from the gyros since you combine them with the acceleromter and everything seems fine.

The gyros are good for short time response, in long time response the values get pretty bad as they drift a lot.

On the other hand, accelerometers are good for long time response, since short time response is noisy because of gravitational influence.

That's why you need a filter to combine them.

Wrapping up, it is normal to have this behavior in gyros. If you want to know more about the effect behind this sensor, try this reading.


More missed messages with longer cables with nRF24L01+? I am using nRF24L01+ 2.4 GHz transceiver.

When I connect them directly (with SPI pins 10..13 from Arduino) to the adapter board for the nRF24L01 I get occasionally errors (meaning the receiver does not get the sent message).

However, I want to use one nRF24L01 purely for transmitting, and one for receiving. So each Arduino will have 2 nRFs, one for receiving, one for transmitting.

Since they both use SPI, I need to take the pins 10..13 to a breadboard and forward them from there to both nRFs. However, I did a test with only the transmitter, and found out I get more errors than direct wiring.

The only difference is that I now use extra jumper wires (4" / 10 cm). Can the extra cable length cause problems?
Would it help if I use less long M/F dupont cables? (so the total length still is 8"/20cm)? ... I don't have such short ones, so I cannot try.

I use for the breadboard to the nRFs 8"/20cm M/F dupont cables.

See picture below. The white/grey/red/blue 20cm/8" dupont cable directly wired to pins 10..13 Arduino gives less errors than the situation on the photo where the white/orange/red/blue 4"/10cm cables are added.

the Antenna is interfering with the signals because of its proximity to the point on the bread board where you are connecting the wires, as Majenko said.

If you rotate the nRF24L01 board 180 degrees you will increase the distance between the wires and the antenna and this will reduce the interference, but because of the way radio waves propagate there is also a chance that it may make it worse.  The radio wave propagate from the antenna in a share particular to the antenna.  I don't know what shape this antenna puts out, I'd expect it to be omnidirectional (all ways) because of its purpose.  However all directions are not equal because of reflections, the shape of the antenna, defects in the shape of the antenna, etc and if the pattern of the propagation can be mapped you can identify the make of board and if the mapping is accurate enough even the instance of the board itself.

So, to cure interference:

Increase the distance this reduces the power of the interference by the square of the distance.
Change the orientation, usually by something other than 90 or 180 degrees.
Shield the wires.

In short move the antenna further away from the wires, can you use MF DuPont wires to remove the radio from the breadboard all together.  The fact it won't sit still and is sliding all over you desk will probably help with reflections.


Why is the output on the MOSI line shifted 1 bit over from what I commanded? I've been trying to work with an AD5685R DAC. Per that datasheet, to get DAC1 to output max voltage (5V), I would perform:

SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE3); // DAC uses CPHA=1, CPOL=1

digitalWrite(CS, LOW);
SPI.transfer(0x31); // upper nibble sends a "write and update" command, lower nibble says "DAC1"
SPI.transfer(0xFF);
SPI.transfer(0xFC); // 14-bit DAC, last 2 bits are dontcares, make them 0
digitalWrite(CS, HIGH);

Replace 0xFFFC with 0x0000 to get 0 volts out.

Sending this command as written somehow writes to DAC4 instead of DAC1! and while 5V will come out when I write 0xFFFC, I get to 2.5V when writing 0x0000 instead of 0V.

If I command this with a Bus Pirate and directly write the bytes out, it works exactly as desired.

I used the Bus Pirate to sniff the SPI traffic and it turns out I'm not getting what I've commanded. Rather than 0x31 0x00 0x00 for instance, I get 0x18 0x80 0x00.

If we break this out into bits:

0x310000: 0011 0001 0000 0000 0000 0000 // commanded
0x188000: 0001 1000 1000 0000 0000 0000 // actually sent

So the command actually sent out is shifted by 1 bit!

Here's the bit pattern for 16383 counts (i.e., 2^14-1):

0x31FFFC: 0011 0001 1111 1111 1111 1100 // commanded
0x18FFFE: 0001 1000 1111 1111 1111 1110 // actually sent

The opcode corresponding to 0x18 is "write to input register 4" (the output occurs because I've pulled the /LDAC pin permanently low, see the datasheet), which explains why I'm getting an output on DAC4 instead of DAC1.

This occurs with both a Sparkfun Pro Micro and an Arduino Mega 2560.

What is going on here? Why is the Arduino not sending out what I've actually commanded? Again, writing the hex codes directly to the DAC using a Bus Pirate works perfectly.

CPOL is clock polarity, and CPHA is clock phase.

The SPI modes are:

Mode 0 (the default) - clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)

Mode 1 - clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)

Mode 2 - clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)

Mode 3 - clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)

According to your datasheet:

  Data from the SDIN line is clocked into the 24-bit input shift register on the falling edge of SCLK.

Judging by the diagrams on the datasheet, Mode 1 is what you want. You want the trailing edge of high to low.

More information at SPI - Serial Peripheral Interface - for Arduino


Why can't my bluetooth receive serial data from my android phone, but can send serial data from my bluetooth to my android phone? I can receive serial data from my phone but I can't send serial data to the arduino using bluetooth. I can see my input from serial monitor to my Android but not the other way. I'm using ARF7044A bluetooth module if that matters. Any help would be appreciated please.

Arduino to Android: Working
Android to Arduino: Not working.

Here is the wiring:

Here is the code:

char state;
void setup()
{
pinMode(8, OUTPUT);
Serial.begin(9600);
}

void loop()
{

  if(Serial.available())
  {
    state = Serial.read();
    Serial.println(state);
  }
  if (state == 'a')
  {
    digitalWrite(8, HIGH);
  }
  else if(state == 'b')
  {
    digitalWrite(8,LOW);
  }
}

Your erroneous level shifting attempt from Bluetooth TX to Arduino RX is the root of your problem.

Pins 0 and 1 are also connected to the on-board USB interface chip via a pair of 1kΩ resistors. These resistors serve two purposes:

To "weaken" the drive of the USB chip's UART interface (actually only needed on the USB chip's TX -> Arduino RX connection), and
To protect both the USB chip and the main MCU from damage should two connected pins be set to opposing levels, which would cause high currents to flow through both output drivers.

The TX pin of the USB chip is actively driven HIGH all the time when idle (stupid design by Arduino, it should be Hi-Z when the port is not open), and the RX pin is pulled up by the internal pullup resistor in the USB chip.  Further, when the Arduino's Serial is in use the TX pin of the Arduino is actively driven HIGH when idle (or LOW when transmitting a "1" bit).

The actual circuit you have looks more like this:

simulate this circuit – Schematic created using CircuitLab

Transmitting from the Arduino to the BT module is straight forward enough - the "high" point of the circuit is the Arduno's TX pin at 5V when idle.  Current flows through R2 to the USB RX pin, and through R5 to the BT RX pin, with a portion split off to ground, which is what you want for your level shifting.

Communication in the other direction, however, is different, because you have two balanced "high" points in your circuit - one at the USB TX and one at the Bluetooth TX - and the fact you have 1kΩ resistors in both branches means that neither transmitter is "stronger" than the other. This means that when the BT TX is LOW (0V) you have around 2.5V at the Arduino RX pin (5V over two 1kΩ resistors = 2.5V in the center tap - see here).

Since 2.5V is neither within the Arduino's HIGH nor LOW voltage ranges (which are more than 3.5V for HIGH and less than 1.5V for LOW when running from 5V) the input is completely ignored.

The 3.3V transmitted by the Bluetooth module is a little under the official threshold for a HIGH signal on an Arduino, but in practice, it usually is detected fine. So remove the resistor network from the Bluetooth's TX pin and connect it directly to the Arduino. Since the input threshold voltage is a function of the supply voltage (0.7 * Vcc) it depends very much on your power supply as to whether it will work reliably or not. If you find it doesn't, you should use some upward level shifting.  There are simple MOSFET based bi-directional level shifters available cheaply that are a better solution than resistors, and will allow proper operation in both directions, shifting a high voltage to a low one and a low voltage to a high one. These are good for lower frequency communications such as UART. If you should need higher frequency, or you find a simple MOSFET based shifter isn't working for you then a 74HCT08 or similar chip (be sure to use the HCT range not the HC range) or a dedicated level shifting chip may be in order.


Which one is IR led? I've ever been so confused in my life. I'm new to Arduino and electronics but I just can't figure it out which diode is IR transmitter/receiver or even if it is IR. I know that IR is not visible to human eye but I'm really clueless and I need help distinguishing them. I think the black one is a receiver but when I connect the white/transparent one it lights up so I guess It's not IR diode, right? How do I test them to see it anyways?

If you connect one of these and you can see it light up with your naked eye then it is not an IR LED, it's a visible-light LED. It's also not an IR sensor.

If you want to see IR, point a digital camera (like in your phone) at it and apply power. The sensors in digital cameras almost always detect some IR, so you can see a faint light on the screen. To test this, point your phone at a TV remote and press the button. If you see a flashing light in your phone's screen, you know it can "see" IR (Most digital cameras have an IR filter to get rid of most of the IR going into the camera, but they generally allow enough IR through that if you point them directly at an IR LED you can usually see it, at least faintly.)

Note that you should be able to use a visible light LED as a light source for an IR photoresistor/photodiode/phototransistor, since visible light LEDs will also give off some IR. However, an IR LED will put out a WHOLE LOT more IR than a visible light LED at of the same power.

The black one is probably an IR receiver. The color of the lens probably blocks visible light but not IR.

All the IR LEDs I've seen have looked clear, but I could not see any visible light when I powered them up.


Building an AtMega328p from Transistors I'm a little new to circuitry, and the Arduino in itself!

From what I know, I think that it might be possible to actually build one (the processor itself, of course) from transistors. This isn't a practical question, of course, but it would be an excellent learning opportunity.

Would it be actually possible to go through with such a project (Even without EEPROM)?

If so, how would it be completed?

Thank you!

Yes, it is possible - after all, the Arduino is essentially just a bunch of incredibly tiny transistors. Early computers, before ICs were invented, were built from transistors. Before that it was valves. Before that it was relays. All just, at the end of the day, switches.

Would it be a practical project? Not really, although someone has done it (not for the AVR CPU, but the concept is the same): http://www.megaprocessor.com/

How would you start? Well, first off you'd create the basic building blocks of a CPU, which is logic gates. There are two basic ones that can be combined together to make any other gate: the NAND gate and the NOR gate. You'd pick one of those and put lots of them together to make the basic sections of the CPU. Then those blocks connect together to form the CPU. More logic gates go together to make the IO functionality, memory, interfaces, etc.

Basically:

Transistors combine to make NAND gates (or NOR gates if you prefer that form)
NAND (or NOR) gates combine to make complex gates.
Complex gates combine to make logic functions
Logic functions combine to make logic blocks (like the ALU)
Logic blocks combine to make the CPU


Networking multiple Arduino Megas and updating their programs from one master Is it possible to link multiple Arduino Megas using RS485, for example, and update the program on client Megas from one master Mega, as well as for them to communicate with each other? Whilst I found multiple examples of networks, nothing comes up for programming the boards other than through a PC

Thanks for any pointers!

In principle, yes, you can do it. It's what existing bootloaders do -- they take code over the serial port, or USB, load it to flash, and then branch to it. Not to mention OTA.

So yes, you can modify the bootloader to use different pins, talk rs485, come up with code-integrity checks, specify particular bit patterns to signal "reboot" or "now load new code", and so on. If you have enough flash, you can even keep two copies, a working and a new, like most OTA code does.

I am not aware of a ready-made library that does that. If I wanted to roll my own, I would start by studying the OTA code.


Segmentation fault and huge SRAM need for Serial.println I have written my own 'assert' since I want to use it for both Windows and Arduino. The class is called from many files (about 10).

AssertUtils.h:

#pragma once

#define assert(expr) AssertUtils::Assert2((expr), (__func__), (__FILE__), (__LINE__));

class AssertUtils
{
public:
    static void Assert2(bool expression, const char* funcName, const char* fileName, int line);
};

AssertUtils.cpp:

#include "AssertUtils.h"
#include "Arduino.h"

/* static */ void AssertUtils::Assert2(bool expression, const char* funcName, const char* fileName, int line)
{
    if (!expression)
    {
        Serial.println(funcName);
        Serial.println(fileName);
        Serial.println(line, DEC);
        Serial.flush();

        // Abort program execution.
        abort();
    }
}

When I compile this, the SRAM usage is 1469 bytes (together with the rest of my sketch and classes).

When I comment the line below, I get a segmentation fault in a random assert call (when I comment out that call, I get it in the next, etc.).

    //Serial.println(funcName);

When I also comment out the second print statement, the compiler reports only 1137 bytes SRAM usage (which I expect since this was about equal until before I added the Assert class).

    //Serial.println(funcName);
    //Serial.println(fileName);

Questions:

How can I get rid of the segmentation fault?
How can it be that about 332 bytes are used for one two additional print statements? (maybe related to the const char* buffering (?)

Note, this answer is not MY answer, but approximately the combination of the first 5 comments from my original question.

What I did was:

(Juraj) Changed the compiler version to 6.21
(juraj) Added an F in F(__FILE__)
(KIIV) Removed func; this did not work with the F flash helper, but I can find back the code anyway unambiguously because of the file name + line number.
(Majenko) I removed the class and use a macro. This costs some more Flash memory (depending on the number of asserts I use, but I'm still around 40% (was 35%).

The SRAM usage is now 1125 bytes, even less than where I'm started with.

The resulting code is below:

#define assert(expression) \
  if (!(expression)) \
  { \
    Serial.println(F(__FILE__)); \
    Serial.println(__LINE__, DEC); \
    Serial.flush(); \
    abort(); \
  }


How to use a DC buck converter to regulate Uno R3 input voltage? I have had a rough time trying to understand why this isn't working correctly. Quick background: I set up a system to pop open car doors using touch sensors. I heard that powering the Arduino Uno R3 straight off the car battery is not a good idea, so I bought a buck converter. I wired it up and calibrated the output on the converter for 5V. When I hooked it up to the Arduino (via the barrel jack), I experienced some odd effects. The output pins and the 5v power pins were only getting 3.5V.  I had to adjust the buck converter up to about over 7V in order to get 5v on the Uno.

Then the sensors started acting oddly. Auto triggering and alternately not working. Anyone know what I am doing wrong?

Converter I bought:  https://www.amazon.com/gp/product/B0159W0UL2/ref=oh_aui_detailpage_o07_s00?ie=UTF8&psc=1

The barrel jack needs 9-12 V, the internal voltage regulator of the Arduino will reduce this to 5 V.

Since you only supply 5 V, there is a loss in the internal voltage regulator why you probably get only 3.5 V.

And after applying 7 V, probably some (sub) system gets less than the necessary voltage, or there are occasional 'downspikes' lower than 5 V.

The default adapter that you use for supplying voltage to the Uno, also is 9V-12V. Also, check the polarity.

See the following link for more info:

What adapter


Can I use notepad++ for writing sketches? Before I install the Arduino IDE, I was just wondering whether I could just use notepad++ to write the files and move them into correct location. I assume notepad++ doesn't support Arduino code, but I suspect there will be a mod for it, even though sketches are a low-end version of C++, which is supported.

You can easily use notepad++ or any text editor to edit arduino code files (.pde or .ino). I use the sublime text editor for all my arduino coding.

As you noted, the arduino syntax is c++, so setting the syntax highlighting mode to c++ is all that you need to do; no mod should be necessary.

Arduino includes a "Use external editor" option in the preferences menu that will make it reload the file every time you compile or upload. It also disables editing in the editor window. In this mode, just save your file in any editor, change to the arduino window, and hit upload.

Since 1.5, arduino has had command line support. most editors allow making the "build" button execute arbitrary commands in the current directory. by setting build to run "arduino --verify" or "arduino --upload" you can code in any editor you want even without having an arduino window open.


Is it possible to have two serialEvent() in Arduino code? I am developing a code on Arduino and need to implement a condition that if data is available form "serial2" then only get the input for "Serial" terminal of Arduino.

I have tried with below code, but its behavior is when I am sending something from "serial" terminal of arduino, control goes into the loop "serialEvent()" otherwise even if I am sending the data over "serial2" it is not entering in that loop.

Below is my code snippet:

void serialEvent()
{
  int DATAaddressMSb, DATAaddressLSb;
  digitalWrite(DIR485, LOW);
  delay(100);
  delay(10);
  while (Serial2.available()>0)
  {
    Serial.println("serial2 data available");
    int i = 0;
    int bufferIn1[9] = { int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00) };
    bufferIn1[i] = Serial2.read();
    Serial.print(bufferIn1[i], DEC);
    Serial.print(" ");
    if(i == 0){Serial.print("BUFFER VAL 0");
    Serial.print( bufferIn1[i], DEC);}
    if(i == 1){Serial.print("BUFFER VAL 1");
    Serial.print( bufferIn1[i], DEC);}
    if(i == 2){Serial.print("BUFFER VAL 2");
    Serial.print( bufferIn1[i], DEC);}
    i++;
  }

  while (Serial.available()&& pos < sizeof my_str - 1) {
    char c = Serial.read();
    if (c == '\n') {            // \n means "end of message"
            my_str[pos] = '\0';     // terminate the buffer
            pos = 0;                // reset to start of buffer
            String str((char*)my_str);    // converte char array in string
            if (str == "PCB-CODE") { Serial.println(SN_CODE); }
            if (str == "FW-VERSION") { Serial.println(FW_ver); }
            if (str == "STOP" ) { TESTcode = 0; IDcode = 999; }
            if (str == "TEST1") { TESTcode = 1; delay(6000); Serial.println("Enter ID "); }
            if (str == "TEST2") { Serial.println("Initialising Board ");  delay(6000); TESTcode = 2; }           // For all tests

            if (str == "ID0") { IDcode = 999; }
            if (str == "ID1") { delay(60); IDcode = 1; }       // Test for FW version
            if (str == "ID2") { IDcode = 2; }       // Test for 3.3V
            if (str == "ID3") { IDcode = 3; }       // Test for Main power
            if (str == "ID4") { delay(50); IDcode = 4; }       // Test for +15V
            if (str == "ID5") { IDcode = 5; }       // Test for +10V
            if (str == "ID6") { IDcode = 6; }       // Test for +8V
            if (str == "ID7") { IDcode = 7; }       // Test for +5.5V
            if (str == "ID8") { IDcode = 8; }       // Test for +1.2V
            if (str == "ID9") { IDcode = 9; }       // Test for +2.5V
            if (str == "ID10") { IDcode = 10; }     // Test for -15V
            if (str == "ID11") { IDcode = 11; }     // Test for POW_LIGHT
            if (str == "ID12") { IDcode = 12; }     // Test for +s_stab
            if (str == "ID13") {delay(50); IDcode = 13; }     // Test for +CELLA
            if (str == "ID14") { IDcode = 14; }     // Test for FPGA_GPIO
            if (str == "ID15") { IDcode = 15; }     // Test for DAC_OUT
            if (str == "ID16") { IDcode = 16; }     // Test for CURRENT_LOOP
            if (str == "ID17") {delay(50); IDcode = 17; }     // Test for Torque signal
            if (str == "ID18") { IDcode = 18; }     // Test for EXT_TRIGGER
            if (str == "ID19") { IDcode = 19; }     // Test for Encoder
            if (str == "ID20") { IDcode = 20; }     // Test for RAM
            if (str == "ID21") { IDcode = 21; }     // Test for SD Card
            if (str == "ID22") { IDcode = 22; }     // Test for Ethernet
            if (str == "ID23") { IDcode = 23; }     // Test for CAN
            if (str == "ID24") { IDcode = 24; }     // Test for I2C
     for( int i = 0; i < sizeof(my_str);  ++i )    // resetta la stringa ricevuta         // reset the received string
          my_str[i] = (char)0;
        }
        else {my_str[pos++] = c;}
  }
 }

Please guide. Thank you........

According to https://www.arduino.cc/en/Reference/SerialEvent

Arduino Mega handles:

void serialEvent1(){
//statements
}

void serialEvent2(){
//statements
}

void serialEvent3(){
//statements
}

Every other Arduino has only single:

void serialEvent(){
//statements
}


Send packet of multiple sensors data to Bluetooth module In my project I am using 3 sensors. I am sending a regular stream of sensors data to Bluetooth module  but now I want to send data in form of packet (which may be 30 bytes or 40 bytes of size) in which first 10 bytes contain the first sensor data while next 10 bytes contain second sensor data and so on. But problem here is I am not finding something relevant to my approach. Can any one suggest me some link or some way to do this.
Thanks in advance.

There are many ways to transmit binary data over a byte-stream based interface like Serial (which is used by common bluetooth modules like the HC-05/HC-06). I will only describe one here.
First we need to define a start byte, which marks the start of a new packet. That can be any arbitrary value, for example 0xFF. It is also possible to use a specific byte sequence as start marker. This start byte/sequence is what we send first when transmitting a packet.
Then we want to transmit the size of the following data. With small to normal packet sizes a single byte is enough here (giving room for up to 255 bytes).
Sometimes you might want to compute a CRC hash value to check for data corruption. That could also be send here. But unless you have a system, which really is loosing/corrupting data, you don't need it. I suggest you first try it without and check, if corrupted data is really a thing for your setup.
And then we are sending the actual data. How exactly you are doing this depends on how the data is stored in your code. Though you will use Serial.write() in some way. If you want a more specific answer in this regard, you need to include your code, so that we can see how you are storing your sensor data.
On the receiving side you would then wait for the start marker, read the size byte and then read bytes until you have received as many, as the size byte said. As you have multiple sensors, you could send the sensor data of each sensor in it's own packet. The data could then be formatted like: 1 byte sensor ID, X byte sensor data.


HC-06 Bluetooth Module on Arduino Nano I'm working on a project where I need to have Bluetooth capability on my Arduino Nano to send data from a sensor over to the computer. Unfortunately, I'm having a difficult time figuring out how to establish a connection from the HC-06 to the computer.

I've hooked up the HC-06 to my Arduino in a fashion similar to the picture shown below.

I've also been testing it with various code that I've found online that deal with tutorials on the HC-06.  The current code I'm working with is below.

#include <SoftwareSerial.h>
SoftwareSerial BT(1, 0);

void setup()
{
  // set digital pin to control as an output
  pinMode(13, OUTPUT);
  // set the data rate for the SoftwareSerial port
  BT.begin(9600);
  // Send test message to other device
  BT.println("Hello from Arduino");
}
char a; // stores incoming character from other device
void loop()
{
  if (BT.available())
  // if text arrived in from BT serial...
  {
    a=(BT.read());
    if (a=='1')
    {
      digitalWrite(13, HIGH);
      BT.println("LED on");
    }
    if (a=='2')
    {
      digitalWrite(13, LOW);
      BT.println("LED off");
    }
    if (a=='?')
    {
      BT.println("Send '1' to turn LED on");
      BT.println("Send '2' to turn LED on");
    }
    // you can add more "if" statements with other characters to add more commands
  }
}

When I search for a connection on my computer, it finds the HC-06 and I can then attempt to establish a connection.  I enter the pairing code of 1234.  It then says that a connection has been established so I go into the Bluetooth Services tab where it tells me what COM port to use (either COM7 or COM4 depending on which computer I try it on.  I've tried this on two separate computers.)

So, I open a PuTTY session and attempt to connect to the indicated COM port.  About 50% of the time, it says that a connection could not be established to the indicated COM port.  The other 50% of the time, I am able to open a PuTTY session but then nothing happens.  The green LED on the HC-06 continues to blink away no matter what I try to do.

Any help would be VERY appreciated as I feel like I've tried everything I can think of.

Thank you!

I agree with TisteAndii's comment. Your voltage divider is in the wrong place. You are dividing down the 3.3V signal from the HC-06 to be a maximum of 2.269 volts. However the Nano requires at least 3.5V to be considered HIGH.

Plus, you are putting 5V from the Nano into the HC-06 which may damage it.


samd21 linking, change the base addresse from the default I'm working on creating a safe firmware upgrade for my adafruit feather m0.
I understand from my CTO that wrote the previous upgrade that for either samd21 or all arm m0 (not sure which) the compiler compiles non relative addresses, meaning bx 0x3000 will jump to address 0x3000 and not 0x3000 bytes from my location.
My goal is to split the flash into 4 banks:

bootloader (2k)
user data
firmware #1
firmware #2
which firmware will be booted is up to a flag in the flash do decide.
i understand from my predecessor this is an issue since firmware#2 when loaded to ram might not run.
I disagree and do believe simple changes in the .ld script should accomplish the task.

My only question to  you guys is changing the .ld script .text address is enough ? i know the bootloader jumps to an address that was defined in the  .ld script if it's not 0xFFFFFF (if the flash was written to).
do i ned to change the .ld script to include two .text sections ? do i need to also define how they reside in the RAM as well ?
any examples ? hint ?

Thanks.

A typical LD script consists of two sections - one that defines memory ("MEMORY") regions, and another that defines what to put in those memory regions ("SECTIONS").

To carve holes in an existing memory layout it is usually enough to just change the first section - the part that defines the layout of the memoy. Shrink and move existing blocks of memory and insert new ones.

For example you may have this at the moment:

MEMORY
{
  FLASH (rx) : ORIGIN = 0x00000000+0x2000, LENGTH = 0x00040000-0x2000 /* First 8KB used by bootloader */
  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

There is a hole already defined of size 0x2000 at the start of flash, and the sketch is loaded from 0x2000 onwards.

You may want to shrink and move that, and add a "user data" chunk. It's enough to just go:

MEMORY
{
  USERDATA (rx) : ORIGIN = 0x2000, LENGTH = 0x1000
  FLASH (rx) : ORIGIN = 0x3000, LENGTH = 0x00040000-0x3000
  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

(I collapsed some of the maths cus it's pointless).  Now the flash area (where the sketch goes) has been shrunk by 0x1000 and moved an extra 0x1000 up the memory map. A USERDATA chunk has been inserted which you can then use later on if you so wish.

To make things get put in there by the linker script (you don't need to change anything else to move the sketch data...) you can define a new section in the later part of the linker script:

.userdata :
{
    KEEP(*(.userdata))
    KEEP(*(.userdata.*))
} > USERDATA

That should then place anything that you put in a .userdata section (or a subsection within that) within your sketch into the USERDATA chunk of flash - separate from your sketch.

(sketch)
const uint8_t __attribute__((section(".userdata"), used)) data[] = { 10, 100, 123, 177, 221, 49 };

However, if you plan to use it like EEPROM and only write to it using code in your sketch then you don't need to worry about anything like that - just carve out the hole.  You can also provide some globals to help with your code, though:

(linker script)
PROVIDE(userdata_start = ORIGIN(USERDATA))
PROVIDE(userdata_length = LENGTH(USERDATA))

Then you can use those in your program to know where the USERDATA chunk is and how big it is (ideal if you ever choose to change it - no need to change your code, only the linker script).


Arduino Nano - Unknown USB device I just bought an Arduino Nano v3.0 (compatible? +- 5$) and I cannot connect it to my computer (Windows 8.1 64bit, Arduino IDE 1.6.8 installed).

The Arduino was bought as a clone but shows GRAVITECH.US on the front.
It has a FTDI FT232RL chip (1412-G B8908572) on the back.

When connecting the Arduino the power leds burns the TX and RX led flash a few times (really shortly) and then die. Then the yellow L leds blinks once per second continiously.(power to the Arduino comes from the USB cable, not from external power)

In the system tray I get a message saying

"The last USB device you connected to this computer malfunctioned,
and Windows does not recognize it."

In the device manager I get a node under Universal Serial Bus Controllers:

Unknown USB Device (Device Descriptor Request Failed).

When examining the properties of the device, the device-status is:

Windows has stopped this device because it has reported problems. (Code 43)
A request for the USB device descriptor failed.

I tried to reset the device
I tried different USB cables
I used another Windows 8.1 PC without Arduino IDE installed
I used an old XP computer

All give same error.

I read about the bricking of clones by the recent FTDI drivers...
I downloaded the FT_Prog tool V3.0.60 to check the PID, but the tool simply does not find the Arduino...

I'm out of ideas... does anyone have some left?

Thanks in advance!

Michiel

I found the issue!
There is a bug in the Arduino hardware:
https://ketturi.kapsi.fi/2014/04/how-to-fix-moody-arduino-nano/

You need to bridge pins 25 and 26 of the FTDI chip (located at the back of the Arduino) to ground the pin 26 TEST signal.
If I connect these pins then it works just fine!


Burning bootloader and uploading sketch on ATMEGA328 I have a ATMEGA328-PU (not a atmega328P-PU) and managed to install the boot loader on it using an Uno as ISP, but now i can not upload any sketch, this are the steps I've done so far:

connected this pins:

reset to pin10

11 to 11

12 to 12

13 to 13

and 5V to 5V and ground to ground.

uploaded ArduinoISP from examples and then changed the programmer to Arduino as ISP.

Then i changed this line in avrdude.conf:

part parent "m328"
    id          = "m328p";
    desc        = "ATmega328P";
    signature       = 0x1e 0x95 0x0F;

    ocdrev              = 1;
;

to:

part parent "m328"
    id          = "m328p";
    desc        = "ATmega328P";
    signature       = 0x1e 0x95 0x14;

    ocdrev              = 1;
;

selected burn bootloader and uploaded the boot loader with success.

and then i removed pin 10 to 13 and connected reset to reset, RX to RX and TX to TX and removed the chip from Arduino UNO.

added this lines to boards.txt:

##############################################################

uno328.name=Arduino328

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

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

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

uno328.build.mcu=atmega328
uno328.build.f_cpu=16000000L
uno328.build.board=AVR_UNO
uno328.build.core=arduino
uno328.build.variant=standard

Selected that from board menu changed the programmer to AVRISP mkll and tried to upload the blink sketch but it stuck on "uploading" and after a while says "an error occurred during upload".

I triple checked the wiring!

Use the https://github.com/MCUdude/MiniCore for ATmega328. It has Boards Manager installation. Choose the right options in Tools menu for your ATmega328.

First burn the bootloader using programmer or "Arduino as ISP". Then you can do serial upload as usual.

You can put the ATmega328 on Uno if you want.


Arduino led not blinking #include <Arduino.h>

void setup()
 {
  pinMode(13, OUTPUT);
 }
void loop()
{
 digitalWrite(13, HIGH);
 delay(1);
 digitalWrite(13, LOW);
 delay(1);
}

I am trying to make an led glow for one second to glow and then go off but nothing happens

#include <Arduino.h>

void setup()
 {
  pinMode(13, OUTPUT);
 }
void loop()
{
 digitalWrite(13, HIGH);
 delay(1000);
 digitalWrite(13, LOW);
 delay(1000);
}

The problem with your code is that the delay function works in milliseconds and not seconds . 1sec = 1000ms .


Arduino 5V pump digital pin I am trying to control a 5V pump with arduino and ultrasonic sensor however i can't make it work with the pump connected to a pin.

I saw on the forum that you need transistor or relay but i don't understand why ?

Thanks !

Probably because the pump will use more current (mA) than a GPIO pin of the Arduino can deliver.

A GPIO pin on the Arduino can deliver 20 mA, or 40 mA max (but not advised for longer time).

Therefore, a separate power supplyis used, where the base pin of a transistor is connected to a GPIO pin (with a resistor) to 'switch' the transistor on and off.
The transistor base can be very low current (way within a GPIO's current range), which result in a much bigger current from the collector (connected to the power supply) to the emitter (connected to GND). The pump is somewhere between the external power supply and GND).

If you search for 'transistor as a switch' you will find many examples.

You also can use a relay if you don't need to switch it on often. Relay's are typically used for net-powered devices (110+ volts) and/or high current. See also Duncan's comments for additional notes regarding relays.


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

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

void setup ()
{

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

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

    delay (1000);

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

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

}

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

}

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

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

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

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


Trinket: Battery + USB at the same time? Is it allowed to have battery and USB connected to the Trinket(3.3V) at the same time?

I am using the battery to also power other components, so always disconnecting power, hooking USB to re-program and vice-versa is quite time consuming (and I fear to ruin the connectors).

From https://learn.adafruit.com/system/assets/assets/000/010/773/original/adafruit_products_trinket3.png?1378223258 it looks OK -- there are blocking diodes D3 and D2 that prevent backfeeding either the battery or the USB +5.

If you are worried, or want to monitor battery-only performance, you could make a special USB cable with the +5 red wire disconnected, and rely on the in-circuit battery to power the device, while still using the USB data lines.  See https://www.pjrc.com/teensy/external_power.html Option 2 for an example of the cable surgery.


How to communicate with arduino uno when arduino motor shield connected to arduino uno? I'm using this Dual Motor Shield

when I plug Arduino Dual Motor Shield into Aruino uno can't seen any way to communicate with Adruino uno.how can I communicate with uno ?

Communicate with what? A PC? The usb serial port should still work fine, and anything connected to the RX/tx pins (D0 and  D1)
If your concern is that there is no longer a socket on the top of this shield that you can plug wires into, well you can solder on some wires to the top of the board, or you could get a screw shield board to go between the arduino and motor shield which would make all the pins available. I have also use small gauage wire wrapped around the shield pins and then just insert the shield onto the arduino making kind of a wire wrap connection between the boards.


xbee communication not established between arduino I have 2 Xbee Series2 modules, one set to Coordinator AT (Connected to PC with XCTU via USB dongle) and other set to Router AT(Connected to Arduino is connected to PC USB... RX>TX  TX>RX and 5V GND)

http://continentalee.com.sg/xbee-adapter
My xbee adapter

I have the programme uploaded into Arduino, a very simple sketch to test xbee wireless communication.

Code is here

char msg = ' '; //contains the message from arduino sender
const int led = 13; //led at pin 13

void setup() {
Serial.begin(9600);//Remember that the baud must be the same on both arduinos
pinMode(led,OUTPUT);
}
void loop() {
while(Serial.available() > 0) {
           msg=(char) Serial.read();

           if(msg=='H') {
               digitalWrite(led,HIGH);
           }
           if(msg=='L') {
                digitalWrite(led,LOW);
           }
delay(1000);
}
}

The problem comes.

When I type "H" in the Serial Com, the led light up, and the letter "H" appears in the XCTU console.

however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino

Thank you for your help in advance.

Your example does not show your code that sends correctly but I will assume that it used 9600 speed and that the xbees are configured to 9600.

Not sure if this will help ...

  Arduino is connected to PC USB... RX>TX TX>RX

1) In this case maybe you should ensure that xbee tx is connected to the correct rx pin on the Arduino? I know you have stated this above but with the basic xbee configuration, if data works one way then it should also work the opposite way.

  however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino

2) Your example doesn't show any code to send data to XCTU and the pin13 LED will only light up when an 'H' is sent from XCTU

You could try this for better diagnostics

    void loop() {
while(Serial.available() > 0) {
           msg=(char) Serial.read();

      Serial.print("data arrived from xctu: ");
      Serial.print(msg);
      Serial.println();

           if(msg=='H') {
               digitalWrite(led,HIGH);
           }
           if(msg=='L') {
                digitalWrite(led,LOW);
           }
delay(1000);
}
}


Sense Whether Circuit is Closed How can you sense a closed circuit? I want to have 4 pins with disconnected wires and when touched with a fifth wire play a specific note on a piezo buzzer until disconnected again.

This project loops through several keys and checks whether they are being touched using the Capactive Sensor library. I want to do something similar, but not with capacitive sensing. Alternatively, it may work to have the buzzer always trying to play a note, but only sounds when one of the 4 circuits is close. I'm just not sure how that would work in the code.

Here is their code that uses capactive sensing:

#include <CapacitiveSensor.h>
#include "pitches.h"

#define COMMON_PIN      2    // The common 'send' pin for all keys
#define BUZZER_PIN      A4   // The output pin for the piezo buzzer
#define NUM_OF_SAMPLES  10   // Higher number whens more delay but more consistent readings
#define CAP_THRESHOLD   150  // Capactive reading that triggers a note (adjust to fit your needs)
#define NUM_OF_KEYS     8    // Number of keys that are on the keyboard

// This macro creates a capacitance "key" sensor object for each key on the piano keyboard:
#define CS(Y) CapacitiveSensor(2, Y)

// Each key corresponds to a note, which are defined here. Uncomment the scale that you want to use:
int notes[]={NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5}; // C-Major scale

// Defines the pins that the keys are connected to:
CapacitiveSensor keys[] = {CS(3), CS(4), CS(5), CS(6), CS(7), CS(8), CS(9), CS(10)};

void setup() {
  // Turn off autocalibrate on all channels:
  for(int i=0; i<8; ++i) {
    keys[i].set_CS_AutocaL_Millis(0xFFFFFFFF);
  }
  // Set the buzzer as an output:
  pinMode(BUZZER_PIN, OUTPUT);
}

void loop() {
  // Loop through each key:
  for (int i = 0; i < 8; ++i) {
    // If the capacitance reading is greater than the threshold, play a note:
    if(keys[i].capacitiveSensor(NUM_OF_SAMPLES) > CAP_THRESHOLD) {
      tone(BUZZER_PIN, notes[i]); // Plays the note corresponding to the key pressed
    }
  }
}

Connect your fifth wire to ground. Set the four inputs to INPUT_PULLUP. The four inputs will default HIGH, and be pulled LOW when connected to the ground wire.


Getting POST data into a char array I'm using Energia to program TI's CC3200 MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.

I'm trying to get the CC3200 to act as a Webserver which when successfully starts up serves up a page with two fields for the username and password that the user needs to fill. Now I'm able to see that the two fields are being successfully POST'd (through Serial.write but only when the code to get it into buffer is not present) but I was hoping someone can help me get this content into a character array (called buffer declared before the setup loop begins).

The code in the section //Here is where the POST data is does not seem to be working as I see garbage values in buffer and in the Serial.write. How do I get these POST values into buffer OR even better how do I split the two field values and store them into two separate character arrays?

void loop()
{
  // listen for incoming clients
  WiFiClient client = server.available();

  if (client) {
    //Serial.println("Client connected");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;

    while (client.connected()) {
      while(client.available()) {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {

            // Here is where the POST data is.
            Serial.println("Post data: ");
            int ctr = 0;
            while(client.available())
            {
            Serial.write(client.read());
            buffer[ctr] = client.read();
            ctr++;
        }
        Serial.println("Buffer: ");
        Serial.write(buffer);
        Serial.println();

        //Serial.println("Sending response");
        // send a standard http response header
        client.println("HTTP/1.0 200 OK");
        client.println("Content-Type: text/html");
        client.println("Connection: keep-alive");
        client.println();

        //form added to send data from browser and view received data in serial monitor
        client.println();
        client.println("<!DOCTYPE html>");
        client.println("");
        client.println("");
        client.println(" <FORM action=\"\" method=\"POST\">");
        client.println("
");
        client.println("    Username:");
        client.println("    <INPUT type=\"text\" name=\"uname\">

");
        client.println("    Password:");
        client.println("    <INPUT type=\"text\" name=\"pwd\">

");
        client.println("    <INPUT type=\"submit\" value=\"Submit\">");
        client.println("
");
        client.println(" </FORM>");
        client.println("");
        client.println("");

        client.println();

        client.stop();
        }
        else if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    //Serial.println("Disconnected");
    Serial.println();
  }
}

In this loop

while(client.available()) {
    Serial.write(client.read());
    buffer[ctr] = client.read();

you're using client.read() twice, so the buffer gets only every second character.

A solution could be:

while(client.available()) {
    int c = client.read();
    Serial.write(c);
    buffer[ctr] = c;


ESP-01 does not run code after Deep Sleep When using the deep sleep functionality on several ESP-01 boards, the boards require two resets in order to wake up properly (regardless of whether the resets are done by manually bridging the rst pin or by soldering a wire to do it from an interrupt). The boards do wake up and print some text automatically, but they do not run their firmware/code.
#include <ESP8266WiFi.h>
void setup() {
    Serial.begin(74880);
    Serial.print("\n--------------STARTING----------------\n");

    //pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    //digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off (gpio @ high= off)

    delay(500);
    ESP.deepSleep(2000000, WAKE_RF_DEFAULT );
}

void loop() {
}

I have not been able to just wake the board and run the code like most examples on the web intend to work, so I suppose the problem is not with this code.
On a successful wake up, the serial output looks like this:
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld

--------------STARTING---------------

After the first reset, the board does indeed wake up, but it does not run it's code. It only prints this
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

And then hangs there. After another reset, it successfully runs it's code.
This issue persists across all the esp 01 boards i own, and i have tried pulling UP and DOWN almost every combination of pins recommended. The line that is printed in the fauly cases does indeed say it is booting in the right mode, but still the code does not run, nor mine nor the one that runs before mine

What sasso is describing is classic Deep Sleep Zombie mode. There's someone else here with ESP-01 boards with the same issue.  I'd bet you got your boards in blister packs from Inland.  I didn't see any ESP-01 boards from Inland at my local computer store, only ESP-01S, and that one works with Deep Sleep just fine.  I only bought the one for a test.  I believe it's the Flash chip, but we haven't proven that yet.  I have plenty of Winbond flash in case I find a board that goes zombie, and can prove or disprove my theory.  I have 8 different types of boards and modules, and all come out of Deep Sleep correctly.
edit: If the pic at Ali is correct, the Puya Flash shouldn't be causing an issue, presuming it's real and not a clone.  Half the time the pics are only 'representative examples' of what they ship.  The ESP8266 Arduino core has supported Puya for a while now.  Also, on sober reflection the Inland package I bought said ESP-01S, and it's actually an ESP-01 (false advertising).  I looked closer and didn't see the pull-up resistors. :-(
If you're powering it from that USB programmer board, it should work.  If you have a separate 3.3V supply, I'd be suspicious of the supply.  The current spikes as the ESP is booting will cause many switching supplies to drop below 2V briefly, and the ESP goes insane.  Without having a zombie in front of me, I'm at a loss to go a lot further as my 'scope leads aren't that long.