# Question
Title: Using a MOSFET module to control DC LED PWM
I've seen some similar questions here for using MOSFET to control 12V LEDs But apparently the only MOSFET currently available to us is a 2-MOSFET high power trigger module, details in the link below.

https://www.elecrow.com/high-power-mosfet-trigger-switch-drive-module.html

How do we connect this to the Arduino to send the PWM trigger (I get confused by the three holes) and how do we connect the DC power to this??? I get confused with the power connections.

# Answer
> 3 votes
The three TRIG/PWM pins are connected to the same electrical point. The same goes for the three GND pins.

You can either solder:

1. A **2-pin 0.2 inch screw terminal** (the very same kind of those blue connectors already in the board) to the pair of big holes closer to the edge, or
2. A **2-pin 0.1 inch header** to the 2 holes in the centre of the 4-hole row (the smaller ones).

These will be the control input you should be connecting your Arduino to.

The DC power supply for the load that will be switched by the MOSFETS has to be connected between the VIN+ and VIN- terminals. Note that VIN- is connected internally to GND.

Your load has to be connected between the OUT+ and OUT- terminals.

That's all you need to know. In case you're in doubt, I've drawn this schematic for you (see below)

simulate this circuit – Schematic created using CircuitLab

**IMPORTANT ADDITIONAL NOTES:**

1. **No flyback diodes are present in the board**. If you try to switch an inductive load (a motor, a solenoid, etc.) with this board you have a high risk of damaging the MOSFETs and rend it useless.
2. **You need at least a 5V control signal** for switching high current loads with this board. Although a 3.3V control may seem able to switch the MOSFET, its internal RdsON at 3.3V could easily be high enough to produce excessive power dissipation and blow up the MOSFET. See these curves from the AOD4184 datasheet:

# Answer
> 0 votes
it seems to be a typical low-side switch (dual switches). the load goes into DC+ and DC- --\> ask the manufactuer to be sure.

whether it works for you will depend on the load, driving signal and the mosfet used -\> you should ask the seller for a schematic, or buy one and reverse engineer it.

---
Tags: pwm, mosfet
---


# Question
Title: Arduino Zero (ATSAMD21G) - I2C - continuous wrong data flow
I encountered a strange behavior while running 2 way transmission tests between 2 Arduino Zero (ATSAMD21G), one master and one slave. Wrong data is being continuously transferred both ways. The expected data is also being transferred in between. I have to filter out the received data to catch it (line 41 in Master's code and 33 in slave).

I'm using the stock wire libraries (being different for the 2 boards), along with Nick Gammon's "I2C\_readAnything".

Master's code

Slave's code

I think this continuous flow doesn't allow the bus to be released. It might be what's making it impossible to communicate with a second master (and maybe causing my previous problem)

I also tried my code between a Mega 2560 (slave) and a Zero (master). Fake data is, this time, only being sent one way (from the Zero to the Mega only).

Is there some specific code to add to send data properly from ATSAMD boards? Is it a bug in the SAMD Wire library?

I also had to add a 1ms delay after sending data from the Master. It wouldn't go through otherwise. Shouldn't it be handled by the ATSAMD or the Wire library?

# Answer
The code had several issues.

`receiveEvent`, on the slave side, contained a `millis` `if` condition timer that made it time out. I moved the timer to the master side before calling `Wire.requestFrom`.

`receiveEvent`, on the slave side, was also confusing real data with incoming `requestEvent`. I added an `if` statement to compare the `receiveEvent` data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the `Wire` library)

I set the global variables used in events as `volatile`. The code is working too without this tho.

fixed Master code

fixed Slave code
> 1 votes

# Answer
Start with a single byte, with a very small sketch, with both the Master and the Slave at 100kHz. When that is working 100% reliable, then you can try to transfer a struct.

The Slave RequestEvent function should always return valid data, not once every two seconds. The global variables that are used in receiveEvent or requestEvent **and** in the loop() should be made 'volatile'. Disable the interrupts in the loop() when reading or writing the global volatile struct.

With your sketch, you have to open the serial monitor for both the Master and Slave.

You could add more tests, for example testing the return value of Wire.endTransmissing, testing the 'howMany' parameter, testing the actual number that Wire.request returns.
> 0 votes

---
Tags: i2c, arduino-zero
---


title: Explain what is meant by "Arduino core"

text:
# Question
Title: Explain what is meant by "Arduino core"
What is an "Arduino core"?

Are there many different "Arduino cores"? such as a core that applies to LCD displays, another core that applies to servos, etc.?

# Answer
The Core is the software API for a specific group of chips.

For instance, the AVR core supports the AVR chips found on most Arduino boards. The SAM3X core supports the Arduino Due. Etc.

It is the code that provides things like digitalRead(), analogWrite(), millis() etc.

Since each family of chips works differently that abstraction layer between your sketch and the physical hardware of the chip needs to be different.

In your default IDE installation the Arduino AVR core can be found within the `hardware/arduino/avr/cores/arduino` folder.

Cores are usually installed as part of a "boards" bundle in the boards manager. This includes definitions for the boards ("variants"), the core and, equally importantly, the compiler and firmware uploading software for the chip on the board.
> 7 votes

# Answer
The "core" provides the low-level APIs (Application Programmer Interfaces) which are documented in the Arduino Reference page. For example, `digitalRead`, `digitalWrite`, `delay` and so on.

The core files usually contain the "include" files from Atmel which provide documented names for the various registers in the chip (eg. `DDRB` for data direction register B).

Since each chip type will have different addresses for the registers you will need a different core for each processor chip. Also in some cases people have assembled the chip onto different boards, and the cores will reflect how the board is wired. For example "edge pin 8" on one board may connect to a different pin on the processor chip compared to another board. Thus if you buy a board from a third-party they may also supply their own core files.

---

> Are there many different Arduino cores such as a core that applies to LCD displays, another core that applies to servos?

These are usually implemented in **libraries** which you can optionally include into your code. The libraries *extend* the core. Often the same library will work with different cores as the core code handles the differences between chips, so that the library doesn't have to.

---

## Selecting a core

As Majenko mentions in his answer, selecting a board in the IDE (Integrated Development Environment) usually tells the IDE to select the appropriate core for that board/chip combination.

More recent versions of the IDE allow you to install more cores by providing a link to where the core files are to be found, and then allowing you to choose one or more cores from that site.
> 5 votes

# Answer
As far as I know the cores are the different products which can be found at Products. In this list the Arduino cores can be selected in the IDE: Cores

LCD display (driver) etc. are mostly referred as shields or modules. A shield is a small 'board' you can stack on top of the Arduino (Core) and a module is normally to be used on a breadboard.
> 0 votes

# Answer
The collection of MCU's that are part of the Arduino family have differences from one to another in features like the address in memory-space of the basic processor registers, the I/O pin assignments to the I/O registers, nature and operation of timers, A/Ds, etc. The kinds of things we do with calls like pinMode(), digitalWrite(), or attachInterrupt().

These are considered the basic or "core" functions to be presented to the programmer by using libraries to present a common interface and hide those differences. The core libraries are managed by the Arduino IDE and the proper one(s) are selected when you select a board-type from the Tools | Board menu.

This is different from the user-contributed and other non-core dependent libraries you keep in your workspace 'libraries' folder. Both kinds are code libraries, but the so-called "core-libraries" are specific to the kind of processor you are compiling your sketch to run on.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Two-way communication on multimaster I2C bus
I'm trying to send data both ways between an Arduino Mega 2560 slave and 2 Arduino Nano Zero (ATSAMD21G).

This example is a simplified setup and code. There will be more masters along with passive slaves on the bus (LCD, EEPROM).

Code and results (txt files)

My code is working fine with one master only and the slave active on the bus (data is sent both ways every 2s). I however notice missing transfers to the masters when more than one master is active. The 2 masters to slave transfers are working properly (once the 2 masters are on, the data is received by the slave every 2s from each master).

Is this problem due to collision? How can I handle it?

# Answer
> 1 votes
The code had several issues leading to a constant flow of wrong data (with correct data in the middle) between the master that won the bus arbitration. This made it keep the bus too long and eventually give it away to the second master at a random time, with missed transfers from the second master in between. The second master was then behaving the same and so on.

`receiveEvent`, on the slave side, contained a `millis` `if` condition timer that made it time out. I moved the timer to the master side before calling `Wire.requestFrom`. Avoid slow code in `receiveEvent`!

`receiveEvent`, on the slave side, was also confusing real data with incoming `requestEvent`. I added an `if` statement to compare the `receiveEvent` data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the `Wire` library)

These fixes solved the busy bus problem. I figured these out after asking question #35092

The bus speed also had to be reduced because 800 kHz was too fast for the Mega 2560 (but worked between 3 Nano).

The slave has to send the data destined to both masters to each of them because `requestEvent` can't tell which master is asking for data. The data is then filtered on each master to only keep the relevant information.

The data is now being transferred both ways between the 2 Nano masters and the Mega slave at the correct interval, without corrupt data.

fixed Slave code

fixed Master 1 code

fixed Master 2 code in the same repo (I'm limited to 2 links post)

# Answer
> 0 votes
> notice missing transfers to the masters when more than one master is active.

Because you didn't provide a way for the master's to know of a transmission ISS in progress. Lack of conflict resolution. A problem with all multimeter transmission.

A simpler approach is for the slave to signal a transmission from the master. That can be done via a slave requestion pin from the slave to the master.

---
Tags: i2c
---


title: Multi-LED Toggle Switch

text:
# Question
Title: Multi-LED Toggle Switch
I am using a Python3 GUI on my RPi3 to control my DFRobot Bluno Mega 2560 via USB. The Mega is hooked up to a breadboard with 4 LED's and I am trying to control each LED with their own toggle switch. I was able to do this with one LED but for some reason when I try to achieve the same with more than one it doesn't work, I get absolutely no response from the LED's whatsoever. It is something to do with how the arduino is receiving the ASCII code, or I think it may be a problem with how I am implementing tkinter as I have little experience with it. If anyone can tell me what I am doing wrong please let me know.

Here is the Python3 GUI code:

```
import serial # import the serial library
import time # import the time library
from tkinter import * #import Tkinter GUI library

def toggleRed():
    if redBtn.config('relief')[-1] == 'sunken':
        redBtn.config(relief="raised")
        arduino.write('a'.encode())
    else:
        redBtn.config(relief="sunken")
        arduino.write('b'.encode())

def toggleGreen():
    if greenBtn.config('relief')[-1] == 'sunken':
        greenBtn.config(relief="raised")
        arduino.write('c'.encode())
    else:
        greenBtn.config(relief="sunken")
        arduino.write('d'.encode())

def toggleBlue():
    if blueBtn.config('relief')[-1] == 'sunken':
        blueBtn.config(relief="raised")
        arduino.write('e'.encode())
    else:
        blueBtn.config(relief="sunken")
        arduino.write('f'.encode())

def toggleYellow():
    if yellowBtn.config('relief')[-1] == 'sunken':
        yellowBtn.config(relief="raised")
        arduino.write('g'.encode())
    else:
        yellowBtn.config(relief="sunken")
        arduino.write('h'.encode())

print ('Connecting...')
arduino = serial.Serial("/dev/ttyACM0", 9600)
time.sleep(3)
print ('Connection established successfully')

appWindow = Tk() # creates the application window (you can use any name)
appWindow.wm_title("RGB LED Control") # displays title at the top left
appWindow.config(bg ="#037481")

mainFrame = Frame(appWindow, bg="#037481") #define the main frame of the GUI
mainFrame.grid() #grid the frame into the App Window

btnFrame = Frame(mainFrame, bg="#037481") #define the frame within the main frame that holds buttons
btnFrame.grid() #grid the frame into the main frame

redBtn = Button(btnFrame, text="RED", width=12, bg="red", relief="raised", command=toggleRed)
redBtn.grid(column=0,row=0,sticky='EW')

greenBtn = Button(btnFrame, text="GREEN", width=12, bg="green", relief="raised", command=toggleGreen)
greenBtn.grid(column=0,row=1,sticky='EW')

blueBtn = Button(btnFrame, text="BLUE", width=12, bg="blue", relief="raised", command=toggleBlue)
blueBtn.grid(column=0,row=2,sticky='EW')

yellowBtn = Button(btnFrame, text="YELLOW", width=12, bg="yellow", relief="raised", command=toggleYellow)
yellowBtn.grid(column=0,row=3,sticky='EW')

appWindow.mainloop()# begins main loop

```

Here is the arduino code:

```
int ledRed = 13;
int ledGreen = 11;
int ledBlue = 9;
int ledYellow = 7;

//int ledRedStatus;
//int ledGreenStatus;
//int ledBlueStatus;
//int ledYellowStatus;

void setup() {
  pinMode(ledRed, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledBlue, OUTPUT);
  pinMode(ledYellow, OUTPUT);
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() == '97') {
    digitalWrite(ledRed, LOW);
  }
  if(Serial.available() == '98') {
    digitalWrite(ledRed, HIGH);
  }
  if(Serial.available() == '99') {
    digitalWrite(ledGreen, LOW);
  }
  if(Serial.available() == '100') {
    digitalWrite(ledGreen, HIGH);
  }
  if(Serial.available() == '101') {
    digitalWrite(ledBlue, LOW);
  }
  if(Serial.available() == '102') {
    digitalWrite(ledBlue, HIGH);
  }
  if(Serial.available() == '103') {
    digitalWrite(ledYellow, LOW);
  }
  if(Serial.available() == '104') {
    digitalWrite(ledYellow, HIGH);
  }
}

```

# Answer
Adding comments to your code would help us understand your intentions.

It is assumed you are sending the ASCII values for 'a', 'b', 'c', ... for different buttons and their actions. And that you want to receive these on an Arduino over the USB using the USB serial port protocol. It is also assumed that your Python script works and the Linux OS is creating a /dev/ttyACM0 or some such serial device when you plug in your Arduino.

Looking at your Arduino code we see you are only checking for the number of bytes in the Arduino's serial port receive buffer by using the Serial.available() method call. If your intentions were to read a byte of data you would instead call the serial.read() method.

It is suggested that you check if there is any data available and if there is you would read it once and save it to a variable. Then you can check this variable many times and decide what action to take based on its value. If you read the buffer many times you would be pulling a new byte of data from the buffer with each read. If you run out of data to read you will be supplied with the value of -1 as an indication there is no more data.
> 1 votes

# Answer
```
  if(Serial.available() == '97')

```

Make sure the comparison is actually valid and Serial.available() does what you think it does. If you wish to read a value from serial port, .available() doesn't seem to be the right function for that.
> 0 votes

---
Tags: arduino-mega, led
---


# Question
Title: Max current of Vin and 5V pin on Arduino Nano
What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

# Answer
It's hard to say. The maximum the on-board regulator can provide is 800mA. However the actual amount it can provide at any time depends on other external factors - most notably:

* The voltage of your supply
* The ambient temperature around the board
* The thermal mass of the copper the tab is soldered to

The higher your input voltage the more excess voltage has to be converted to heat. When it gets too hot it overheats and (theoretically) shuts down.

Also the board itself will take some of the maximum 800mA quota, say 50mA (guestimate), so that leaves 750mA theoretical maximum for the 5V pin - but only when powered from not much more than 6.2V (5V + 1.2V regulator dropout voltage).

However, if you are powering from the USB port then it is limited to whatever the USB port can provide (100mA for a passive hub, 500mA for a normal USB port, 2A for a CDP).

The VIN current will be the same as the 5V pin current + the board current.
> 9 votes

# Answer
> What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

it depends on the power dissipation limits (and to a less extent the current limit) on the regulator. the power dissipation is determined by the load your arduino and its loads draw, and the voltage dropout on the regulator.

the other part of the thermal limit is the thermal resistance of the package and ambient temperature.

Most of them use el cheapo 1117 regulators in sot223 that has a limit of 1amp + a thermal limit of 100c/w. so max power dissipation should be less than 1w. That means a practical limit of 0.5amp under the most aggressive conditions (2v dropout, or 7v input).

at 9v input, max of 0.25amp. at 12v input, a max of 0.15amp. ...
> 1 votes

---
Tags: arduino-nano, pins, current
---


# Question
Title: Any resources you know with regards to remotely reading data from arduino?
I am trying to implement arduino101 and my application needs to read data from the Arduino without a USB connection to my laptop. I appreciate you if you know any beginner-level tutorial for this.

Please let me know if you can't understand my question.

# Answer
> 2 votes
You can use the Bluetooth on the board, a Bluetooth dongle for your laptop if the laptop does not have bluetooth or you can buy a wifi shield.

The 101 has Bluetooth LE on the board.

You will find there is a Bluetooth -\> Serial USB software, so the application on the laptop can still work the same way as when using the usb.

Here are the Bluetooth examples for the 101 on arduino.cc

https://www.arduino.cc/en/Reference/CurieBLE

and the user guide for the 101

https://www.arduino.cc/en/Guide/Arduino101

---
Tags: arduino-ide, wireless, remote-control
---


title: How do I install Arduino drivers?

text:
# Question
Title: How do I install Arduino drivers?
I need to install my Arduino drivers, but Windows 8.1 doesn't seem to like Arduino, and it greys out the update driver button. Therefore I can't select the drivers from the drivers folder in my Arduino IDE folder.

There are drivers that need to be installed. But Windows 8.1 greys out the `update driver software` button. Also, it refers to Arduino Uno as an `unknown device`. How do I install the Arduino drivers and make Windows let me install the drivers?

# Answer
> 1 votes
The IDE package usually ships with the driver(at-least the latest one).
Go to **Program Files** in **C:** and find the **Arduino** folder and you should find a folder named **Drivers**. Inside you will find an application named **dpinst-x86**. Run it and you should be good to go!

# Answer
> 0 votes
Often reinstall the latest arduino IDE with Windows Administrator rights helps (use right click execute as administrator).

# Answer
> 0 votes
If the arduino is undetected in PC go to control panel-device manager - connect the arduino and some COM port will appear click it and troubleshoot make sure your PC is connected to internet and then you will be able to see your com port in arduino ide.

---
Tags: arduino-uno, windows
---


title: Led and button simulation of a blink

text:
# Question
Title: Led and button simulation of a blink
My circuit:

My code:

```
// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2; // pushbutton connected to pin 2.

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == HIGH) // check while the button is pressed
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
  }
}

```

What I wish to do is that when I press the button, the Led's start flashing and when I press them again, they stop blinking (like a fire alarm). Right now they do nothing and I dont know why. Is it something with the circuit or the code?

# Answer
> 1 votes
The volatage level on the IO pin needs to change (from low to high and vice versa), only then can the microcontroller detect a button press. Without another connection to the button, IO2 is simply floating (unconnected).

There are two methods to implement this: external pull-up or external pull-down resistors and internal pull-up resistors (both methods are described for example in this tutorial).

I prefer the internal pull-up resitor method. You need to connect the second pin of the button to GND. Then change your setup code to

```
pinMode(buttonPin, INPUT_PULLUP);

```

If the button is not pressed, the internal pull up resistor inside the microcontroller pulls IO2 to +5V and a `digitalRead(buttonPin)` returns `HIGH`. When you press the button, IO2 is pulled to GND and `digitalRead(buttonPin)` returns `LOW`.

So in your case you need to check for a `LOW` reading, because you want the LEDs to blink when the button is pressed.

(Btw. you can replace the while loop with an if, since the `loop()` function is already executed in an infinite loop.)

---
Tags: arduino-uno, led, button, simulator
---


title: ESP01 flashing error

text:
# Question
Title: ESP01 flashing error
I am trying to program an ESP8266-01 WiFi module using an Arduino Uno as a USB to TTL programmer. I have removed the ATmega and grounded the RESET pin (quite useless without the uC though). Then, using esptool.py I tried to upload a Bare minimum sketch with the Arduino IDE and later using the following:

```
python esptool.py -b 57600 -p /dev/cu.usbport write_flash 0x000000 "nodemcu.bin"

```

However, both ways give me the same output:

```
A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet ('\x08')

```

I have tried sending AT commands to the ESP01 like "AT" or "AT+GMR" and everything works fine, but I cannot upload any sketch because of that error.

I also followed esp8266 official forum advice to edit the Python script according to the following, but without success.

```
Line 43 ESP RAM BLOCK = 0x1800 //change this to 180
Line 44 ESP RAM BLOCK = 0x400 //change this to 40

```

The level conversion from 5v TTL to 3.3v is done through simple resistor node (2k and 1k), while RST is kept at Vcc through 10k pull-up resistor and a push button to ground it.

# Answer
> 0 votes
Your wiring sounds wrong.

Tie CHPD to Vcc (3.3v) to enable the device.

Tie GPIO0 to ground as you power up, to put it into programming mode.

RST can be left floating, or PULL (not tie!) up to Vcc through a resistor, say 10k.

That diode level shifter arrangement is unusual. A potential divider on the ESP's RxD is all you need - say 1k and 2k.

# Answer
> 0 votes
An addition to Mark's answer, from Uploading sketch to ESP8266

> Before download, pull both GPIO0 and RST to ground. Release the pull down on RST, but keep GPIO0 low. When the IDE has finished uploading, release GPIO0 from low.

---
Tags: esp8266
---


title: Tiny RTC I2C module not working

text:
# Question
Title: Tiny RTC I2C module not working
I bought a Tiny RTC I2C module and it doesn't work. When i run the TimeRTCSet from TIME library all i get is:

```
Unable to sync with the RTC
0:00:00 0 0 1970
0:00:01 1 1 1970
0:00:02 1 1 1970
0:00:03 1 1 1970
0:00:04 1 1 1970
0:00:05 1 1 1970
0:00:06 1 1 1970
0:00:07 1 1 1970

```

The module is connected like this:

Vin -\> 5V Gnd -\> Gnd SCL -\> A5 SDA -\> A4

I'm using arduino uno.

I tried with a simple i2c scanner, but it returned two devices!

```
Scanning...
I2C device found at address 0x50  !
I2C device found at address 0x68  !
done

```

Only the clock is connected. I tried removing the battery for night to reset it, but it didn't fix it.

Could you help me?

# Answer
This issue can be fixed by deleting the library downloaded using arduino library manager and replacing it with the library from github.
> 0 votes

# Answer
Try using the example code from the MD\_DS1307 library to find the settings on your RTC, when I first wired mine up the clock was not running and I couldn't set the time on it. After I enabled it, it worked just fine.
> 0 votes

---
Tags: arduino-uno, i2c, rtc, wire-library
---


title: How I can make alarm on off?

text:
# Question
Title: How I can make alarm on off?
I want to do is BEEP! to show that the program is running.

```
#define SPKR 4 //this is the digital pin that you plugged the red       wire into

void setup()
{
   pinMode(SPKR, OUTPUT); //set the speaker as output
}

void loop() //do this over and over
{
   digitalWrite(SPKR, HIGH); //turn the speaker on
   delay(500);                     //wait for half a second
   digitalWrite(SPKR, LOW); //turn the speaker off
   delay(500);                    //wait for half a second
}

```

With out this any other way I mean without repeating the code HIGH / LOW during this beep I want do same things else

# Answer
The code you show will toggle the `SPKR` pin at a 1 Hz rate. If you have an ordinary speaker attached, you will hear it click twice a second, but it won't generate an audible tone.

To generate a tone, use `tone(pin, frequency)` calls, or `tone(pin, frequency, duration)` calls.

For example:

```
void loop() {
   tone(SPKR, 400, 500); // 400 Hz tone for half second
   delay(500);           // no tone for half second
}

```

Note, ordinary speakers are low-impedance devices, eg 4 Ω, 8 Ω, etc. You can use an audio transformer for impedance matching – this helps produce an adequate output volume – but lacking that, should put a resistor (eg 220 Ω) in series with the speaker to avoid over-current conditions. AVR pins can deliver 25 mA without too much stress, and typically are rated at an absolute max of 40 mA.
> 2 votes

---
Tags: arduino-uno, programming
---


title: MIDI connectors / Diodes

text:
# Question
Title: MIDI connectors / Diodes
Does anybody know if the following MIDI DIN connectors will fit in a breadboard?

(or in general with 'generic' electrical components?)

MIDI DIN

And the same for:

Diodes to be used for MIDI in.

# Answer
Breadboards use a 2.54 mm (0.1") grid. The PCB footprint on that link uses a nominal 2.5 mm grid, which is essentially the same:

However, those pins are rather large; it's possible that you need to rotate some pins by 90° (with pliers and brute force) to make them fit into your breaboard's holes, or that they do not fit at all. And even if they fit, they can ruin your breadboard. You might need to file them off.

Consider using a panel-mount MIDI jack instead (which would require soldering, or leads with test clips):

(search for "5 pin DIN female jack")

---

The MIDI specification recommends a 1N914 diode, but that is only because it was written over thirty years ago. The 1N4148 is much more common now, and has the same characteristics. But this diode is used only as reverse voltage protection for the optocoupler's LED, so you can use any random fast switching diode.

---

As for the optocopler (which you didn't mention, but I'll throw in my two cents worth anyway): the PC900 was discontinued, and the 6N138 is slow. Use either the H11L1 (of which the PC900 was a clone) or the 6N137; both work best with a 1 kΩ pull-up resistor.
> 1 votes

---
Tags: midi
---


# Question
Title: Post-split, where do I download the Arduino IDE?
I've been out of the loop with Arduino for several years. I heard about the split (another link), but didn't really understand, nor keep up with it, nor the details of the fallout.

Today, I decided to jump back in and make something, and a DDG search led me to Arduino.cc to get the software. But is that what I need?

How do I know if that's the right software IDE? Is there another location? Does it matter? Does it depend on more variables? Is this split akin to the OpenOffice and LibreOffice split, where one is more better (technical term!) supported than the other?

I'm working on an Arduino Uno I got from Microcenter.

# Answer
The split is already over. They are working on merging everything that happened during the split, if they haven't already.

I'd go with the arduino.cc version, as that was the website before the split (where the other party used arduino.org).
> 3 votes

# Answer
Both sites contain the same version of the IDE. .Org dropped their 1.7.x branch (actually 1.0.x renumbered) and both now have the 1.6.x branch version-bumped up to 1.8.x.

As Gerben noted, the split is over, The rift is healed!.
> 1 votes

---
Tags: arduino-ide
---


title: Cheat Sheet for interruption

text:
# Question
Title: Cheat Sheet for interruption
Just read a post about timers and there was a timers cheat sheet posted there. It has been very helpful and I wonder if there is one for interrupts as well?

The post with the nice timer cheatsheet was this one Arduino constant clock output

# Answer
Perhaps something like this (for the Arduino Uno based MPU):
> 1 votes

---
Tags: arduino-uno
---


title: Radio Issues with RF69HW

text:
# Question
Title: Radio Issues with RF69HW
I am working through this tutorial on using the RF69HW. The RF69HW datasheet can be found here. I am using an Eegoo Uno R3 and yes I am aware that the Arduino is a 5v and the RF69HW is a 3.3v board. I am using some voltage dividers to get the voltage to 3.3v via the circuit shown below, at end of question.

I would use a level shifter but I only realized this mistake today and I am trying to get this working ASAP. The radio does not appear to be working. In fact the program seems to get caught on it. I introduced:

```
radio.sendACK();
Serial.print(" - ACK sent");

```

After the button has been pressed. This is the output I get:

```
Listening at 915 Mhz...
Button pressed!

```

So it gets to the line before it where the button is pressed but then gets stuck attempting to sendACK. I don't know what to make of this. Any help getting these two to communicate is appreciated. Code and pictures below.

Here is the code I am using as the sender:

```
#include <SPIFlash.h>
#include <SPI.h>
#include <LowPower.h>
#include <RFM69.h>
#include <RFM69_ATC.h>
#include <RFM69_OTA.h>
#include <RFM69registers.h>

//*********************************************************************************************
// *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
//*********************************************************
//This part of the code simply sets up the parameters we want the chip to use
// these parameters allow you to have multiple networks, channels, and encryption keys
#define NETWORKID     100  //the same on all nodes that talk to each other
#define RECEIVER      1    //unique ID of the gateway/receiver
#define SENDER        2    // you could for example, have multiple senders
#define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
//Select your frequency by uncommenting
#define FREQUENCY     RF69_915MHZ
#define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
#define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
//*********************************************************************************************
#define SERIAL_BAUD   9600

//This part defines the LED pin and button pin
#define LED             9 //LED on D9
#define BUTTON_INT      1 //user button on interrupt 1 (D3)
#define BUTTON_PIN      3 //user button on interrupt 1 (D3)
#define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

RFM69 radio;

// the setup contains the start-up procedure and some useful serial data
void setup() {
  Serial.begin(SERIAL_BAUD);
  radio.initialize(FREQUENCY,NODEID,NETWORKID);
#ifdef IS_RFM69HW
  radio.setHighPower(); //only for RFM69HW!
#endif
  radio.encrypt(ENCRYPTKEY);
  char buff[50];
  sprintf(buff, "\nListening at %d Mhz...", FREQUENCY==RF69_433MHZ ? 433 : FREQUENCY==RF69_868MHZ ? 868 : 915);
  Serial.println(buff);
  Serial.flush();
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  attachInterrupt(BUTTON_INT, handleButton, FALLING);
  pinMode(RX_TOGGLE_PIN, OUTPUT);
}

//******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
#define FLAG_INTERRUPT 0x01
volatile int mainEventFlags = 0;
boolean buttonPressed = false;
void handleButton() {
  mainEventFlags |= FLAG_INTERRUPT;
}

byte LEDSTATE=LOW; //LOW=0

void loop() {
  //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
  if (mainEventFlags & FLAG_INTERRUPT) {
    LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
    mainEventFlags &= ~FLAG_INTERRUPT;
    if (!digitalRead(BUTTON_PIN)) {
      buttonPressed=true;
    }
  }
  if (buttonPressed) {
    Serial.println("Button pressed!");
    buttonPressed = false;
    radio.sendACK();
    Serial.print(" - ACK sent");
    if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
      delay(100);
  }
  //check if something was received (could be an interrupt from the radio)
  if (radio.receiveDone()) {
    //print message received to serial
    Serial.print('[');Serial.print(radio.SENDERID);Serial.print("] ");
    Serial.print((char*)radio.DATA);
    Serial.print("   [RX_RSSI:");Serial.print(radio.RSSI);Serial.print("]");
    Serial.println();
    if(LEDSTATE==LOW) LEDSTATE=HIGH;
    else LEDSTATE=LOW;
    digitalWrite(LED, LEDSTATE);
    digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
    //check if sender wanted an ACK
    if (radio.ACKRequested()) {
      radio.sendACK();
      Serial.print(" - ACK sent");
    }
  }
  radio.receiveDone(); //put radio in RX mode
  Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
}

```

And the receiver:

```
#include <SPIFlash.h>
#include <SPI.h>
#include <LowPower.h>
#include <RFM69.h>
#include <RFM69_ATC.h>
#include <RFM69_OTA.h>
#include <RFM69registers.h>

//*********************************************************************************************
// *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
//*********************************************************
//This part of the code simply sets up the parameters we want the chip to use
// these parameters allow you to have multiple networks, channels, and encryption keys
#define NETWORKID     100  //the same on all nodes that talk to each other
#define RECEIVER      1    //unique ID of the gateway/receiver
#define SENDER        2    // you could for example, have multiple senders
#define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
//Select your frequency by uncommenting
#define FREQUENCY     RF69_915MHZ
#define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
#define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
//*********************************************************************************************
#define SERIAL_BAUD   9600

//This part defines the LED pin and button pin
#define LED             9 //LED on D9
#define BUTTON_INT      1 //user button on interrupt 1 (D3)
#define BUTTON_PIN      3 //user button on interrupt 1 (D3)
#define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

RFM69 radio;

// the setup contains the start-up procedure and some useful serial data
void setup() {
  Serial.begin(SERIAL_BAUD);
  radio.initialize(FREQUENCY, NODEID, NETWORKID);
#ifdef IS_RFM69HW
  radio.setHighPower(); //only for RFM69HW!
#endif
  radio.encrypt(ENCRYPTKEY);
  char buff[50];
  sprintf(buff, "\nListening at %d Mhz...", FREQUENCY == RF69_433MHZ ? 433 : FREQUENCY == RF69_868MHZ ? 868 : 915);
  Serial.println(buff);
  Serial.flush();
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  attachInterrupt(BUTTON_INT, handleButton, FALLING);
  pinMode(RX_TOGGLE_PIN, OUTPUT);
}

//******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
#define FLAG_INTERRUPT 0x01
volatile int mainEventFlags = 0;
boolean buttonPressed = false;

void handleButton() {
  mainEventFlags |= FLAG_INTERRUPT;
}

byte LEDSTATE = LOW; //LOW=0

void loop() {
  //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
  if (mainEventFlags & FLAG_INTERRUPT) {
    LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
    mainEventFlags &= ~FLAG_INTERRUPT;
    if (!digitalRead(BUTTON_PIN)) {
      buttonPressed = true;
    }
  }
  if (buttonPressed) {
    Serial.println("Button pressed!");
    buttonPressed = false;
    radio.sendACK();
    Serial.print(" - ACK sent");
    if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
      delay(100);
  }
  //check if something was received (could be an interrupt from the radio)
  if (radio.receiveDone()) {
    //print message received to serial
    Serial.print('['); Serial.print(radio.SENDERID); Serial.print("] ");
    Serial.print((char*)radio.DATA);
    Serial.print("   [RX_RSSI:"); Serial.print(radio.RSSI); Serial.print("]");
    Serial.println();
    if (LEDSTATE == LOW) LEDSTATE = HIGH;
    else LEDSTATE = LOW;
    digitalWrite(LED, LEDSTATE);
    digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
    //check if sender wanted an ACK
    if (radio.ACKRequested()) {
      radio.sendACK();
      Serial.print(" - ACK sent");
    }
  }
  radio.receiveDone(); //put radio in RX mode
  Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
}

```

Here is a link to project pictures: imgur.com/a/sFW88

Here is my circuit diagram:

# Answer
> 1 votes
The circuit diagram shows several resistive voltage divider circuits, each made up of a 1KΩ in series with 2KΩ.

When 5 V goes into the top of such a divider, about 3.3 V appears at the resistor junction. (And 0 V in gives 0 V out.) This is suitable for a 5 V output pin connected to a 3.3 V input pin.

For connecting RF69HW 3.3 outputs (eg MISO) to 5 V Uno inputs, ideally one would step up 3.3 V to 5 V. Instead, MISO goes to the resistor junction of what *resembles* a resistive voltage divider but in fact is not.

Consider a low output on MISO; then the 1K-2K junction goes to zero; so the Uno reads 0 on D12, as it should.

Now consider a high output on MISO. The 1K-2K junction goes to 3.3 V, driving about 1.65 mA to ground through the 2KΩ resistor. Presumably the SPI library uses pin 12, MISO, as an input, so current through the 1KΩ resistor is specified to be at most 10 μA (per Table 29-14 in ATmega328 datasheet) and is quite likely to be at most a few nanoAmps. In any case, the voltage at pin 12 will be quite close to 3.3 V, which will register as a high input. (Figure 31-72 in ATmega328 datasheet shows a 2.6 V threshold when Vcc is 5 V.)

This is more of a long comment than an answer, because although the MISO circuitry is problematic, it appears that it should work anyway.

---
Tags: arduino-uno, rf
---


title: BLE Shield v2.1

text:
# Question
Title: BLE Shield v2.1
I have an Arduino Mega 2560 and a BLE Shield v 2.1 from RedBearLab. When I try to connect it through Bluetooth from my laptop to 'BLE Shield', it says 'Connected!'. When I try from a Windows phone, it also says 'Connected'.

But when I try to connect from an Android device, it gives me an error: 'pairing rejected by BLE shield' or 'couldn't pair with BLE Shield because of an incorrect PIN or passkey'.

What seems to be the problem?

# Answer
I would guess that the problem is an incorrect PIN or passkey.

I've read from manuals for some gadgets that some devices/phones automatically try the PIN 0000 and some don't. I have never seen my Windows phone ask for a PIN when the device hasn't got one set, so I'm guessing that Windows automatically tries 0000 and Android doesn't. Is there a setting on Android that will let you enter the pin (which is probably 0000) ?
> 1 votes

---
Tags: bluetooth, android
---


title: Stop Led's from blinking

text:
# Question
Title: Stop Led's from blinking
My code:

```
// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   }
 if (buttonState == HIGH){
   digitalWrite(led, LOW);}
  }

```

The last line of code:

```
if (buttonState == HIGH){
   digitalWrite(led, LOW);}

```

Is what I tried using to turn the led off from its continuous blinking state. So the point of this project is to make the led's blink with a button, then turn them off with the same button. This has been bugging me for hours and I've done all the work but can't seem to get this last part done. What is being done wrong here?

**EDITED for clarification:**

The intention is that with each push of the button the LED is toggled between a blinking and a no-blinking state. The state of the LED is not driven by the level (pushed/unpushed) of the button itself, but by the pushing action itself.

# Answer
It makes sense to make switch-testing fairly independent of blink-control. That's done in the following code, which turns blinking on or off each time a button is pressed. With this code, between button presses the LED either is off or it blinks at about a 2 Hz rate.

```
enum { LED=13, ButtonPin=2, BounceMS=50, BlinkMS=256 };
unsigned long buttonAt;
bool blinky, bouncy, buttonState;

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(ButtonPin, INPUT_PULLUP);
  blinky = bouncy = buttonState = false;
  buttonAt = millis();
}

void loop() {
  // Detect button changes
  if (bouncy) {
    if (millis() - buttonAt > BounceMS)
      bouncy = false;       // End of debounce period
  } else {
    if (digitalRead(ButtonPin) != buttonState) {
      buttonState = digitalRead(ButtonPin);
      buttonAt = millis();
      bouncy = true;        // Start debounce period
      if (buttonState) {    // Was button just pressed?
        blinky = !blinky;   // Toggle blink-state
      }
    }
  }
  // Control light-blinking
  if (blinky) {
    // Turn LED on for BlinkMS ms, then off for same
    digitalWrite(LED, (millis() - buttonAt)%(2*BlinkMS) < BlinkMS);
  } else {
    digitalWrite(LED, LOW);
  }
}

```
> 3 votes

# Answer
**EDITED**

The Arduino `loop()` function makes the use of a `while` loop redundant in this case. Even worse: the way you've implemented that `while` loop prevents `buttonState` from being updated, thus getting stuck in the loop.

What you actually need is to use timers to blink the LED, and a 2-state machine driven by HIGH to LOW button transitions.

Try this instead:

```
#include "Timer.h"

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
const int led = 13;
const int buttonPin = 2;

// declare state variables as global
bool buttonState = LOW;
bool buttonState_prev = LOW;
bool toggleBlinking;
bool blinkState;

// declare a Timer object so blinking can be done without loosing button presses
Timer timer_b;
int blink_id;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);

  // initial state: toggle led each 1000 ms
  blink_id = timer_b.oscillate(led, 1000, HIGH);
  blinkState = true;
  toggleBlinking = false;
}

// the loop routine runs over and over again forever:
void loop() {
  // Update the timer (required)
  timer_b.update();

  // check if button has been pressed (HIGH to LOW),
  // then debounce it and raise toggle flag
  buttonState = digitalRead(buttonPin);
  if ((buttonState != buttonState_prev) && (buttonState_prev == HIGH)) {
    // simple button debounce (confirm press after some ms)
    delay (50);
    buttonState = digitalRead(buttonPin);
    if (buttonState != buttonState_prev) toggleBlinking = true;
  }

  // keep current LED state unless the button has been pushed
  switch (blinkState) {
    case true:
      // if button has been pushed, stop blinking and change LED state
      if (toggleBlinking == true) {
        timer_b.stop (blink_id);
        blinkState = false;
      }
      break;
    case false:
      digitalWrite(led, LOW);
      // if button has been pushed, start blinking and change LED state
      if (toggleBlinking == true) {
        blink_id = timer_b.oscillate(led, 1000, HIGH);
        blinkState = true;
      }
      break;
  }

  buttonState_prev = buttonState;
  toggleBlinking = false;
}

```

**NOTE:** You'll need to install the Timer.h library. I'VE TESTED MY CODE AND IT WORKS.
> 3 votes

# Answer
As the OP explained in a comment, what he is trying to achieve is to have a button alternate between blink and off, not having the button to be pressed to shut down the led.

This can be done in this way:

```
bool prevButtonState;
bool ledBlinking;

void loop()
{
    bool buttonState = digitalRead(buttonPin);

    if (prevButtonState && !buttonState)
    { // Pressing edge: there is a transition between high and low
        ledBlinking = !ledBlinking;
    }
    prevButtonState = buttonState;

    if (ledBlinking)
    {
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(1000);               // wait for a second
        digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
        delay(1000);               // wait for a second
    }
    else
    {
        digitalWrite(led, LOW);
    }
}

```

This, however, leads to a very long time between successive checks of the button (since there is a 2s delay between cycles). You can solve this using the millis function:

```
bool prevButtonState;
bool ledBlinking;
unsigned long prevMillis;

void loop()
{
    bool buttonState = digitalRead(buttonPin);

    if (prevButtonState && !buttonState)
    { // Pressing edge: there is a transition between high and low
        ledBlinking = !ledBlinking;

        prevMillis = millis() - 1000; // Force a check
    }
    prevButtonState = buttonState;

    if (ledBlinking)
    {
        if ((millis() - prevMillis) >= 1000)
        {
            prevMillis += 1000;
            digitalWrite(led, !digitalRead(led));
        }
    }
    else
    {
        digitalWrite(led, LOW);
    }
}

```

Next there is the debounce problem, but this becomes OT. Suggestion: use the Bounce2 library to manage the button if you experience bounces
> 3 votes

# Answer
```
while (buttonState == LOW)

```

gets you trapped in an endless loop, once `buttonState == LOW`.
You have to poll `buttonState` **inside** this loop if you ever want to get out of it.
However this is not enough for your purpose. What you really need is a (boolean) variable - let's name it `blinking`, for instance - which changes its value each time you see a falling edge on buttonState.
Then check this variable's value in an if/else clause like this:

```
if (blinking == true)
{
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
}
else
{
   digitalWrite(led, LOW);}
}

```

But with this you will soon face the next problem: The polling speed for your button is very low, because of the very long delays, which keep you about 2 seconds inside the `if` clause.
Try setting up the blink cycle using a PWM, as described here
Then use the `if` clause above to set the PWM duty to 50%, and the `else` clause to set it to 0%.
> 2 votes

# Answer
try this:

```
if (key_pressed()) digitalWrite(LED_PIN, (digitalRead(LED_PIN)==ON)?OFF:ON);
else digitalWrite(LED_PIN, OFF);

```

define ON/OFF based on your led connection.

Edit.

If you want the button too change the mode of led blinking, try this.

```
    if (btn_pressed())                  //if btn falling edge detected
        btn_status ^= 1;                //flip the last bit. btn_status += 1; works as well
    if (btn_status & 0x01) led1_flp();  //flip led1
    else led1_off();                    //otherwise, turn off led1

    //flip led2
    IO_FLP(LED_PORT, LED2);

```

the logic is fairly simple: if the button is pressed (active low), toggle btn\_status. if btn\_status is 1, blink the led1.

basically, press the button, led starts to blink; press the button the 2nd time, led stops to blink;

led2 is always blinking, to show concurrency of the code.

here it goes in action.

the code is written for a pic but basically runs on any mcu.
> 1 votes

---
Tags: arduino-uno, led, button, resistor
---


title: ESP01 unsuccessful code execution

text:
# Question
Title: ESP01 unsuccessful code execution
I am trying to upload the Blink example from the Arduino IDE to a ESP8266-01 module using an Arduino Uno as serial programmer. Now, the upload is successful but, upon restart (and disconnecting GPIO0 from GND), nothing happens.
I have tried with different example sketches but it seems code was not uploaded.

My Board manager configuration

* Board: Generic ESP8266 Module
* Flash mode: QIO
* Flash frequency: 40 MHz
* CPU frequency: 80 MHz
* Flash size: 1M (128K SPIFFS)
* Debug port: Serial
* Debug level: none
* Reset method: ck (tried nodemcu too without success)
* Upload speed: 115200
* USB port

As an addition, here's what I get from the ESP01 through the Arduino IDE Serial monitor:

```
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
e:
 ets Jan  8 2013,rst cause:3, boot mode:(3,7)

ets_main.c

```

and here's the IDE console window output:

```
sptool.py v1.3
Connecting..........
Auto-detected Flash size: 8m
Running Cesanta flasher stub...
Flash params set to 0x0020
Writing 229376 @ 0x0... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x0 in 39.0 seconds (47.0 kbit/s)...
Writing 229376 @ 0x10000... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x10000 in 39.0 seconds (47.0 kbit/s)...
Leaving...

```

The sketch I am using

```
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

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

```

# Answer
> 0 votes
If you are using an ESP01 I don't think you should be using GPIO1 as the output pin, its my understanding that they don't have GPIO1.

I think they have GPIO0 and GPIO2, so you should have attached the LED to GPIO2 and use `digitalWrite(2, HIGH);` in you code.

Have a look at this page and see if what its on about is what you are trying to do.

http://iot-playground.com/blog/2-uncategorised/38-esp8266-and-arduino-ide-blink-example

---
Tags: arduino-ide, esp8266
---


title: FFT library for Arduino 101?

text:
# Question
Title: FFT library for Arduino 101?
I am currently trying to get a real-time FFT working for a project on an Arduino 101 which uses the Intel Curie chip. All the FFT libraries (if any) seem to be for the Arduino Uno and architecture dependent (most of them have assembly stuff for optimization).

I was wondering if there is any robust, up do date and most importantly working (with the latest Arduino 101) library. I have tried the PlainFFT library which I read might be compatible with the Arduino 101 (https://forum.arduino.cc/index.php?topic=409791.0).

However this library seems to be out of date, using old extensions of sketch files and old library names in its code (I could not get it to work). Alternatively I wanted to try and tailor a pure C code such as https://github.com/jtfell/c-fft, which seems to have its own Makefile for compilation (this one uses a C99 compiler). I could compile and use this code on a Linux terminal but I am not sure how to go on about making it run inside an Arduino sketch.

# Answer
> 1 votes
I used lightweighted **KissFFT** (Mark Borgerding) at Arduino Mega and seems it is pure C code so should be running anywhere.

---
Tags: library, 101
---


# Question
Title: Increase IR transmitter directivity and range
I am working on a project to control different devices with arduino and IR LED so I am testing with this circuit:  So, everything is working fine but I want to increase range of my transmitter. For now its barely giving response at 1 meter distance. **I want to increase this to at least 5 meters**. I tried to increase receiver sensitivity by giving 5V to TSOP, when I do this the range is satisfactory but the directivity is too much its even responding when I point IR LED in opposite direction(inside a room, maybe the radiaton is bouncing off walls - this is not happening with 3.3V). I Know the transmitter range can be increased by increasing the current flowing through LED like this (please correct me if I am wrong):  The problem is with directivity of emitter, I do not want all the devices in my room to turn on when I try to turn on my TV. **The devices are placed up to 1 meter apart and the transmitting range should be at least 5 meters.**

* Also it would be helpful if someone clarifies which part is actually sensitive (the part which looks like LED or the flat backside part - image below) for TSOP i.e. which part receives the pulses, so that I can cover it with tape (so that it receives signal from only one direction) if nothing else works.

Any help is appreciated, thank you.

# Answer
The IR sensors are usually build that way, that they get signal from as wide range as possible, also using walls, ceiling etc. to reflect the signal to receiver - the bussiness logic is simple - user want press buttton and have TV reacting - no trying to hit some particular spot on TV wiht invisible light - it is not shooting game, it is meant as remote switch and if it works regardless actual direction, then the best. To select different devices the transmiter sends different codes - every device in room ideally gets the same input, just the TV "knows" it should react say to range 0xFF0000..0xFF00FF and the radio knows it should react to 0xFF1100..0xFF11FF instead (it is more conplicated and the ranges are not continuous and possibly ovelaps, but it is the principle).

So the best way to difference between your devices is using longer numbers and let the device react just to some selected (specific to that device) and ignore all others.

But if you insist on "shooting it directly to head", then the way is putting both the transmitter diode and the receiver to some kind of tubes (like bore of riffle), so the data could be only send to /get from some small cone of space and communication occures only when those cones are aligned. Anyway it would probabelly react on the reflection from the wall on your back (shooting cone opposite way) as then the cone will get way larger by distance (and so hit more receivers) and also from difraction from particles in the wall (so the wall would light to all directions, not just reflect the cone, as mirror would). And there is nearly nothing to prevent this. (Yes, you can cover the wall with some nonreflective black textile or so, but would you do it?)

---

As for active part of the receiver, the datasheet say the center of sensiteve area is in the centre of the "diode-like" part, with angle around 80 of sensitivity to both sides vercically and horisontally (with the best sensitivity vaguely straight forward) http://html.alldatasheet.com/html-pdf/26589/VISHAY/TSOP1738/1117/6/TSOP1738.html \- but basically it can somehow receive nearly from anywhere on the "diode-like" side.

The back side (flat one) should not be sensitive.

---

Also you can (and should) use resistor between the pin and transistor base, to limit current from the pin. (transistors have gain like 100 or more, so you need a little current to fully open it).

---

LEDs are current consumers, not voltage consumers, so you restrict current (not voltage) thru your LED to not burn it and to make it shine more or less. LEDS should use current sources (like providing 20mA, no more or less for normal LED), not voltage sources (which would provide something like 9V, 5V, 3.3V or any other value, no more or less).

But as there are much more easily obtained voltage sources, the resistors are use to limit current thru the LEDs as easy "cheat".

You take the voltage of source (say 9V), substract all known voltages around the path (typically 0.7V for transistors, 1.2V for LEDS and so) and suppose the rest is wasted on the resistor. Knowing maximum alloved current for your LED (typically 20mA for "normal one") you compute value of resistor by dividing voltage (in V) by current (in A) to get resitance (in Ohm).

In your picture: 9V-0.7V-1.2V=7.1V on resistor, 7.1V/0.02A=355 Ohm. You take any resistor equal or larger than that and it would be safe to shine for infinity.

First cheap IR LED I found have typical continuous current 20mA, Absolute Maximum Ratings at Ta=25℃ (room temperature) is current 100mA and Peak Forward Current (1/10 Duty Cycle, 0.1ms Pulse Width) 1A. But those Absolute values are values, where you probabelly will destroy the LED soon, as any temperatue higher (as in summer) moves them down fast. You should read "Absolute Maximum Ratings Values" as "values, which can destroy it randomly any moment, if I get near to them" rather than "manufacturer recomed it for extreme usage". (you cannot make perfect laboratory conditions for any device in normal use).

But if you want to make extra power on the risk of destroying the LED, you can set the resistor as low as 7.1V/0.1A = 71 Ohm or even for short pulses 7.1V/1A=7.1 Ohm, but I would bet, that the LED will burn soon anyway. I myself would risk like 80 Ohm in short pulses, but it does not get as much more light as it get in heat. Consult you datasheet and try only on your own risk.

---

**TLDR:** I suggest using unique codes by your Arduino sender for diferent receivers, because you cannot reach you goal other way with good certainlity.

Use your receiver to scan all usual remote controllers you have, then select something totally different for your Arduino receivers.
> 1 votes

---
Tags: ir
---


# Question
Title: Advice needed, commercializing an Arduino Due project
We have a project using an Arduino Due, and we are looking to commercialize the project. How would one typically proceed? Would you use the Arduino Due inside the project? This seems very amateur. Using another Arduino is not an option due to the number of interrupts, number of pins, and processing power required. Thanks!

# Answer
> 1 votes
Depends on the kind of project you are doing. If the Due is just minor part (say you are producind 3D printer) and you plan to do like tens of the devices, I would consider using it, but probably would solder it in for good contact reliability. Maybe put it inside a box too, so nothing can short anything on the board. (And then the Due is not in plain sight).

If it is mainly Due with some sensors around and you want to sell thousands of them, then I would make extra PCB for it, containing everything what is possible on one board. (Like @Majenko suggested.)

Anyway I made a lot of PCB in my kitchen (yes, literally) for my "Arduino" projects, even when I made only 1 or 2 devices just for me. Every of them worked just fine. It is not so dificult to do if you are not pushing some limits too hard. Even Due small chip can be soldered by hands and with some basic tools on your eating table.

But if you lack the skills, hiring contractor (or found company, which does that) may be cheaper in terms of your time and number of devices destroyed before getting the skill and customers complaining about devices broken after short time use.

# Answer
> 2 votes
There's two routes you can take.

First route:

1. Get the Due schematics.
2. Remove the parts you don't need.
3. Add to it the new components for your product.
4. Lay out the PCB design.
5. Get the PCB manufactured.
6. Solder all the components on.
7. Test it and go back to step 2/3 as required.

Second route:

1. Hire a contractor that knows the SAM3X and can do it all for you.

---
Tags: arduino-due, electronics
---


title: Change conditioning in real time

text:
# Question
Title: Change conditioning in real time
I am currently writing a program that reads an output voltage from a capacitive moisture sensor and depending on the moisture content, it will water some plants accordingly. I would like to make it so that a user can change the condition in real time because different plants will require different amounts of water. This will give a little more freedom on how much water the user would prefer for their plant. This is the code I have so far:

```
int solenoidPin = 4; //connected to Digital 4
int moisturePin = A0; //connected to Analog A0

void setup() {
  Serial.begin(9600);
  pinMode(solenoidPin, OUTPUT);
}
void loop() {
  int val;
  moisture = analogRead(moisturePin); //connect sensor to Analog A0
  Serial.println(val); //print the value to serial port
  delay(1000); //wait 1 second for next reading

  if (moisture <= 350) //if moisture is less than reading 350 {
  digitalWrite(solenoidPin, HIGH); //switch solenoid ON
  delay(600000) //water for ten minutes
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
}

```

I am aware that there is a touch screen shield for the Arduino and I could possibly allow the user to interact what is going on. However, I'm just asking if it's possible to change the `if (moisture <= 350)` while the code is running and perhaps allowing the user to change that value. If so, then how? Could I use a touch screen shield or another shield that allows a user to change the condition?

# Answer
> ```
>   if (moisture <= 350) //if moisture is less than reading 350 {
>
> ```

That is wrong, because you have the brace `{` **after** the comment. You need it **before** the comment, eg.

```
 if (moisture <= 350) { //if moisture is less than reading 350

```

Or preferably in my opinion:

```
if (moisture <= 350) //if moisture is less than reading 350
  {

```

---

> I'm just asking if it's possible to change the `if (moisture <= 350)`

Yes, of course. That's what variables are for. You could read a potentiometer, and the value from that could replace `350` in the code. You could use a simple LCD or LED display to show what the current reading is.

---

> delay(600000) //water for ten minutes

Your problem here is that the sketch will be totally unresponsive (it would not react to your changing the moisture level) during the time you are watering. You might want to read How to do multiple things at once which shows how you can keep doing other things, while waiting for time to elapse.
> 1 votes

---
Tags: sensors, shields
---


# Question
Title: Open video file if sensor reaches certain threshold value
I am an ABSOLUTE beginner at Arduino and my first project I've proposed to my teacher is as follows: an Mq-2 smoke sensor will sense smoke and if the level of smoke reaches a certain value (only because I want the smoke to accumulate for aesthetics purposes) then a video file in whatever directory opens and plays. It seemed plausible at first, but as I search for pertinent info., I am faced with content and hobbyists whose instructions and "knowledge" are way out of my depth. Can anyone help me with this? If anyone knows a good website/tutorial videos/documents/books that a beginner like me should take to improve his programming and physical computing(?) skills, please let me know!

# Answer
What I'm thinking is that you could make a conditional statement. Below is a little a bit of pseudo code on how to possibly open said video from an SD card because there's no way Arduino would be able to store a video on it's own, let alone play good quality videos:

```
int dangerLevel = 500 (or however the shield reads the smoke level)

int smokeDetectorPin = A0

setup:

smokeDetected = analogRead(smokeDetectorPin)

loop:

if smokeDetected >= dangerLevel:

open video from SD card directory or computer.

```

So in order to get a "video" from the SD card, you should check this website. Like I mentioned before, this is really primitive and it's probably not what you're looking for.

I found something very interest about the Arduino that I never knew you could do before and using composite display from a TV. Interesting and you can find that info here.

And lastly, to get a video from your computer or laptop, there's really no easy way. However, I did find two solutions that might be able to do this. First of all, and this may sound ironic since we're on an Arduino Stackexchange, you could use a Raspberry Pi (and this is the easily solution I can think of) though I believe your instructor prefers if you use the Arduino instead. Second, and this took me forever to find on the internet, you could use a third party software called "Gobetwino" and you can check out what that does here. I saw on YouTube video of a quick little demonstration of what it does. When the button is pressed, the video is played. That's conditional and you can do the same thing but for the smoke detector.
> 1 votes

---
Tags: sensors
---


# Question
Title: My Digispark board won't show up in Ports tab in Arduino IDE (OSX)
I bought a Digistump/Digispark board online and when i received it, I plugged it into my iMac to see if it works. I went to the apple in the top left corner and clicked "About this Mac". Then I clicked "System Report" and I went to the USB tab and it showed something connected as:

```
"Vendor-Specific Device:"

```

I was glad that it showed up but when I went to the Arduino IDE it didn't show up in the ports tab. I downloaded the AVR pack and the driver (i'm pretty sure the driver should work, if there is a specific driver that will work could someone send me to it) I am really frustrated and mad because it seems like this always happens. If someone could help me that would be greatly appreciated! Thank You.

```
Atmel 1624 tiny85

```

# Answer
> 6 votes
I don't think it is supposed to. The Digispark briefly connects in "bootloader" mode, which you spotted as "Vendor-Specific Device:".

Then after 5 seconds it runs the loaded sketch. If your sketch doesn't create a USB port (eg. a keyboard) then it will disappear from the USB list.

See:

http://digistump.com/wiki/digispark/tutorials/connecting

You don't select the port, the core files automatically find the Digispark and program it. You have to plug in the Digispark when instructed, to activate the bootloader.

---
Tags: usb, avr, compile, digispark
---


# Question
Title: Why is the piezo buzzer not making any sound?
My ciruit:

My code:

```
// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   tone(12,260);
  {
 }
  }
}

```

What I wish to do, is that when the button is pressed, and the Led's start to blink, I want the piezo buzzer to make a sound. I have never worked with them before so I am having troubles getting results. Is it that the setup is wrong or the code needs extra lines than just the `tone(12,260);` that I added?

# Answer
Both the code and the circuit have problems.

In the code:

• If the `while (buttonState == LOW)` loop is ever entered, it will never be left, because `buttonState`, the controlling variable, does not change within the loop.

The simplest fix is to remove the line `bool buttonState = digitalRead(buttonPin);` and replace `while (buttonState == LOW)` with `while (!digitalRead(buttonPin))`, which says to loop while `digitalRead(buttonPin)` is not true; ie, while it is false, or low.

• The empty braces, `{ }` at the end of the `while` loop are superfluous and should be deleted.

In the circuit diagram:

• Neither of the leads of the buzzer is attached to the Arduino circuit, so it won't make any sound. Note, `tone(12,260);` tells the Arduino to use pin 12 for tone output.

To fix this problem, run a wire from pin 12 to one side of the buzzer, and a wire to ground for the other side of the buzzer.

• A blue LED in series with a red LED might or might not turn on when supplied with 5 V. For example, if the red LED takes 1.8 V and the blue LED takes 3.3 V to turn on, the 5.1 V total is too high to be turned on by 5 V signals. Remove one of the two LEDs, and move the wires to the other LED to complete a circuit.
> 2 votes

---
Tags: arduino-uno, led, button, sound, piezo
---


# Question
Title: 5V usb surge protection for circuit board?
I want to use a mini usb jack to power my device off board, but I want to make sure that the usb power coming in is not any higher than the 5V. I've read a bit about polyfuses but I am unsure if they would be useful for this scenario. Thanks!

# Answer
> 4 votes
A polyfuse will limit **current** not voltage.

There are transient protection diodes which switch on if voltage exceeds a given level, which are often used in conjunction with a polyfuse. The diodes cause excessive current to flow, effectively turning on the polyfuse for extended overload, or just absorbing shorter transients. The Raspberry Pi uses a SMBJ5.0A device to suppress transients.

You should NOT need any of this if you use a reasonable power supply.

# Answer
> 0 votes
I second Milliways answer:

> You should NOT need any of this if you use a reasonable power supply.

Anyway, if you really have a crappy power supply you can use one of the modules you find on ebay (for instance this is the first result I came across). Be sure to look for "buck boost" modules (step up/down), because they can both raise and lower the voltage.

This will do the job your power supply is not able to do, so to give you a stable voltage. You can then also vary the voltage without worrying (they usually are able to handle 4V (e.g. lithium batteries), 7.2V (e.g. 2 lithium batteries), 12V, ...

If you want also reverse protection, I suggest you to simply put a diode in series with THE INPUT (anode on the positive of your power supply, cathode on the IN+ terminal of this regulator). This way the voltage drop will be absorbed by the regulator. You can use a cheap 1N4007 or even a Schottky diode (which have less drop -\> better power consumption).

I discourage you from using a full wave rectifier, since the diodes on the ground will change the ground reference (and so if you connect something else you may experience problems).

You can find a lot of "buck/boost" modules out there, just check that the input and output voltages and currents are suitable for your project.

But again, unless your power supply is really crappy you won't need this. If you just need an inversion protection, you can also use a circuit I found on a PC : put a fuse (they used a real fuse, you can use a polyfuse) between the power positive input and the circuit positive, then add a diode with the anode to ground and the cathode to the circuit positive. If you attach it correctly the diode will be reverse polarized and the circuit will work correctly, if you attach it in reverse the diode will conduct and so will create a large current which will trip the fuse.

---
Tags: power, usb, current
---


title: I2C between 2 or more Arduino boards

text:
# Question
Title: I2C between 2 or more Arduino boards
HELLO I have already connected with I2C 2 Arduino's all is working with comunication on Bus I2C. My Setup is : MASTER with LCD I2C , RTC1037 SLAVE some sensor not I2C

I allready put 2 pullup resistor 10Kohm on SDA and SCL

I need to switch off the slave arduino but when i switch off the Slave board the Master Arduino stop working.Why? It's possible to continue working with master board and the slave board switch off? Thank's for help

# Answer
You need to isolate the slave device from the I2C bus since it is causing interference with the signals.

Adafruit have published a good application note about level shifting in I2C busses using MOSFETs, and it also contains a bit about bus isolation:

> **2.3.4 Isolation of the powered-down “Lower voltage” section.**
>
> An additional feature of the level shifter circuit in figure 2 is the isolation of the “Lower voltage” section when VDD1 is switched off. In that case VDD1 is about 0 Volt and the MOS-FET’s \[sic\] are switched off because VGS is below the threshold voltage. The “Higher voltage” section is not hindered and stays operational. To assure a noise margin, the MOS-FET’s should have a minimum threshold voltage VGS(th) of e.g. 0.4V and VDD1 must stay below this value. The isolation feature can also be applied if no level shifting is required, VDD1 and VDD2 may have the same value, e.g. both 3.3V or both 5V.
> 0 votes

---
Tags: i2c
---


# Question
Title: CAN-Bus shield, SD-card module & LED_BUILTIN use D13; possible collision?
To my knowledge the SeeedStudio CAN-Bus shield utilizes D13, and so does the SD-card module I use. And also Arduino Uno's LED\_BUILTIN is 13. **Am I in danger of some sort of collision here?**

I have read this question, but that one describes situation where both modules are on *a single shield.*

Why I am alerted: I can perform following sequence: turn the LED on, open file, write, close file, turn the LED off, no apparent problem here. But when I connect my CAN-Bus shield to merely read messages (i.e. no sending data to the shield, not on purpose) my car behaves funny as if I still somehow managed to send some rogue bytes to the shield. (Right side windows and mirror are dead, infotainment display shows dead splash screen, dashboard complains about "engine malfunction" and airbags...)

I wonder if by writing to the SD-card and possibly turning the LED on I didn't send some bytes to the shield. Do I need to somehow Select Slave?

# Answer
> 1 votes
Yes you are in danger of a collision, how much danger I can't say, but the potential is there.

1. You could stop using the LED on D13?
2. Could you move the pins of your SD card reader, or get a different one that allows I2C or SPI interfacing?

I guess there is nothing that can be done to the CAN bus device, but if there is it might be a good idea to move its pins.

---
Tags: communication
---


# Question
Title: Arduino LCD Display 2x16 custom char byte limit
Some years ago I stumble with a problem while using the 2x16 LCD. What happened was that there was a limit to how may byte arrays I could declare. So my project came to a halt because I needed to create more custom characters to advance any further...

The lcd accept custom characters to store them but I suppose there is a limit to this, am I wrong?

I'm trying to create a set of custom characters that move on screen. Since there are a lot of animations I need several of them to have a smooth animation. The problem resides in the limit of characters I can pre-establish after executing lcd.begin()

I don't post code because to my understanding that is not relevant and because sincerely is a crap since I wrote it down when I was learning programming some years ago. I want to resolve this so I can rewrite the code.

LCD version: QAPASS 1602A

Here is an example:

byte Ghost\[8\] = { 0b00000, 0b01110, 0b01110, 0b10101, 0b11111, 0b11111, 0b11111, 0b10101 };

lcd.createChar(0, Ghost);

So the right question is: Do I need to reset the LCD chip then declare the new characters to the lcd to make it available? How?

# Answer
> there was a limit to how may byte arrays I could declare.

If the problem was that you ran out of free RAM, then the fix is to move those byte arrays into program space.

Atmega 328 processors (Uno) are very RAM-limited. Fortunately you can assign constant data - fixed character strings, lookup tables for math, fonts, CRC calculation, etc - to be stored in program space which is much more generous. The upside is you can free lots of RAM in an application like yours that needs lots of constant data. The downside is that access to the data is a little bit slower:

```
// Definitions for data in program space
#include <avr/pgmspace.h>

// Place the character table in Flash
byte const Ghost[8] PROGMEM = {
   0b00000,
   0b01110,
   0b01110,
   0b10101,
   0b11111,
   0b11111,
   0b11111,
   0b10101
};

// Read a byte of character data
OneByte = pgm_read_byte(&Seg7_segtbl[index]);

```

Update:

> LCD version: QAPASS 1602

If that has an Hitachi HD44780 controller on it, its datasheetsays it has a 64-byte character RAM - more than enough for a full display of 2 x 16 unique characters, but if you need a wider choice of characters than a set of 64, you may need to re-load the RAM with a custom sub-set for any given screen-full. For animating, though, you'll probably need all of the individual parts of each animation in the LCD RAM at once; reloading during animation will most likely disturb the smoothness. One possibility is to load part of a subset between animation frames - if that's even possible. (I haven't studied this controller to that level of detail).
> 1 votes

---
Tags: arduino-nano, lcd
---


title: Simple memory chip for Arduino?

text:
# Question
Title: Simple memory chip for Arduino?
My basic question is: **What is a good alternative to EEPROM chips for external memory on the Arduino Unor R3?**

I know that there are EEPROM chips when one would like an external memory chip. It, in fact, seems like this is the standard choice. I am wondering if there are any other good ways to work with external memory. Are there, for example, memory chips that work a bis simpler? Like, a chip that doesn't require any specific libraries in the Arduino?

(I do not have extensive experience working with the Arduino.)

# Answer
There is no DRAM, SRAM nor flash interface in ATmega, so you can't extend your chip memory. You can only connect serial (SPI, I2C) or parallel memory (usind GPIO).

Neither SPI nor I2C require any specific libraries. SPI is much simpler to program than I2C and much faster, but require more wires.

Instead of using rather slow EEPROM, you can try FRAM (non-volatile) or SRAM (volatile, but may be battery-sustained). They are usually available with the same interface as EEPROM, but don't suffer from limited number of erase cycles. FRAM can withstand ridiculous number of erasures, SRAM is virtually indestructible.
> 7 votes

# Answer
No. There is no external memory interface on the ATmega328P, so all external memory requires some sort of library to use.
> 5 votes

# Answer
Personally I like the Amtel 24C256 chip/module. It is I2C enabled and the standard Wire library is all you need to talk to it. It is 256 bits or 32K 8 bit bytes in size. Data is sent and read in byte chunks. Addressing is at the bit level. It can run on 3.3V and 5V. Ebay has a bunch of suppliers for it. There's a number of good How-To's on line.
> 5 votes

---
Tags: arduino-uno, memory
---


# Question
Title: I2C Wire.write function doesn't seem to work
Using the simplest code possible to test the library:

```
#include <Wire.h>

void setup()
{

  Wire.begin(); // join i2c bus

  Wire.beginTransmission(44); // transmit to device #44 (0x2c)
                              // device address is specified in datasheet

  Wire.write(0xA);             // sends value byte
  Wire.write(0xA);             // sends value byte
  Wire.write(0xA);             // sends value byte

  Wire.endTransmission();     // stop transmitting
}

```

But my data (three test byte of 0xA) is not getting sent. See image. As you can see, I get start bit, address, and then the stop bit. No data. Where am I going wrong?

# Answer
> 2 votes
According to the captured communication `NACK` was received (confirmed in comments) and according to the `Wire` library `twi_stop` will be called (and sent) in this fault scenario.

```
case TW_MT_SLA_NACK:  // address sent, nack received
  twi_error = TW_MT_SLA_NACK;
  twi_stop();
  break;

```

# Answer
> 2 votes
It looks like you have code for an I2C master. Sending to a slave involves sending the slave address, and waiting for an ACK from the slave (that is, the addressed slave pulls the data bus low).

You can see that in a graphic from my page about I2C:

At the 100 µs mark you can see that the slave pulls SDA low, which is an ACK. Thus the master knows that the addressed slave exists. Without that, the slave is not there, and there is no point in sending any further data.

# Answer
> 2 votes
OK, I figured out what was going on...

An example program that I downloaded to test the hardware was sending a "self address" command to the chip, which was causing the address to get set to 0x03 and I didn't notice this. This new address stays in memory. So, when I went back to test the library code, I was sending 0x00 (default from factory) instead of the new address (0x03). The NACK after the address byte should have been a clue, but hey, live and learn.

Thanks for all the responses. Hopefully my pain will help someone else.

---
Tags: i2c, wire-library
---


# Question
Title: error: 'CLASS' does not name a type only when creating object inside another object
I'm trying to use Adafruit's LED Backpack library within a custom class. When I use the Adafruit library directly within a sketch, it compiles fine. When I use an example sketch provided with the library, it compiles fine. However when I create an instance of my custom class with the Adafruit object within it, I get the following error:

> In file included from sketch\_feb18a.ino:6: /Users/lawnmowerlatte/Documents/Arduino/libraries/Bargraph/bargraph.h:18: error: 'Adafruit\_24bargraph' does not name a type

All the reasons I've seen for this error stem from the library being missing or otherwise incorrectly installed. However, since I can use it directly, I think something else must be wrong.

**Working**

```
#include <Adafruit_LEDBackpack.h>
#include <Adafruit_GFX.h>
Adafruit_24bargraph bar = Adafruit_24bargraph();

void setup() { }
void loop() { }

```

**Not Working**

```
#include <bargraph.h>
Bargraph bargraph = Bargraph("Test", "api", 0);

void setup() { }
void loop() { }

```

**bargraph.h**

```
#ifndef Bargraph_h
#define Bargraph_h

#include <Adafruit_GFX.h>
#include <Adafruit_LEDBackpack.h>

#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

class Bargraph {
  public :
    String name;
    String api;
    Adafruit_24bargraph bar;

    Bargraph(String _name, String _api, int _device,
        String _type="Default");

    void set(String _value);
    void setMax(String _max);
    void update();
    void print();

  private :
    int display[24];

    long max;
    long value;
    int device;
    int size;
    String type;

    void format();
    void write();
};

#endif

```

**bargraph.cpp**

```
#define OFF 0
#define RED 1
#define YELLOW 2
#define GREEN 3

#include <bargraph.h>

#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

Bargraph::Bargraph(String _name, String _api, int _device, String _type) : bar() {
    name        = _name;
    api         = _api;
    max         = _max.toLong();
    device      = _device;
    type        = _type;
    value       = 0;

    for (int i=0; i<24; i++) {
        display[i] = OFF;
    }

    bar.begin(0x70+device);
}

**Methods Omitted for Brevity**

```

Can anyone explain what's going on here? I'm pretty certain my class syntax is correct as I have other object-in-object relationships working. I can post code to GitHub if anyone would like to see more context.

# Answer
I think these lines still need to be in your main sketch file (in addition to being in your custom class file):

```
#include <Adafruit_LEDBackpack.h>
#include <Adafruit_GFX.h>

```

If I remember the Arduino IDE quirks correctly, it uses the `#include` directives in the main sketch file to determine which libraries to actually link. It's one of those annoying features that was intended to be beginner-friendly but sometimes just makes things more confusing.
> 3 votes

# Answer
If you used the serial port, Arduino sometimes causes confusion. Close Arduino IDE and delete files in folder C:/users/\[your name\]/AppData/Local/Temp/ Its working. Regards
> 1 votes

---
Tags: arduino-mega, library, compile, adafruit, class
---


title: Program Arduino Uno via Nano

text:
# Question
Title: Program Arduino Uno via Nano
To keep the question short:

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

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

```
Nano.Pin   Uno.Pin

10         Reset

11         11

12         12

13         13

GND        GND

```

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

---
Tags: arduino-uno, arduino-nano
---


# Question
Title: Is EEPROM's location relocated on sketch compile?
I assumed the microcontroller has 3 components as per storing data: \- flash memory for the program \- RAM for variables \- EEPROM for non-volatile user-storage

And I always assumed those are separate chips on the board. However, working directly with a RobotDyn Uno R3 leads me to believe I may be wrong somehow.

I compiled this program:

```
#include <EEPROM.h>

struct SettingsStruct {
  String server;
  String port;
  String user;
  String password;
  String description;
} gSettings = {
  "192.168.1.6",
  "8080",
  "fci blah vlak",
  "zangazang4",
  "Extra string here"
};

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

  //saveConfig();

  Serial.print(F("EEPROM size is: "));
  Serial.print(EEPROM.length());
  Serial.print(F(" bytes"));
  Serial.println("");

  loadConfig();
  Serial.print(F("Server: "));
  Serial.print(gSettings.server);
  Serial.println("");
  Serial.print(F("Port: "));
  Serial.print(gSettings.port);
  Serial.println("");
  Serial.print(F("Username: "));
  Serial.print(gSettings.user);
  Serial.println("");
  Serial.print(F("Password: "));
  Serial.print(gSettings.password);
  Serial.println("");
  Serial.print(F("Description: "));
  Serial.print(gSettings.description);
}

void loop()
{
  // nope
}

void loadConfig() {
    for (unsigned int t=0; t<sizeof(gSettings); t++)
      *((char*)&gSettings + t) = EEPROM.read(t);
}

void saveConfig() {
  for (unsigned int t=0; t<sizeof(gSettings); t++)
    EEPROM.write(t, *((char*)&gSettings + t));
}

```

Problem is that each time I add new elements to the struct, and I run the program, the serial prints different things. I recognize previously saved strings but they are right shifted, meaning that somehow the ZERO address of EEPROM might have moved backwards and previously saved strings move right and offocurse, appear on other struct variables.

This leads me to believe the actual EEPROM is related with the flash memory and depends on it on each compile. As if the ZERO address of EEPROM is established after each compile.

Can anyone confirm this or lead me to some documentation relating this? It's a weird mystery that I would like to clear out.

# Answer
The EEPROM is a completely separate part of the silicon inside the chip. It has no address of its own.

You are making a fundamental error in what you are doing, though - you cannot directly store the contents of strings by looking at the addresses of those strings. The data in them is dynamically allocated in RAM and is completely separate from the object. You will have to come up with a different way to store your data.
> 1 votes

---
Tags: eeprom
---


# Question
Title: How to do weigh scale zeroing (tare weight)?
I'm using the sketch below for a weighing scale. The sketch prints out the load-cell voltage just fine. I can't figure out how to let the scale run a couple seconds to stabilize, then use the current voltage reading (nothing on the scale) as the "Zero" voltage. Then subtract that "Zero" voltage from future readings to get the actual voltage for any weight placed on the scale. For example, let's say the nothing on the scale voltage is 0.5 volts. Then a 10 LB weight is added and the voltage goes up to 1.5 volts. So the actual voltage increase from the weight is 1.5 minus 0.5, or 1.0 volts.

```
#include <ads1262.h>

const float VREF = 2.50;  // Internal reference

ads1262 PC_ADS1262;  // ADC object

void setup() {
  // initialize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
  pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
  Serial.begin(9600);

  // initialize ADS1292 slave
  PC_ADS1262.ads1262_Init();
  Serial.println("ads1262 Initialised successfully....");
}

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
                  | (uint32_t) buffer[2] << 16
                  | (uint32_t) buffer[3] <<  8
                  | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;

  // Report a smoothed-out reading.
  Serial.println(voltage, 8);
}

```

# Answer
You start out with a variable named Tare initialized to zero `float Tare = 0.0;` put in a conditional like `if (millis() > 2000 & Tare == 0.0) Tare = voltage;` and always report `voltage - Tare`.

```
float Tare = 0;

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;
  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
    | (uint32_t) buffer[2] << 16
    | (uint32_t) buffer[3] <<  8
    | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;
  if (millis() > 2000 & Tare == 0.0) Tare = voltage;
  // Report a smoothed-out reading.
  Serial.println(voltage-Tare, 8);
}

```

If you want to make it smarter, add a button for tare and maybe if you have a calibration weight, add a button for calibrating.

```
float scale= 1.0;
const float calib_weight = 500.0; // grams?
...
if(tareButton | (millis() > 2000 & Tare == 0.0)) Tare = voltage;
if(calibrateButton) scale = calib_weight / (voltage-Tare) ;
...
Serial.println((voltage - Tare)*scale,8);
...

```
> 1 votes

# Answer
The direct answer to your question is to wait for the scale to settle and store the Tare voltage; then subtract it from future readings.

But that only works if the scale's transfer function (Voltage as a function of weight, or V(f)) is linear (weight = Voltage * CONSTANT). Otherwise you need to keep the Tare in weight units, do the full conversion of voltage to weight on subsequent readings, and subtract the Tare weight from that.
> 0 votes

---
Tags: arduino-uno, programming
---


# Question
Title: SparkFun Monster Moto Shield current sensing issue
I am using a SparkFun Monster Moto Shield (PDF) for driving two DC motors. The shield is working fine and I am able to drive the motor in both directions. However, the current sensing is continuously showing "zero" in the serial monitor.

I am confused why the shield is not measuring any current. I want to measure normal current of 750 mA and stall current of 6 A but I'm getting zero value continuously. If anyone can help me I shall be very thankful.

# Answer
> 1 votes
Can you show us how your code is looking like? Please remember that you can not measure current directly, the method that is used to do that is to measure voltage drop on measuring resistor.
Check this image

---
Tags: sensors, current
---


# Question
Title: Arduino interrupt not called using PinChangeInterrupt
I am new to Arduino and I was trying to figure out how to use an interrupt. When I ran this it would read my magnet but the interrupt would never be called and I couldn't figure out if anyone can help me that would be great.

Thanks.

Here is the code

```
#include <PinChangeInterrupt.h>

//#define INTERRUPT_PIN 12
#include <Math.h>

#define RADIUS 3
const int hallPin = 7; // the number of the hall effect sensor pin
const int ledPin =  13; // the number of the LED pin
// variables will change:
int hallState = 0; // variable for reading the hall sensor status
double inital_val = 0.0;
double distance = inital_val;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  //attachInterrupt(hallPin, calc_distance, HIGH);
  // initialize the hall effect sensor pin as an input:
  attachInterrupt(digitalPinToInterrupt(hallPin), calc_distance , HIGH);
  Serial.begin(9600);
}

void loop() {
  //read the state of the hall effect sensor:
  hallState = digitalRead(hallPin);
  if (hallState == LOW) {
    // turn LED on:
    Serial.print("Main Loop: HallState LOW\n");
    digitalWrite(ledPin, HIGH);
    Serial.print(distance, 2);
    Serial.print("\n");
  } else {
    Serial.print("Main Loop: HallState HIGH\n");
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

void calc_distance() {
  Serial.print("INTERRUPT! \n");
  if (digitalRead(hallPin) == HIGH) {
    Serial.print("YES!\n");
    distance += PI * 2 * RADIUS;
  } else {
    Serial.print("NO!\n");
  }
}

```

# Answer
The attachInterrupt function is only for normal interrupts. Read the reference: attachInterrupt

When you need the Pin Change Interrupts, there is a library for that: EnableInterrupt

Try to keep the interrupt routine as short as possible. Do not use the Serial functions in calc\_distance because the Serial functions themself use also interrupts.

The Arduino Mega does not have 'double' floating point variables, the compiler changes it into 32-bit 'float' variables. You are reading the interrupt pin for a test ? I don't understand why you do that. Please make "distance" a volatile variable. In the loop function, the interrupts should be turned off when reading "distance". Because "distance" is a 4 bytes 'float' variable and the Arduino Mega is a 8-bits microcontroller. An interrupt could occur when the "distance" is only read for a part from memory.
> 1 votes

---
Tags: arduino-mega, sensors, interrupt
---


# Question
Title: Can regular Arduino pins be used during SPI?
I have a circuit in which I'm using an Arduino Pro Mini to interface with an RF69 radio via SPI. The SCK pin on the Pro Mini is pin 13, which also happens to be the LED pin. Is it possible to write pin 13 high and low in the same sketch that I'm interfacing with the radio? I don't need to do SPI communication simultaneously with the LED. I can put the radio to sleep then use the LED. I'm wondering if this will some how mess up the SPI communication or if everything will be OK.

# Answer
> 3 votes
I did not check the datasheet of the RF69, but it is customary for SPI devices to have a “slave select” input pin. When such a device is *not* selected, it will leave its MISO pin in high impedance and completely ignore whatever may happen on the MOSI and SCK pins. This effectively disconnects the device from the SPI bus. In this situation you show be able to play with the LED without disturbing the device.

Beware that the slave select pin is usually active low: write it to `HIGH` to *deselect* the device.

---
Tags: communication, spi, arduino-pro-mini
---


# Question
Title: PCF8563 does not remember time when restarting Arduino Uno?
I'm trying to use the following RTC module (PCF8563) with Arduino Uno.

I am using this library to set/get time and date from PCF8563. However, whenever I shut down the Arduino, the time/date is lost! Even though, as you can see in the picture, the module is equipped with a 3V battery to keep running when Arduino is unplugged.

Any help would be highly appreciated!

# Answer
> 0 votes
\[SOLVED\]

The solution is simply to put a jumper between BAT and VCC positions in the module itself. Many thanks to Edgar Bonet

---
Tags: arduino-uno, time, datalogging
---