title: Error Compiling to Board Teensy LC

text:
# Question
Title: Error Compiling to Board Teensy LC
I wrote a simple switch program using a teensy LC and transistors, but the Arduino compiler will not compile for the Teensy LC. And not for just my program, but any program, including the example programs included in the Arduino. I have tried compiling for other boards and they all compile fine. This problem was also replicated on another computer running Windows 10, I am running Windows 7, with the same error message. The error message and associated code is below, for reference.

```
int led1 = 0;
int led2 = 1;
int led3 = 2;

int input1 = 5;
int input2 = 7;
int input3 = 9;

int bypass1 = 23; //output 1
int toneStack1_1 = 22; //output 2
int toneStack1_2 = 21; //output 3
int bypass2 = 20; //output 4
int toneStack2_1 = 19; //output 5
int toneStack2_2 = 18; //output 6
int bypass3 = 17; //output 7
int toneStack3_1 = 16; //output 8
int toneStack3_2 = 15; //output 9

boolean bypass = true;        //idicators for which mode is active
boolean toneStack1 = false;
boolean toneStack2 = false;
boolean toneStack3 = false;

void setup()
{
  pinMode(input1, INPUT);    //setting inputs
  pinMode(input2, INPUT);
  pinMode(input3, INPUT);

  pinMode(led1, OUTPUT);    //setting outputs
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);

  pinMode(bypass1, OUTPUT);
  pinMode(toneStack1_1, OUTPUT);
  pinMode(toneStack1_2, OUTPUT);
  pinMode(bypass1, OUTPUT);
  pinMode(toneStack2_1, OUTPUT);
  pinMode(toneStack2_2, OUTPUT);
  pinMode(bypass1, OUTPUT);
  pinMode(toneStack3_1, OUTPUT);
  pinMode(toneStack3_1, OUTPUT);

  digitalWrite(bypass1, HIGH);   //sets to bypass mode
  digitalWrite(bypass2, HIGH);
  digitalWrite(bypass3, HIGH);

}

void loop()
{
  input1 = digitalRead(input1);    //reads inputs from pushbuttons
  input2 = digitalRead(input2);
  input3 = digitalRead(input3);

  if(input1 == HIGH && bypass == true) //Bypass to tonestack 1
  {
    digitalWrite(bypass1, LOW);   //turns off bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack1_2, HIGH);

    bypass = false;
    toneStack1 = true;
  }

if(input2 == HIGH && bypass == true) //Bypass to tonestack 2
  {
    digitalWrite(bypass2, LOW);   //turns off bypass transistors
    digitalWrite(bypass3, LOW);

    digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2

    digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
    digitalWrite(toneStack2_2, HIGH);

    bypass = false;
    toneStack2 = true;
  }

  if(input3 == HIGH && bypass == true) //Bypass to tonestack 3
  {

    digitalWrite(bypass3, LOW); //turns off bypass transistor

    digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2
    digitalWrite(bypass2, HIGH);

    digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 3 transistors
    digitalWrite(toneStack3_2, HIGH);

    bypass = false;
    toneStack3 = true;
  }

  if(input1 == HIGH && toneStack1 == true) //tonestack 1 to bypass
  {
    digitalWrite(bypass1, HIGH);   //turns on bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, HIGH);

    digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
    digitalWrite(toneStack1_2, LOW);

    bypass = true;
    toneStack1 = false;
  }

  if(input2 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 2
  {
    digitalWrite(toneStack2_1, HIGH);   //turns on tone stack 2 transistors
    digitalWrite(toneStack2_2, HIGH);

    digitalWrite(bypass1, HIGH); //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
    digitalWrite(toneStack1_2, LOW);

    toneStack2 = true;
    toneStack1 = false;
  }

  if(input3 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 3
  {
    digitalWrite(toneStack3_1, HIGH);   //turns on tone stack 3 transistors
    digitalWrite(toneStack3_2, HIGH);

    digitalWrite(bypass1, HIGH);    //sets bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
    digitalWrite(toneStack1_2, LOW);

    toneStack3 = true;
    toneStack1 = false;
  }

  if(input2 == HIGH && toneStack2 == true) //tonestack 2 to bypass
  {
    digitalWrite(bypass1, HIGH);   //turns on bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, HIGH);

    digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
    digitalWrite(toneStack2_2, LOW);

    bypass = true;
    toneStack2 = false;
  }

  if(input1 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 1
  {
    digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack1_2, HIGH);

    digitalWrite(bypass1, LOW);   //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
    digitalWrite(toneStack2_2, LOW);

    toneStack1 = true;
    toneStack2 = false;
  }

  if(input3 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 3
  {
    digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack3_2, HIGH);

    digitalWrite(bypass1, HIGH);   //sets bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
    digitalWrite(toneStack2_2, LOW);

    toneStack3 = true;
    toneStack2 = false;
  }

  if(input3 == HIGH && toneStack3 == true) //tonestack 3 to bypass
  {
    digitalWrite(bypass1, HIGH);   //turns on bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, HIGH);

    digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
    digitalWrite(toneStack3_2, LOW);

    bypass = true;
    toneStack3 = false;
  }

  if(input1 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 1
  {
    digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack1_2, HIGH);

    digitalWrite(bypass1, LOW);   //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
    digitalWrite(toneStack3_2, LOW);

    toneStack1 = true;
    toneStack3 = false;
  }

  if(input2 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 2
  {
    digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
    digitalWrite(toneStack2_2, HIGH);

    digitalWrite(bypass1, HIGH);   //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
    digitalWrite(toneStack3_2, LOW);

    toneStack2 = true;
    toneStack3 = false;
  }
}

```

And the error message:

```
Arduino: 1.8.4 (Windows 7), TD: 1.38, Board: "Teensy LC, Serial, 48 MHz, Smallest Code, US English"

In file included from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.h:34:0,

                 from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:31:

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp: In member function 'void IntervalTimer::end()':

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:87:20: error: 'IRQ_PIT_CH0' was not declared in this scope

   NVIC_DISABLE_IRQ(IRQ_PIT_CH0 + index);

                    ^

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\kinetis.h:5627:68: note: in definition of macro 'NVIC_DISABLE_IRQ'

 #define NVIC_DISABLE_IRQ(n) (*((volatile uint32_t *)0xE000E180 + ((n) >> 5)) = (1 << ((n) & 31)))

                                                                    ^

Error compiling for board Teensy LC.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

I'm at my wits end trying to figure this out. I have reinstalled the Arduino 1.8.4, reinstalled Teensyduino, installed previous version of Arduino, and rebooting my system. Nothing so far has worked. I feel like there is something I am missing with this, as it seems no one else has my problem, from what I could find. Any help would be appreciated.

# Answer
> 1 votes
I experienced a similar error. Upon further research it seems to be a known issue. I was able to compile using 1.8.2 and Teensyduino 1.36 I accessed 1.36 from downloading the zip file of the pjrc website in the upper right corner. The Link was download website. Then the path was pjrc\_2017\_04\_04\teensy\td\_136

---
Tags: compiler, teensy
---


# Question
Title: I2C from two masters (ATtiny85, ESP8266) to one slave (ATmega328)
I've been working on a project with I2C protocol where an ATmega328 (Arduino) configured as slave, receives messages from an ATtiny (ATtiny85, ATTinyCore by SpenceKonde) configured as master, or from an ESP8266 (ESP-01, Arduino core) configured as master.

All using the standard wire library, powered with 3.3v (LM1117 regulator), SDA and SCL 4.7kohms pull-ups. The ESP pins used are RX and TX, with 330ohms pull-ups.

Individually, it works (ATtiny to ATmega; ESP to ATmega), but when i connect the three on the same bus, after the first message it stops working and the ATmega doesn't receive more messages.

---

Code (modified for readability)

ATmega slave:

```
#include <Wire.h>

const int ADDRESS = 56;

void receiveEvent() {
    Serial.println(Wire.read());
}

void setup() {
    Serial.begin(9600);
    Wire.begin(MY_ADDRESS);
    Wire.onReceive(receiveEvent);
}

void loop() {
}

```

ESP master:

```
#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
const int SDA_PIN = 1;
const int SCL_PIN = 3;

void setup(){
    Wire.begin(SDA_PIN, SCL_PIN);
}

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'e';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(2500;)
}

```

ATtiny master:

```
#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
// SDA = 0; attiny85 pin 5
// SCL = 2; attiny85 pin 7

void setup() {
    Wire.begin();
}

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'a';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(1000);
}

```

---

After some research I found out that the wire library can only work with a single master, is this correct? And the esp can only work in master mode.

Am I doing something wrong, or is this simply not possible?

Are there any protocol alternatives for this design? A single device that only cares about receiving messages, and multiple other devices that only care about sending messages to the central.

Thank you for your time!

# Answer
> 0 votes
The problem is in your implementation. If you REALLY need 2 masters there should be a way to make it work.

At the moment the problem that I can see is that both masters continually poll the I2C data lines, effectively this means that the data on the lines is all mixed up and scrambled together. What could do is have 2 wires connecting both masters. When one of the masters is writing to the slave pull the line high, the other master should read this line as high, and not write data to the I2C lines. When the line drops low, it should then take its turn to write to the AtMega. This method would ensure only one master is using the data lines at one time. The implementation is pretty rudimentary and fairly crude and I'm aware the ATtiny may not have enough pins for this.

The best way to solve your problem I think is to have the ESP8266 as your single master, with your ATtiny and ATmega as slaves. Make the ESP poll the ATtiny for its data/instructions it wants to pass to the Atmega, and get the ESP to pass on this data or instructions to the ATmega along with its own data and instructions. This should be a robust and reliable fix.

# Answer
> 3 votes
If you have 1 receive only device, and 2 send-only devices, why not make the receive-only device the master, but have it poll (periodically, repeatedly ask) the slave devices to send any data they have pending. That way, there is only one master, and it only asks for data when it's ready (that is, not receiving from some other device.)

One purpose of a master/slave bus system is to avoid contention (two or more devices talking at the same time.) The master tells each device when to send, and only listens after it asks.

---
Tags: esp8266, i2c, atmega328, wire-library, attiny85
---


# Question
Title: Voltage on analog pin arduino when arduino turned off
So can I put a voltage from 0v to 5v on an analog Arduino pin before actually turning the Arduino on? And still read the analog pin correctly when turned on?

# Answer
All the GPIO pins have protection diodes in them. The are arranged, effectively, like this:

simulate this circuit – Schematic created using CircuitLab

The internals of the ATMega chip can be visualised for this purpose as a small resistor:

simulate this circuit

If you apply a voltage to the input without anything applied to Vcc you effectively connect the input to ground through the diode and the internals:

simulate this circuit

That means that too much current flows through the diode and potentially breaks it. And that's the least of your worries. The rest of the circuitry in the chip is subject to the same rules - any voltages that can flow back up to the Vcc rail the wrong way through parts of the circuitry in order to get down to ground risk breaking things.

It's almost as bad as connecting the power to the chip backwards. In effect your GPIO pin is acting as Vcc and powering the chip - badly.
> 6 votes

# Answer
> So can I put a voltage from 0v to 5v on an analog Arduino pin before actually turning the Arduino on? And still read the analog pin correctly when turned on?

yes and yes.
> -1 votes

---
Tags: arduino-mega
---


# Question
Title: WiFiSSLClient will not connect to servers with LetsEncrypt certificates
I'm trying to send data from an Arduino program to an app running on Google App Engine but `WiFiSSLClient.connect()` always returns false.

This is despite

* the server being up and running;
* the code working when the web app was on a different server.

The only possible explanation I can come up with is that the App Engine app uses a `LetsEncrypt` certificate while the other server was using one by another company.

```
WiFiSSLClient client;
if (client.connect(server, 443)){
    // Connected to server
} else {
    // Failed to connect
}

```

Does anyone have any solutions to this problem? I had a look at `WiFiClientSecure`; it has the ability to set the CA certificate in code but this seems like a bit of a pain.

# Answer
The solution is to update the certificates the WIFI 101 Firmware Updater tool (in the Arduino IDE).

1. Install the `FirmwareUpdater` sketch, as described on the Arduino site.
2. Select *Tools -\> WiFi 101 Firmware Updater*. Click on the *Add domain* button at the bottom, enter your domain and click *Upload Certificates to WiFi module*.
3. Upload the sketch to your Arduino. It should now connect to the server.
> 1 votes

---
Tags: wifi, mkr1000
---


# Question
Title: Weird output from chained 74HC595 shift registers
EDIT 4/2/18: The Arduino tutorial schematics have been corrected! See https://github.com/arduino/Arduino/issues/6433 for that issue.

I have a project where I am trying to load a 16-bit number onto an EEPROM using an Arduino hooked up to two 74HC595 Shift registers.

I'm loosely following this Arduino tutorial: https://www.arduino.cc/en/Tutorial/ShiftOut, but I'm getting unexpected outputs depending on the number I try to load into the register. I've reduced everything to as simple a setup as I can, and have spent several hours trying to figure out what the heck is going wrong... obviously to no avail.

Here is the schematic - with the exception that I moved the capacitor off of ST\_CP (why would they put that in the tutorial?) to between power and ground:

Here is my code:

```
#define SHIFT_DATA 2
#define SHIFT_CLK 3
#define SHIFT_LATCH 4

void setup() {
  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);

  int address = 0b1111111111111111;  // Case 1
//int address = 0b0000000000000000;  // Case 2
//int address = 0b0101010101010101;  // Case 3
//int address = 0b1010101010101010;  // Case 4
//int address = 0b0101100110101110;  // Case 5

  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, (address >> 8)); // Load first 8 bits
  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, address);        // Load second 8 bits

  digitalWrite(SHIFT_LATCH, LOW);
  digitalWrite(SHIFT_LATCH, HIGH);
  digitalWrite(SHIFT_LATCH, LOW);
}

void loop() {
  // none
}

```

Here is a picture of my breadboard setup with Case 1 loaded:

And here follows my test cases.

1. All 1's (1111111111111111). Looks good.
2. All 0's (0000000000000000). Looks good.
3. Repeated 01's (0101010101010101). Looks good.
4. Repeated 10's (1010101010101010). Output: 1010101000000000. First 8 bits match, last 8 are zeros. Huh?
5. Random sequence (0101100110101110). Output: all over the place. Initially the first 8 bits match as in Case 4, but on repeated resets of the Arduino the output changes, with some weird momentary flickering going on for some of the LEDs. If I press it enough times I can get it back to the initial output, but never what I expect. I am completely stumped. Here is an animated gif of this behavior running on the breadboard: http://i.imgur.com/KEwpSXe.gifv.

What could my problem be? I assume it's something very simple and I'm being an idiot.

# Answer
You should change your capacitors.

You only have 0.1µF instead of 1µF for the bulk capacitor (which really wants to be 10µF). In addition you should add 0.1µF (100nF) capacitors directly across the power pins of each chip:
> 4 votes

# Answer
I have forum post about the 595 chip and a question and answer about SPI.

You can use SPI to do the transfer. This is faster and simpler than shiftOut. Also you need to bring the latch low **before** transferring the data.

Simple example sketch:

```
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

```
> 3 votes

---
Tags: arduino-nano, shift-register
---


title: Servo motor sweeps beyond 180

text:
# Question
Title: Servo motor sweeps beyond 180
I'm trying to get my servo motor to sweep from 0 to 180 degrees then back to 0 degrees for infinite amount of times. I using the following code but my motor keeps resetting when it get backs to 0 degrees (meaning it goes 0--\>180--\>0 then completes a 360 and starts over). Also the 0-180 degree sweep appears to be more of a 0-270 degree sweep. Anyone running into these problems?

```
int angle = 0;

void setup() {
  myservo.attach(9);
  myservo.write(angle);
}

void loop()
{
  for (angle = 0; angle < 180; angle += 1)
  {
    myservo.write(angle);
    delay (50);
  }

  for (angle = 180; angle > 0; angle -= 1)
  {
    myservo.write(angle);
    delay(50);
  }
}

```

# Answer
> 1 votes
Are you trying to have the servo sweep at a particular speed? Why not just use:

```
void loop()
{
  angle=180;
  myservo.write(angle);

  delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.

  angle=0;
  myservo.write(angle);

  delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.
}

```

# Answer
> 2 votes
Is your servo the modified 360 degree type with no position feedback (meaning the internal feedback potentiometer has been disabled)?

# Answer
> 1 votes
I had a bunch of SG90 mini servos so I tried your code. My servos turn 0 -\> 180 -\> 0 -\> 180 -\> 0 -\> 180, over and over. No 360 spins at all.

* Maybe your servo is defect? (can you check with another servo?)
* Maybe it is not getting enough power? (how are you powering it?) It needs at least 4.8V and at least 220mA
* Maybe it doesn't get a strong clean PWM signal? (You'll probably need an oscilloscope to check this)

---
Tags: arduino-uno, servo
---


# Question
Title: How to use ESP8266 wifi shield as a hotspot?
I have bought a ESP8266 wifi shield and I want to use it hotspot, I have tried the examples that have been provided in Arduino IDE, and the shield is getting connected to my network and giving me a wifi but without internet access (like I can connect my phone to the shield but I cannot browse the internet). Any suggestion please?

Thanks......

# Answer
> 2 votes
Connecting through the ESP8266 to the internet would require the ESP8266 to handle Network Address Traversal and/or routing, which is not officially supported.

However, if you are prepared to do a lot of work, it can be done. The performance and reliability is bad, but it can be done. See http://bbs.espressif.com/viewtopic.php?t=960 Note that this will require far more skills than running the examples in the Arduino IDE.

---
Tags: arduino-uno, esp8266
---


title: NodeMCU keeps hanging after random time

text:
# Question
Title: NodeMCU keeps hanging after random time
I have tried almost everything but my NodeMCU keeps hanging after random intervals, it usually stops working after 2 days, but well... I will describe it's behaviour, what I mean by hanging is that the server stops responding to the assigned static ip, if I restart my modem or the node it works again, but this device is meant to be working endlessly and shouldn't stop working even if it has been connected during one week, I have tested it a lot, it has worked for 2 days, for 3 days, once it worked for 4 days without any problem, but after reconnecting it in another place, hanged again after almost 2 days. I started to think that probably the problem it's related to NodeMCU. So please I would really appreciate any helpful suggestion like assigning ip through the modem or something that can help. Thanks in advance.

The NodeMCU is connected to a usb power hub (A regular android phone wall charger), and it controls a relay.

Here is my code:

```
#include <ESP8266WiFi.h>

const char* ssid = "INFINITUM5607";
const char* password = "********";

int ledPin = 13; // GPIO13
int ledPin2 = 12; // GPIO13
int desconectado = 5;
int conectado = 4;
WiFiServer server(80);
WiFiClient client;

int counter = 0;
int count;

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

  WiFi.mode(WIFI_STA);

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);

  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin2, HIGH);

  pinMode(conectado, OUTPUT);
  pinMode(desconectado, OUTPUT);
  digitalWrite(desconectado, HIGH);

  connectWifi();

  Serial.print(F("Setting static ip to : "));
  Serial.println(WiFi.localIP());

  // Start the server
  server.begin();
  Serial.println("Server started");

}

void loop() {

  delay(200);

  if (WiFi.status() != WL_CONNECTED) {
    delay(100);
    digitalWrite(conectado, LOW);
    digitalWrite(desconectado, HIGH);
   connectWifi();
  }

  // Check if a client has connected
  client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  count = 0;
while(!client.available()){
delay(1);
count++;
if ( count > 1000 )
{
Serial.println("Abandoned Client");
client.stop();
return;
}
}

//Serial.println("new client");
//  int t = millis();
//  while(!client.available()){
//  delay(1);
//  if (millis()-t>130) return;
//  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  client.println("HTTP/1.1 200 OK");
  client.println("Access-Control-Allow-Origin: *");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one

  // Match the request
  if (request.indexOf("/switch") != -1)  {
    digitalWrite(ledPin, !digitalRead(ledPin));
    digitalWrite(ledPin2, !digitalRead(ledPin2));
    printSwitch();
  }else if (request.indexOf("/uno") != -1) {
    client.print("Canal 1 apagagado | Canal 2 encendido");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/dos") != -1){
    client.print("Canal 1 encendido | Canal 2 apagado");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/tres") != -1){
    client.print("Canal 1 apagado | Canal 2 apagado");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/cuatro") != -1){
    client.print("Canal 1 encendido | Canal 2 encendido");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/cinco") != -1){
    printIP();
  }else if (request.indexOf("/apagaruno") != -1){
    client.print("Canal 1 apagado");
    digitalWrite(ledPin, HIGH);
  }else if (request.indexOf("/apagardos") != -1){
    client.print("Canal 2 apagado");
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/prenderuno") != -1){
    client.print("Canal 1 encendido");
    digitalWrite(ledPin, LOW);
  }else if (request.indexOf("/prenderdos") != -1){
    client.print("Canal 2 encendido");
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/canaluno") != -1){

    if(digitalRead(ledPin) == HIGH) {
      client.print("Off");
  } else {
    client.print("On");
  }

  }else if (request.indexOf("/canaldos") != -1){

    if(digitalRead(ledPin2) == HIGH) {
    client.print("Off");
  } else {
    client.print("On");
  }

  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
  client.stop();

}

void printSwitch(){

  if(digitalRead(ledPin) == LOW) {
    client.print("Canal 1 Encendido");
  } else {
    client.print("Canal 1 Apagado");
  }
  Serial.println("");
  if(digitalRead(ledPin2) == LOW) {
    client.print("Canal 2 Encendido");
  } else {
    client.print("Canal 2 Apagado");
  }
}

void printIP(){
  delay(100);
  client.print(WiFi.localIP());
}

void connectWifi()
{
  Serial.print("Connecting to "+*ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  }

  // config static IP
  IPAddress ip(192, 168, 1, 66);
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  digitalWrite(conectado, HIGH);
  digitalWrite(desconectado, LOW);
  Serial.println("");
  Serial.println("Connected");
  Serial.println("");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}//end connect

```

# Answer
Check the power source. If you're powering it via USB it is likely to malfunction over time, but if you use an external and stable power source you won't have that kind of problem.
> 1 votes

---
Tags: esp8266, nodemcu
---


# Question
Title: Mysterious RX pulses on UART connect on OS X Arduino Due
Arduino IDE 1.6.8, Arduino Due, Mac OS 10.11.3

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

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

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

Repro steps on my machine:

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

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

# Answer
Short:

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

Long:

Look at function:

`void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)`

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

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

```

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

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

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

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

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

---
Tags: arduino-due, uart, osx
---


# Question
Title: How do I calculate sampling rate of external ADC?
I am wondering if someone could explain this to me.

I want to calculate sampling rate of external ADC. I am using ADS8320 which has max sampling rate of 100kHz, with Arduino MEGA 2560. SPI divider is set to 128, which makes SPI frequency 125kHz. Baud rate is 115200 (I am not sure if this is important).

Thanks a lot!

# Answer
> 1 votes
To get an idea of the sampling rate write a loop that takes 10,000 measurements and time how long it takes. You have your sample rate, not perfect but gives you some idea.

```
long start = millis();
// the loop

Serial.print( 10000000/(millis() - start) );
Serial.println(" samples per second");

```

# Answer
> 0 votes
Easy.

1. Based on your set up, figure out the spi speed.
2. Take a look at the adc datasheet, figure out it's frame of transmission . Aka how many pulses per frame / sampling.
3. The product of the numbers in 1 and 2 gives you the minimum time per frame. The inverse of it is the maximum transmission in your application. That speed is cap by the devices own max sampling rate (100ksps).
4. Your actual sampling rate will depend on your specific application but it should not go above the number obtained in 3.
5. You may need to factor in other timing requirements as well so read the datasheet carefully. But the gist is the same.

---
Tags: arduino-mega, spi, adc
---


# Question
Title: Problem reading in Arduino serial port with 5K potentiometer
I have written code to see values of a 5K potentiometer from 0 to 1023. Whenever I rotate the knob, the value should change from 0 to 1023. I have connected the potentiometer to the Arduino's pin A1, but there is a problem with readings. Whenever I am rotating the potentiometer's knob, the serial port is only showing 1023. Please help.

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

void loop() {
  int sensorValue = analogRead(A1);
  Serial.println(sensorValue);
  delay(500);
}

```

# Answer
> 3 votes
It sounds like it might be a wiring problem. Check that you have the potentiometer connected correctly. Your circuit should look something like this:

# Answer
> 1 votes
Disconnect the pot and take some readings. You should get some random values near zero. That would mean you're not connecting the leads right or the swinger is stuck at one end.

---
Tags: arduino-uno
---


title: How to send information from Arduino?

text:
# Question
Title: How to send information from Arduino?
I plan to make an air quality monitoring system that uses Arduino uno, but I can't decide how I will be able to distribute the air condition and harmful gas concentration info and have it available to other people.

Aside from using a GSM module to text individual persons and making a new website to chart the data from the Arduino, what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

# Answer
> 1 votes
> what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

take a different route. get the information to a pc (or to a server through a pc) and you have much more flexibility.

there are many ways to get that information to a pc, like serial, spi, i2c, acquisition cards, wired / wireless, ....

# Answer
> 0 votes
There is a Wi-Fi module named "ESP-01" (which uses the ESP8266 microcontroller) and it comes ready to be used with Arduino. But better than that, I think, is that you can program it directly via Arduino's IDE if you flash it with NodeMCU's firmware. You can also use a NodeMCU instead of Arduino, but ESP-01 has the advantage of being much, much cheaper.

# Answer
> 0 votes
You can use a pair of ESP8266 WiFi Transceiver modules (one as the client and the other as the server).

There are a few guides to getting started with the ESP8266 out there, which generally contain some helpful tips.

I also found this fairly straightforward ESP8266 – Wireless Weather Station with Data Logging to Excel project which illustrates the principle of using a pair of ESP8266 modules as client and server.

# Answer
> 0 votes
Others suggest ESP8266, but I think it's now outdated, there's a new and improved version of it available named ESP32, it's better in basically every way (faster, more RAM, ROM etc.), not that much more expensive and can still be programmed using the Arduino IDE, that means programming it just as simple as programming an ESP8266.

Disclaimer: ESP32 Arduino core is still under development, some less frequently used features might be experimental or missing.

---
Tags: arduino-uno, communication
---


# Question
Title: Very long range wireless communication between two arduinos(500-1000 KM)
I searched for very long range wireless communications between two Arduinos, but can't find solutions. I don't live in USA, In my country there are regions, where GSM does not work. I want wireless communication approximately 500-1 000 KMs. What are options without GSM for that distance wireless communication(500-1000 KM)?

# Answer
> 1 votes
Back in the old days, we used things called modems to connect computers across POTS.

Your country may not have GMS, but I bet you still have old land lines. In that case, you can use a land line + modem to connect the arduinos directly , no Internet involved, no ISP needed, no overhead, no lag, nothing. It's just one Arduino at each end of a very long cable. No TCP/IP needed, but you need your own protocol to keep data in sync and filter out errors. There is lot of well proven ones from the golden era of BBS.

I search Aliexpress, I didn't find any modem suitable for direct conection with Arduino, but there is a lot of USB modem like this:

I don't know if they can work with Arduino. I'm afraid that they are *win-modem* only.

What it really works with anything is a traditional modem, like this model from Multitech (not an endorsing):

You will need a RS-232 level converter however, because RS-232's voltages can go up to 25V. The converter avoids you to deal with the peculiarities of the RS-232 standard and DB-9 connector.

And a cable, of course.

You can develop and test your project using a *null modem* cable, to connect both Arduinos, a few meters apart, without need of a land line.

# Answer
> 1 votes
> What are options without GSM for that distance wireless communication(500-1000 KM)?

1) use the internet;

2) use narrow band transmission, like qrp;

3) use relays;

4) use satellite phones;

5) use a high-powered lw transceivers.

6) ...

---
Tags: arduino-uno, communication, wireless
---


title: Simulate V1838B IR LED output

text:
# Question
Title: Simulate V1838B IR LED output
I have a HDMI switcher which uses a TL1338 IR LED that's connected via a 3.5mm audio jack. It has its own remote for switching between the inputs, but I want to use my TV remote.

In order to do that I want to connect the IR led to an ATTiny85 to receive the input and send the 'translated'code to the switcher.

When analysed with an oscilloscope it seemed that Arduino Libraries output a PWM signal, while the TL1838 outputs a digital signal. Is there a way to simulate a TL1838 signal?

Original situation:

Goal situation with ATTiny85.

# Answer
> 0 votes
What you want to do is send "unmodulated" IR Codes, but the library is trying to modulate them with a 38khz carrier. (The TL1838 device has a built-in demodulator.)

While your question is not a duplicate, this answer applies.

---
Tags: pwm, attiny, ir, attiny85, infrared
---


# Question
Title: Using multiple sensors on ESP8266 Wifi module
I have an ESP8266 ESP-01 WiFi module. I have a project where I need to use the following and send their data to a firebase database.

2x Force Sensitive Resistors(Sensor)

1x GPS module

My question is what GPS module can I use to send GPS location thru the ESP8266 Wifi module. My ESP-01 has only 2 GPIO. What should I do so I can use 2 FSR and GPS module at the same time send all 3 data to firebase realtime database.

Thanks

# Answer
> 2 votes
I would go for an i2c A/D converter, example ADS1015 (4 analog input, 12 bit) and connect that to the ESP-01.

Ref.:

https://en.wikipedia.org/wiki/I%C2%B2C

https://www.youtube.com/watch?v=6IAkYpmA1DQ&t=32s

# Answer
> 1 votes
You really need something external to both provide the analog inputs for the force sensors and the serial communication for the GPS module.

The simplest "something" is another microcontroller. Ideally one with two UART ports.

You can then:

* Communicate between the microcontroller and the GPS with one UART
* Sample the FSRs with the microcontroller
* Format and send the data to the ESP-01 through the other UART

Using `SoftwareSerial` you chould just about do it with an Arduino Uno (though you'd have to disconnect whatever was on the hardware UART every time you wanted to program it), but ideally something with more UARTs would be better, such as a Mega2560.

A halfway house between the two would be a board based around the ATMega32U2 which uses a direct USB connection for programming leaving the hardware UART free to be used permanently. However you'd still need to use `SoftwareSerial` to emulate the second UART (maybe best for the GPS since it's then only used for receiving).

---
Tags: sensors, esp8266
---


title: I2C conflict with 2 Arduinos

text:
# Question
Title: I2C conflict with 2 Arduinos
I am having some trouble connecting my 2 Arduino Nanos with I2C. I have this configuration:

* SLAVE RECEIVER Nano with DS1037 and LCD 16x02 on I2C.
* MASTER SENDER Nano.

After some time the Slave receiver prints on LCD random chars. If I delete the line including library RTCLIB.h everything is working except the clock. Thanks for your help :D

Slave receiver code:

```
#include <Wire.h> // include la libreria
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"

LiquidCrystal_I2C lcd(0x3E, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
RTC_DS1307 RTC; // orologio

static int anno;
static int giorno;
static int mese;
static int ora;
static int secondo;
static int oldSecondo;
static int minuto;
static int oldMinuto;
static int annoGrezzo;

//------------------------------------------------------------
// si ripete la union esattamente come nel master
union Scomp_float {
  // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;

//------------------------------------------------------------
// si ripete la union esattamente come nel master
union Scomp_long {
  // si utilizza union x long
  long int mioL;
  char byte_sL[4];
} S_long;

//------------------------------------------------------------
//------------- byte temporanei
byte f0 = 0;   // contengono i byte ricevuti
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
byte a1 = 0;
//-------------------------------------------------------------
//  qui si introdurranno i dati ricomposti dopo la trasmissione
long int masterLong = 0;
float masterFloat = 0;
int masterInt = 0;
//--------------------------------------------------------------

void setup() {
  Wire.begin(80);                // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
  lcd.begin(16, 2);
  Serial.begin(9600);           // start serial for output
  //-----------orologio-----------
  RTC.begin();
  // Check to see if the RTC is keeping time.  If it is, load the time from your computer.
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // This will reflect the time that your sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  //-----------fine orologio-----------
}

void loop() {
  //------------------------------------------------------------
  //   si stampano i dati ricevuti e ricomposti
  //------------------------------------------------------------
  Serial.println(masterInt);
  Serial.println(masterLong);
  Serial.println(masterFloat);
  DateTime now = RTC.now();
  annoGrezzo = now.year();
  anno = ( annoGrezzo % 100);
  mese = now.month();
  giorno = now.day();
  ora = now.hour();
  minuto = now.minute();
  lcd.setCursor(0, 0);
  lcd.print(masterInt);
  lcd.setCursor(0, 1);
  lcd.print(giorno);
  lcd.print(" ");
  lcd.print(mese);
  lcd.print(" ");
  lcd.print(anno);
  lcd.print("  ");
  lcd.print(ora);
  lcd.print(":");
  lcd.print(minuto);
  delay (1000);
  lcd.clear();
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  if (howMany == 2) {
    // se in arrivo due dati
    f0 = Wire.read(); // si leggono i byte
    f1 = Wire.read();
    masterInt =  ((f1 << 8) | f0); // si ricompone l'intero
  }

  if (howMany == 4) {
    // se in arrivo 4 dati è un float
    f0 = Wire.read();  // si leggono i byte
    f1 = Wire.read();
    f2 = Wire.read();
    f3 = Wire.read();
    S_float.byte_s[0] = f0; // si ricompone il float
    S_float.byte_s[1] = f1;
    S_float.byte_s[2] = f2;
    S_float.byte_s[3] = f3;
    masterFloat = S_float.temp;
  }

  if (howMany == 5) {
    // se in arrivo 5 dati è un long
    f0 = Wire.read();  // si leggono i byte
    f1 = Wire.read();
    f2 = Wire.read();
    f3 = Wire.read();
    a1 = Wire.read();
    S_long.byte_sL[0] = f0;  // si ricompone  il long
    S_long.byte_sL[1] = f1;
    S_long.byte_sL[2] = f2;
    S_long.byte_sL[3] = f3;
    masterLong = S_long.mioL;
  }
}

```

Master sender code:

```
#include <Wire.h> // si include la libreria
//---------------------------------------------------------
union Scomp_float {
 // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;
//---------------------------------------------------------
union Scomp_long {
 // si utilizza union x long
  long int mioL;
  char byte_sL[4];
} S_long;
//----------------------------------------------------------
// questi sono i dati che si vogliono trasmettere

long int mioLong = 1234567801;
float mioFlo = 123456.29;
//----------------------------------------------------------
byte a1 = 0; // conterrà i primo byte dell'int
byte a2 = 0; // conterrà il secondo byte dell'int
byte f0 = 0; // contengono i byte del float e del long
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

void loop() {
  int mioInt = random(30000);
 //-----------------------------------------------------
 // trasmissione di un intero ( 2 byte)
 //-----------------------------------------------------
  a1 = byte(mioInt); // si scompone l'intero in 2 byte
  a2 = byte( mioInt >> 8);
  Wire.beginTransmission(80); // inzia trasmissione allo slave

  Wire.write(a1); //  invia un byte
  Wire.write(a2); //  invia il secondo byte
  Wire.endTransmission(); // stop transmitting
 //------------------------------------------------------
  delay (2000);
 //------------------------------------------------------
 // trasmissione intero lungo 4 byte
 //------------------------------------------------------
  S_long.mioL = mioLong; // si scompone in 4 byte
  f0 = S_long.byte_sL[0];
  f1 = S_long.byte_sL[1];
  f2 = S_long.byte_sL[2];
  f3 = S_long.byte_sL[3];
  a1 = 1; // si trasmette questo byte solo per segnalare allo slave
 // che stiamo trasmettendo un long
 // una volta scomposto si trasmettono i 4 byte
  Wire.beginTransmission(80); // trasmette allo slave
  Wire.write(f0); // invia un byte
  Wire.write(f1); //
  Wire.write(f2); //
  Wire.write(f3); //  invia un byte
  Wire.write(a1);
  Wire.endTransmission(); // fine trasmissione
 //-------------------------------------------------------
  delay (2000);
 //------------------------------------------------------
 //   trasmissione di un float 4 byte
 //------------------------------------------------------
  S_float.temp = mioFlo; // si scompone in 4 byte
  f0 = S_float.byte_s[0];
  f1 = S_float.byte_s[1];
  f2 = S_float.byte_s[2];
  f3 = S_float.byte_s[3];
 // una volta scomposto si trasmettono i 4 byte
  Wire.beginTransmission(80); // trasmette allo slave
  Wire.write(f0); // invia un byte
  Wire.write(f1); //
  Wire.write(f2); //
  Wire.write(f3); //  invia un byte
  Wire.endTransmission(); // fine trasmissione
 //-------------------------------------------------------
  delay (3000);
}
//------ end master ----------------------------------

```

# Answer
> 1 votes
I don't know what your problem is, but you have a gross error at `LiquidCrystal_I2C lcd(0x3E, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);`. You have a I2C LCD display but you are using it as an old-style LCD initialization.

The correct initialization for and I2C LCD display is

```
LiquidCrystal(0x2A, 16, 2);

```

You have to replace 0x2A for the correct I2C address of your LCD display (Use a I2C scanner sketch for that).

You have to check the API of your libraries first (usually a .h file):

```
    /**
     * Constructor
     *
     * @param lcd_addr  I2C slave address of the LCD display. Most likely printed on the
     *                  LCD circuit board, or look in the supplied LCD documentation.
     * @param lcd_cols  Number of columns your LCD display has.
     * @param lcd_rows  Number of rows your LCD display has.
     * @param charsize  The size in dots that the display has, use LCD_5x10DOTS or LCD_5x8DOTS.
     */
LiquidCrystal_I2C(uint8_t lcd_addr, uint8_t lcd_cols, uint8_t lcd_rows, uint8_t charsize = LCD_5x8DOTS);

```

# Answer
> 0 votes
i partially resolve the problem with this:

MASTER RECEIVER code:

```
#include <Wire.h> // include la libreria
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"

LiquidCrystal_I2C lcd(0x3E, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
RTC_DS1307 RTC; // orologio

static int anno;
static int giorno;
static int mese;
static int ora;
static int secondo;
static int oldSecondo;
static int minuto;
static int oldMinuto;
static int annoGrezzo;
char t[10] = {};
char v[10] = {};

void setup()
{
  Wire.begin();                // join i2c bus with address #4
  lcd.begin(16, 2);
  Serial.begin(9600);           // start serial for output

  //-----------orologio-----------

  RTC.begin();
  // Check to see if the RTC is keeping time.  If it is, load the time from your computer.
  if (! RTC.isrunning())
  {
    Serial.println("RTC is NOT running!");
    // This will reflect the time that your sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  //-----------fine orologio-----------

}

void loop()
{
  //------------------------------------------------------------
  //   si stampano i dati ricevuti e ricomposti
  //------------------------------------------------------------
  Wire.requestFrom(8, 3);
  int i = 0;
  while (Wire.available()) {
    t[i] = Wire.read(); // every character that arrives it put in order in the empty array "t"
    i = i + 1;
  }
  Wire.requestFrom(8, 3);
  i=0;
  while (Wire.available()) {
    v[i] = Wire.read(); // every character that arrives it put in order in the empty array "v"
    i = i + 1;
  }
  Serial.println(t);
  DateTime now = RTC.now();
  annoGrezzo = now.year();
  anno = ( annoGrezzo % 100);
  mese = now.month();
  giorno = now.day();
  ora = now.hour();
  minuto = now.minute();
  lcd.setCursor(0, 0);
  lcd.print(t);
  lcd.setCursor(5,0)
  lcd.print(v);
  lcd.setCursor(0, 1);
  lcd.print(giorno);
  lcd.print(" ");
  lcd.print(mese);
  lcd.print(" ");
  lcd.print(anno);
  lcd.print("  ");
  lcd.print(ora);
  lcd.print(":");
  lcd.print(minuto);

  delay (1000);
  lcd.clear();
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()

```

SLAVE SENDER code:

```
#include <Wire.h> // si include la libreria
//---------------------------------------------------------

char t[10];
char v[10];

void setup()
{
  Wire.begin(8); // join i2c bus (address optional for master)
   Wire.onRequest(requestEvent);
}

void loop()
{
 int mioInt = random(30000);
 int mioInt2 = 1234;
  dtostrf(mioInt, 3, 2, t); //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  dtostrf(mioInt2, 3, 2, v);
//------------------------------------------------------
delay (500);
}
void requestEvent() {
  Wire.write(t);
  Wire.write(v);
}
//------ end slave    ----------------------------------

```

now my problem is the second variable T im unable to receive it on Master. Thanks for help

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


# Question
Title: How to switch on or off up to seven devices individually?
Is there a way to turn on or off the power supply of up to seven hard drives with the help of an Arduino? Or maybe there is another way to ultimately - but restorable - prevent read/write access to the disks.

# Answer
Switching power on and off to hard drives is not as simple as you may think.

First you have three voltages to control - 3.3V, 5V and 12V, and on top of that you have (ideally) pre-charging for the 5V and 12V pins. The power-on sequence would ideally be:

1. Power up 5V and 12V pre-charge
2. Power up 3.3V, 5V and 12V main power

That's 5 poles for one drive (although you can get away without the pre-charge).

So you would be switching at minimum 3 power signals per drive. For 7 drives that would be 21 power signals that need to be switched.

**HOWEVER**

**Switching off power to a hard drive using mechanisms that aren't directly under the control of the operating system can cause file-system corruption and data loss.**

The operating system caches data internally and writes it to the hard drive when able to. If the hard drive is turned off while there is still data cached that data will never get written to the hard drive. Worse still, if you turn it off *whilst it is writing* the file-system could become irrevocably corrupted (depending on the file-system in use and the resilience of it).

Most hard drives have the ability to power themselves down at a command from the operating system. I suggest you use this mechanism instead, since it is more reliable that blindly shutting off the power. Chances are your hard drives are already doing this, since most operating systems enable it by default.
> 2 votes

# Answer
An Arduino have 13 digital I/O pins so theoretically you can control 13 devices without any additional additional circuits.

You will probably need some circuits for the devices you want to control.
> 2 votes

# Answer
If you want to control them externally, I suggest buying e.g. an 8 channel relay. This way you can easily control them with the Arduino, and using external power for the devices to switch on/off.

If you want extra protection (especially with motors or expecting spikes on signals), use relays with opto-couplers.
> 0 votes

---
Tags: power, switch, mosfet
---


# Question
Title: Replacement for #include <pins_arduino.h> on particle photon
I've run into this a couple of times when trying to use libraries written for Arduino on a particle photon. Many have the line:

```
 #include <pins_arduino.h>

```

which returns the error on the photon compiler:

```
 fatal error: pins_arduino.h: No such file or directory

```

I had similar trouble with:

```
 #include <WProgram.h>

```

and found an easy fix was to replace that with

```
 #include "application.h"

```

I'm wondering if there's a similar easy fix for pins\_arduino?

# Answer
There are some Arduino libraries, that just implements functionalities that do not depend on hardware. Example of these are almost all those libraries that deal with data structures/types (strings, arrays, trees, lists, etc), or particular algorithms. If such libraries do not depend on other Arduino-specific libraries, you can use them almost certainly.

Other libraries, instead, heavily depend on the hardware currently used on the Arduino boards. In those cases, the library must access the hardware, therefore they will include verious headers, such as pins\_arduino.h (in particular, pin\_arduino.h .

These won't work without heavy modification of such libraries and/or the creation of a wrapper header to "emulate" the required functionalities and define the required macros/constants, according to your hardware.
> 1 votes

---
Tags: library
---


# Question
Title: Bootloader and Boards Definition for Atmega2560V-8AU at 8 MHz / 3.3v
I am working on a home made project,where i am using Atmega2560V-8AU **(note the suffix, this part has an 8 MHz maximum clock rate)** as my main controller, supplying 3.3V to this chip.

I want this controller to work exactly same as standard Atmega2560-16AU like on Arduino Mega(perhaps at a slower baud rate on account of the slower clock)

Does there already exist a suitable bootloader image and board definition for an ATmega2560 operating from an 8 MHz crystal?

If not, what changes would need to be made to the usual 16 MHz bootloader and boards definition to support 8 MHz operation, both for the bootloader and for correct time functions and serial buad rates in sketches?

# Answer
I have used megacore bootloaders, and it solved the problem
> 1 votes

---
Tags: arduino-mega, arduino-ide, bootloader, atmega2560
---


title: connecting multiple keypads

text:
# Question
Title: connecting multiple keypads
My project is to use an Arduino to control the lighting of a small apartment. My preferred option is to replace each wall light switch with a 4x4 membrane keypad (https://www.amazon.co.uk/Mirocle-Matrix-Membrane-Keyboard-Arduino/dp/B01LMU6OPG/ref=sr\_1\_19?s=electronics&ie=UTF8&qid=1504376458&sr=1-19&keywords=membrane+keypad). The UX would allow any keypad to control any light, eg. pressing 1-4 will set light 1 to brightness 4.

The problem I have is this will result require 4 x 8 = 32 pins, so I'm looking for alternatives.

So my questions:-

1/ Is there a simple pll to serial converter that I should be using to interface the keypads?

2/ Can I wire multiple keypads onto the same set of 8 pins? Only one keypad will ever be touched at one time.

3/ Are there simple serial versions of the classic membrane keypad.

# Answer
As far as I know, you can connect multiple keypads of this type to a single set of 8 pins. However, it seems like a lot of wire needs to be strung to get this to work, for each switch, 8 wires for the keypad, and two, or more, for power control.

Were I to do this project. I would likely handle each switch independently, embedding a Pro Mini in each switch box along with an HC-12, or some such. This means no wires are needed, any pad could control any switch, and expansion is much easier.

Of course, this is only what I would do, and you understand your own requirements far better than I.
> 1 votes

# Answer
Or the 8 pins 4 will be connected to output pins to be enabled one at a time and 4 will be connected to input pins that get shorted to the input pins when the button is pressed.

The way to get a keypress from this will be to pull a single output pin high and then check all of the inputs, if any of them are high then the corresponding button is pressed.

If you want to treat all keypads the same then you can simply put them in parallel. If you want to treat each of them differently then you can parallel either the inputs or the outputs. But the other set needs to have a S2P or P2S shift register to get the proper data or make the correct pin high.

Though it will probably be simpler if each got their own microcontroller to poll the keypad and use a different longer range protocol to communicate to the main controller.
> 1 votes

---
Tags: arduino-uno, keyboard
---


title: XBee s6b internet

text:
# Question
Title: XBee s6b internet
For my project i need to send some data logged into a SD card to a remote server. For this im using an XBee S6b wifi module connected to an arduino. ive had trouble connecting the xbee module to wifi. and also how can i set the ssid and other information through arduino?

# Answer
You configure the XBee with AT commands. However there is one important thing to know about the XBee: it loves to be in "data" mode and won't stay in command mode while you play with it.

You need to first get into command mode by sending `+++` with a delay each side of it:

```
delay(1000);
xBeeSerial.print(F("+++"));
delay(1000);

```

Then you can send commands:

```
// Set the SSID:
xBeeSerial.println(F("ATIDThis Is My SSID"));
// Set the wireless key:
xBeeSerial.println(F("ATPKTh!sI5mYk3Y"));

```

Once you have set the details you need to write the settings to flash and reset the XBee for the changes to take effect:

```
xBeeSerial.println(F("ATWR"));
xBeeSerial.println(F("ATFR"));

```

After each command you should really be looking for the "OK" response.

If at any time you don't sent anything for more than a few seconds the XBee will exit command mode and go back to data mode - at which point you will have to go back to command mode with the delays and `+++`.

It's easiest to configure the XBee using your computer and an XBee Explorer.

All the AT commands are detailed here.
> 0 votes

---
Tags: arduino-uno, xbee
---


title: Serial.print and char[] & null

text:
# Question
Title: Serial.print and char[] & null
I don't write a lot of C, so I'm always discovering things I only partly understand in the Arduino variety. One of these is how `Serial.print` handles `char[]`.

Does Serial.print always require a null terminator? In the case of (say) `Serial.print(88, DEC);` is a null implied?

What happens in the following cases?

```
char buff[3] = "ABC"; // warned because no room for a null
Serial.print(buff);   // will absence of a null cause overrun?

char buff[4] = "ABC"; // now there's a null
Serial.print(buff);   // will the null character be sent too?

```

Any references appreciated.

# Answer
> 2 votes
When passing a char\* you need to also pass some way of telling the function where it ends. In C that is usually the null terminator and that's all a null terminator is for. If that is missing then you get a buffer overrun.

The null terminator is not sent.

# Answer
> 3 votes
The "Serial" is a object/class and that makes it possible to have more than one function for `Serial.print()`. According to the type of the parameter the proper `Serial.print()` is selected.

This is the include file for the `Serial.print()`: Print.h
And these are the possibilities:

* `size_t print(const __FlashStringHelper *);`
* `size_t print(const String &);`
* `size_t print(const char[]);`
* `size_t print(char);`
* `size_t print(unsigned char, int = DEC);`
* `size_t print(int, int = DEC);`
* `size_t print(unsigned int, int = DEC);`
* `size_t print(long, int = DEC);`
* `size_t print(unsigned long, int = DEC);`
* `size_t print(double, int = 2);`
* `size_t print(const Printable&);`

The reference for `Serial.print()` is short, but it explains pretty well that those different parameters are possible.

Your `Serial.print(88, DEC);` does not use a string of text, it uses the integer number 88.

As soon as a string of text is used, it should be zero-terminated.
The line `char buff[3] = "ABC";` is indeed wrong, as you already wrote. That is one of the things of the 'c' language. The "ABC" gets a zero-terminater and that makes 4 bytes.

---
Tags: print
---


# Question
Title: Powering Arduino with 12V AC-DC Adapter Jack
I have 12V,700mA AC-DC adapter power jack. Is it ok power on arduino board directly using this power jack?

Though Arduino webpage suggests that arduino can stand and upto 20V power supply, I ask this because somewhere it is written that supply 12v, 700mA will end up the board to smoke and need a converter to make it 5V.

Is this correct?

Thanks, Jyoti Raj

# Answer
You can use that to power the Arduino through the barrel jack or the VIN pin. The only way you end up with smoke is if you try to pull too much current through that setup. Don't power any motors or solenoids directly off of output pins for example.
> 1 votes

# Answer
> Is it ok power on arduino board directly using this power jack?

it depends on the regulator used and the current you expect to draw from the regulator.

essentially, you want to make sure that the power dissipation over the regulator isn't too much. that power dissipation is proportional to the voltage drop over the regulator (Vin - Vcc) and the current draw (20ma + whatever you may draw from the arduino).

once you have that, check against the regulator datasheet to make sure that its temperature rise is within range.
> 0 votes

---
Tags: arduino-uno, power
---


title: Servos: attach() and write()

text:
# Question
Title: Servos: attach() and write()
Arduino newbie here, so this question might sound too simple. I am trying to run a parallax continuous rotation servo using Arduino Uno. From the reference, I learned that the servo needs to be "attached" to one of digital pins with PWM capability, and the servo's speed can be controlled by `write(0~180, 90=stop)`.

But I am having a hard time understanding the role of the PWM digital pin. If the servo's speed and direction of rotation is determined by `write()`, what is the role of `attach(pin#)`?

Thanks in advance!

# Answer
> 1 votes
`attach` tells the servo library which pin it should be writing to, this is stored somewhere in ram and `write` will look it up and communicate with the correct pin.

It's possible that you are using the other pwm capable pins for other purposes and suddenly having that library interfere with that is not a good thing.

# Answer
> -1 votes
First of all, you don't need to connect it to one of the PWM pins. Any digital output pin will work just fine.

Judging by the Arduino reference, attaching the servo to a pin is kind of like to declare a variable. By using `myservo.attach(pin)` you also give the servo a name (myservo in this case), and you can also add maximum and minimum values to the servo's rotation by adding two extra values to the end: `myservo.attach(pin, min, max)`

When you then use the `myservo.write()` function, the Arduino will "remember" what pin myservo is connected to, as well as the maximum/minimum settings for it.

---
Tags: arduino-ide, servo, pwm, sketch
---


# Question
Title: Digispark / DigiKeyboard change keyboard layout
I'm trying to use the Digispark as a Rubber Ducky but the Digispark is only usable with the US laylout. German keyboard layout is QWERTZ. Some keys can be changed, like y and z, but if there are `[` or `]` this isn't possible. Trying to define a `[`-key in DigiKeyboard.h displays a `ü`.

Does someone know a solution?

# Answer
> 2 votes
You can edit the file scancode-ascii-table.h in your DigiKeyboard library. It basically states which ASCII code corresponds to which keyboard scancode.

So if you try to print the ':' character but get a '\>' instead, you know that in the above mentioned file at the ASCII position for ':' is the scancode for a '\>'.

Using this, you can swap the scancodes around and basically create your own 'mapping'. For example, if you swap the values at ASCII 89, 90 and 121, 122 you for example solve the Y/Z switch.

However, I have not figured out how to correctly print a backslash. You might have to map that do a different ASCII character you don't need.

To add to this answer, there exists a workaround using mame82's duck2spark: https://github.com/mame82/duck2spark

# Answer
> 1 votes
Solution is here: Python script to convert RubberDucky payloads to DigiSpark sketch with respect to choosen keyboard layout:

duck2spark

Btw: The keys '\<' '|' and '\>' are on NON-US-KEY-100 on German keyboard layout. The key has value 0x64 for USB HID and the right modifiers have to be set (f.e. ALT\_GR for '|' ). You could send them using

```
DigiKeyboard.sendKeyStroke(key,modifier);

```

For details see USB HID usage tables

# Answer
> 0 votes
here is a library version of Digistump with german keyboard support https://github.com/adnanonline/DigistumpArduinoDe I adapted the keyboard library: digistump-avr/libraries/DigisparkKeyboard/DigiKeyboard.h to the german layout

---
Tags: arduino-ide, library, keyboard, digispark
---


title: Low power RGB LED for wearable device

text:
# Question
Title: Low power RGB LED for wearable device
I am trying to prototype a wearable device which will have about 120 RGB LEDs. I was considering the WS2812B but they seem to draw about 50mA and so may not be a good option since I will be powering them from a battery.

I would be glad to know of other options or ways to implement the LEDs in order to consume less power.

# Answer
You can reduce the current by simply reducing the duty cycle. For example, to display red, rather than sending 255 as the red component, send 42.

If you divide each of the R/G/B values by the same figure you get the same colour, just duller. In a quick test I found that a 24-pixel strip only used 67 mA if I sent red=0, green=0, blue=42 which made them look a dull blue. If you send a value of 8 (in a single channel) then it takes 25 mA for 24 pixels.

A bit more testing reveals a base consumption of 21 mA even if you are sending black. That is, the overhead is 21 mA, which works out at about 1.1 mA per neoPixel.

Based on that, you would consume 335 mA to make 120 NeoPixels show a moderately bright red.

I don't think there is going to be some "magic bullet" that lets you light up 120 LEDs brightly, but not use much power. However using the NeoPixels which lets you have fine control over the brightness of each of the R/G/B pixels is probably going to be about as close as you can get.

The figure of 50 mA which you quoted is to have "full brightness" on all three colours (ie. bright white).
> 1 votes

---
Tags: arduino-uno, led, rgb-led
---


title: HC-05 module short circuit

text:
# Question
Title: HC-05 module short circuit
I have bought a HC05 bluetooth module and I think I accidentally short circuited it. Is there any way to change the voltage regulator or methods to reuse it again?

# Answer
I suppose you're referring to the HC05 module, already soldered on a board, with the 6-pin header. The regulator is on that board.

Online you'll find several versions of that board, therefore you should check the schematics, to find which you need to mount. For instance, on some board, a R1114-33 is used.

Changing the regulator is not the hardest task on earth, however, other components are very close to it (capacitors).

Still there are 2 things to consider:

* Is it worthy to change the regulator? That module will cost few bucks.
* As you can see from the datasheet, the regulator is short-circuit protected (yes, it does not mean that it will be indestructible). I think, instead, you destroyed one of the two ICs of the bluetooth module soldered on board. And those one, beside of being quite difficult to find and expensive in small quantity, they are very hard do replace.
> 2 votes

---
Tags: arduino-uno, hc-05
---


# Question
Title: How to set Inquire Access Code (IAC) via AT commands on HC-05?
I am trying to set IAC of HC05 via AT Commands, but for some reason, the result is not as desired.

I need to set the IAC as '1234', for which I enter the command:

```
AT+IAC=1234

```

The module responds OK, but when I ask `AT+IAC?`, it replies '01234'.

Now, it has been troubling me for the past few days. I've also tried adding '\r\n' to the end of command, but it sets the IAC as '1234444'

I would be thankful if you could help me with this! I tried searching the net but to no avail.

# Answer
> 1 votes
You have to have `\r\n` in both the set and read command.

Example:

```
AT+IAC=12345f\r\n
OK

AT+IAC?\r\n
+IAC: 12345f
OK

```

---
Tags: arduino-uno, hc-05
---


# Question
Title: I have built a battery level indicator and have tested with a 12V battery Would it harm my arduino board if I connect a 48V battery?
I am a newbie and have followed a tutorial to build a battery level indicator as below

Please suggest any changes I'll need to make to make the circuit useful with a 48V battery as the above circuit is tested with a 12V one. Thank You.

# Answer
You have a voltage divider there, which would give (if the pre-set pot was set to the maximum):

```
Vout = (Vin * R2) / (R1 + R2)
Vout = (12 * 10000) / (100000 + 10000)
Vout = 1.09

```

Thus a 12V battery would present 1.09V at the analog input.

This same wiring would seem to be in range for a 48V battery:

```
Vout = (48 * 10000) / (100000 + 10000)
Vout = 4.36

```

Since the analog input can handle up to 5V, then that should be OK. However I would test the voltage divider output first with a multimeter to make sure it doesn't exceed 5V - before connecting it to the Arduino.

---

You would probably need to change the code to test for different ranges of input voltages, other than what is used for the 12V battery.
> 2 votes

# Answer
To get a smoother switch from one level to another you could introduce another resistor and use analogWrite() to dim one LED and make next brighter.

Ref.: https://www.arduino.cc/en/Tutorial/PWM
> 1 votes

---
Tags: battery
---


# Question
Title: Is it possible to connect nodemcu to mobile internet and how?
Guys i have done project home automation over Android in which i have use NodeMCU and relay to control switching of lights but this is a offline project.

Now I want to connect it with internet please tell me if I can connect NodeMCU to mobile WiFi.

I don't have router at home please tell me if it is possible and how?

# Answer
If you have a mobile wifi router, the nodemcu can connect to it just as it would connect to a fixed router. If you want to connect the nodemcu to the internet without a mobile wifi router, you can use a gsm/gprs/3G/4G module, for example the SIM800L. (Provided the location has cell coverage.)
> 2 votes

# Answer
I have a wifi library.This is how I connect the NodeMCU with that library.

```
#include <ESP8266WiFi.h>

#define WIFI_SSID "name_of_your_hotspot"
#define WIFI_PASSWORD "password_of_hotspot"

void setup() {
   Serial.begin(9600);
   WiFi.begin( WIFI_SSID,  WIFI_PASSWORD) ;

    Serial.print("connecting");

    while (WiFi.status() != WL_CONNECTED ) {
        Serial.print(".");
        delay(500);
    }

     Serial.println();
     Serial.print("connected");
     Serial.println(WiFi.localIP);
}

void loop () {
    // Your code
}

```

I used this tested and working code. Comment if any issue.

Make sure you import the library.

Hope this fixed your issue.

***EDIT : 4th Jan 2018***

I know this topic is old and maybe the OP solved this problem but I saw many people struggling with this same situation how to connect nodeMCU to an internet connection.

So, I created a medium post with detailed information on how to Connect ESP8266 module to the internet? You can read the story here (I am not paid or sponsored by this post I made this story to help the newbies)

If you still have any problem comment down below or add a response in my medium story.
> 1 votes

# Answer
You don't need an external router or LAN to connect nodeMCU with Android or any other TCP/IP device. nodeMCU is capable of works as a WiFi access point, among other things.

You use he function `wifi.setmode()` to configure the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

1. **Station mode**, where the NodeMCU device joins an existing network.
2. **Access point** (AP) mode, where it creates its own network that others can join.
3. **Station + AP mode**, where it both creates its own network while at the same time being joined to another existing network
4. **WiFi off**

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.

Now, to connect to Internet you will need something else. You can use a SIM800/SIM900 module, which let you conect your nodeMCU to Internet and send/receive SMS.

In this scenario, nodeMCU will connect directly to Internet for your remote connections, and will also works as WiFi router for local connections.

Keep in mind that nodeMCU is a lightweight router.
> 0 votes

---
Tags: esp8266, nodemcu
---


title: Midi Program not sending notes

text:
# Question
Title: Midi Program not sending notes
I'm working on a midi device with a pro micro, it's reading as a midi device, but not outputting any notes, here's my program: const int button1 = 2; const int button2 = 3; const int button3 = 4; const int button4 = 5; const int button5 = 6; const int button6 = 7;

```
int note = 0;

const int c3 = 36;
const int d3 = 38;
const int e3 = 40;
const int f3 = 41;
const int g3 = 43;
const int a3 = 45;

void setup() {

  pinMode(button1,INPUT);
  pinMode(button2,INPUT);
  pinMode(button3,INPUT);
  pinMode(button4,INPUT);
  pinMode(button5,INPUT);
  pinMode(button6,INPUT);

  Serial.begin(31250);

}

void loop() {
  int button1State = digitalRead(button1);
  int button2State = digitalRead(button2);
  int button3State = digitalRead(button3);
  int button4State = digitalRead(button4);
  int button5State = digitalRead(button5);
  int button6State = digitalRead(button6);

  if (button1State == HIGH) {
    note = c3;
    noteOn(0x90, note, 0x64);
  }
  if (button1State == LOW) {
    note = c3;
    noteOn(0x90, note, 0x00);
  }

  if (button2State == HIGH) {
    note = d3;
    noteOn(0x90, note, 0x64);
  }
  if (button2State == LOW) {
    note = d3;
    noteOn(0x90, note, 0x00);
  }

  if (button3State == HIGH) {
    note = e3;
    noteOn(0x90, note, 0x64);
  }
  if (button3State == LOW ) {
    note = e3;
    noteOn(0x90, note, 0x00);
  }

  if (button4State == HIGH) {
    note = f3;
    noteOn(0x90, note, 0x64);
  }
  if (button4State == LOW) {
    note = f3;
    noteOn(0x90, note, 0x00);
  }

  if (button5State == HIGH) {
    note = g3;
    noteOn(0x90, note, 0x64);
  }
  if (button5State == LOW) {
    note = g3;
    noteOn(0x90, note, 0x00);
  }

  if (button6State == HIGH) {
    note = a3;
    noteOn(0x90, note, 0x64);
  }
  if (button6State == LOW ) {
    note = a3;
    noteOn(0x90, note, 0x00);
  }

}

void noteOn(int cmd, int pitch, int velocity) {
  Serial.write(cmd);
  Serial.write(pitch);
  Serial.write(velocity);
}

```

# Answer
> 1 votes
You are handling your buttons in completely the wrong way. You are basically saying:

> While I press this button send a constant stream of NOTE ON commands. Otherwise send a constant stream of NOTE OFF commands.
>
> At the same time, send more NOTE OFF commands because the other buttons aren't pressed.

So you can see it's going to be a bit of a mess.

Instead you need to detect *changes* in the state of a button.

For example:

```
void loop() {
    static bool oldButton1 = LOW;

    bool button1State = digitalRead(button1);

    if (button1State != oldButton1) { // It changed from last time
        oldButton1 = button1State; // Remember it for next time
        if (button1State) { // Pressed
            noteOn(0x90, c3, 0x64);
        } else { // Released
            noteOn(0x80, c3, 0x00); // Note: 0x80 is NOTE OFF, not 0x90.
        }
    }

    ... etc for the other buttons ...
}

```

# Answer
> 0 votes
Check:

* If your serial properties are ok (baudrate 31250, 8 bits, 1 stop bit)
* Check if noteOn is really called (print out the values which are sent)
* Show your MIDI circuit, assuming you think no MIDI notes are send because you have a MIDI connector attached.
* Use a protocol analyzer if you have one to check the MIDI signals sent
* Check the components of your circuit, e.g. if you use an opto-coupler, what types is it? some are too slow for MIDI
* Do not use virtual serial ports, I tried with MIDI and they give bad results (checked on Uno).

---
Tags: arduino-pro-micro, midi
---


title: Arduino MEGA2560 Standalone

text:
# Question
Title: Arduino MEGA2560 Standalone
I had an Arduino UNO (ATmega168) standalone working, but I need more pins, and I decided to use the ATmega2560, I was searching for some schematics, and none of them shown an ATmega2560 standalone, only the full Arduino, with the FTDI, power transformers... etc integrated. So taking parts from those designs, I made this, but I don't know if it's enough or I need Something more:

Note: VCC2 is connected to 5V.

# Answer
> 3 votes
You need more decoupling capacitors - one per VCC and AVCC pin, plus a larger (10µF) for the whole chip.

You need a pullup resistor (and maybe button) on RESET.

# Answer
> 1 votes
1. check the datasheet;
2. I would put a pull-up on the reset pin, plus a small capacitor;
3. crystal + capacitors as optional;
4. AVCC to VCC with filtering, if you need good analog performance;
5. separate Vbat domain, if it has one.

...

---
Tags: atmega2560
---


# Question
Title: Wiring diagram for Arduino to prevent relay firing on reboot
I'm starting to explore using an Arduino to control a couple of switches programatically. I have read somewhere about relays firing during reboot due to floating inputs/outputs during the reboot phase.

What is the best way to ensure that a relay will not fire on a reboot?

Is there a simple wiring diagram to explain it? I am using an Arduino Uno and a Relay Module.

Any assistance would be greatly appreciated.

# Answer
> 3 votes
Two things:

1. If that relay uses a FET input with no pulldown then you should add your own. If it uses an opto-isolator there is no floating problem to deal with.
2. Don't use pin 13 for a relay - that is connected to the LED which blinks during reset and will "flash" your relay.

# Answer
> 3 votes
You can add a pull down/up resistor between the wire and ground/vcc so that when the arduino pin is set to high impedance during reboot the wire is pulled low/high as desired.

# Answer
> 1 votes
> What is the best way to ensure that a relay will not fire on a reboot?

put pull-up/down, as appropriate, on those pins.

---
Tags: relay
---


# Question
Title: Avoiding false rising and falling edge when using demultiplexer
I have 8 sets of 8 push buttons. There is a Teensy and a demultiplexer. The demultiplexer has 8 outputs. When an output is selected it is pulled low. Each output is connected to a group of 8 push buttons. The 8 push buttons are then connected to 8 pullup inputs on the Teensy.

Each group of 8 push buttons is connected to a unique demultiplexer output, but all the push buttons are connected to the same 8 inputs on the Teensy. That is, push button #1 in group 1 shares a Teensy input with push button #1 in group 2. The push buttons are isolated from each other with diodes.

I'm using `bounce.h` for debouncing. It looks for rising and falling edges.

The problem is this:

* Push button #1 in group #1 is pressed, pulling that input low, causing a falling edge to be detected. This is good.
* The demultiplexer shifts to group #2, where the #1 button hasn't been pressed, and thus is high.
* Because both #1 buttons in group #1 and #2 share the same input line, the Teensy sees this change as a rising edge. This is undesired.

What is the better approach to this?

Thanks,

Dan

# Answer
> 1 votes
To do multiplexing with bounce.h you will need one bounce object *per button*. That's 64 bounce objects for an 8x8 matrix.

Then you only want to update the bounce objects *for the group you currently have active*.

That is:

1. Switch to group 1.
2. Update objects 1-8
3. Switch to group 2
4. Update objects 9-16
5. ... etc ...

You need one object per button so that the internal data can track the state of that specific button, and you only update the 8 objects for the currently selected group otherwise the objects that aren't associated with that group will get confused by incorrect data.

# Answer
> 0 votes
> What is the better approach to this?

write your code so it debounces each pin / group of pins separately.

looks like your code used global / static variables.

---
Tags: teensy, multiplexer, debounce
---


# Question
Title: Send Color value from Processing into Arduino
I know this has been asked before, but I'm new to Arduino and Processing, and I'm trying to take this step by step.

I would like to pass an RGB value from processing, into Arduino via the Serial.Write/Read.

I have my Processing as:

```
void draw(){

  //orange colour in RGB values
  color _rgbColor = color(255, 40, 0);

  //convert colour into hex
  String _hexColor = hex(_rgbColor, 6);

  //convert colour into binary
  String _binaryColor = binary(_rgbColor);

  //pass colour to port
  myPort.write(_hexColor);
  delay(500);
}

```

I assume I can just pass the HEX value straight across, right?

First problem I get is that I can't debug what my Arduino device is getting (when I run the Processing program, the Serial Monitor wont work. Seems like I can only use one or the other). I can print the myPort.read within my Processing after the delay, and I get:

> -1

So I'm not quite sure what I'm doing wrong there.

On the Arduino side, I'm using Serial.read() to retrieve the Serial data, which I assume will all be broken down into bytes, so I need to then convert it into a HEX formate, right?

----- Update -----

I now know that I need to break down my color variable into a char-message. I'm guessing I can do something like this then, for example: And then on the other side (Arduino), I need to rebuild the message, right?

```
if(mousePressed == true){
    //Red
     myPort.write('2');
     myPort.write('5');
     myPort.write('5');
     myPort.write(',');

     //Green
     myPort.write('0');
     myPort.write('3');
     myPort.write('0');
     myPort.write(',');

     //Blue
     myPort.write('0');
     myPort.write('0');
     myPort.write('0');
     myPort.write('\n');
  }

```

My Arduino script is as follows, is this an okay route to go down?

```
String message;
void loop() {

  int _size = Serial.available();

  if(_size > 0){

    char value = Serial.read();
    message += value;

    //full message received (255,255,255)
    if(message.length() == 11){
      String _red = message.substring(0,3);
      String _green = message.substring(4,7);
      String _blue = message.substring(8,11);
      Serial.println("R:" + _red + " G:" + _green + " B:" + _blue);

      //apply to light system
      setColour(_red.toInt(), _green.toInt(), _blue.toInt());

      //clear buffer
      message = "";
      Serial.flush();
    }
  }
}

```

# Answer
> 1 votes
Add `print(_hexColor);` to you processing sketch. The value it's sending should appear in the Processing Console (at the bottom)

# Answer
> 1 votes
I know I'm late, but actually got a working solution, when I was working out a solution for this.

Code in Processing assuming variable `myPort` is handled in `setup()`:

```
void draw() {
    int r = 255;
    int g = 123;
    int b = 2;
    myPort.write('S'); // tell the arduino to do something with leds
    myPort.write(r);
    myPort.write(g);
    myPort.write(b);
}

```

Code for Arduino loop:

```
void loop() {
  int r;
  int g;
  int b;
  if(Serial.available()) {
    if(Serial.read() == 'S') {
      while(!Serial.available()){}
      r = Serial.read();
      while(!Serial.available()){}
      g = Serial.read();
      while(!Serial.available()){}
      b = Serial.read();
    }
    delay(10); // some recovery time, not sure if nessecary

    // do something with rgb values
  }
}

```

This works for me with every possible RGB range. It's not the most elegant solution, but by far better then converting between strings/chars and ints with different bit counts on different devices.

---
Tags: serial, rgb-led, processing-lang
---


# Question
Title: Differences between Arduino IDE versions
I run Arduino IDE on both my Mac and under Raspbian on a Raspberry Pi, both running the latest version of OS.

The Raspberry Pi has `Arduino 2:1.0.5+dfsg2-4.1` and I am running the latest `1.8.4` on macOS. Debian is always somewhat behind the latest software, and this has not concerned me before, as I have never had issues before. (I know I could download the latest ARM32 build or compile from source, but this would probably generate a lot of dependencies.)

I have recently run into a couple of problems. Compiling a script which has `#include <SdFat.h>` generates an error, although the library is present in `~/sketchbook/libraries/SdFat/src/SdFat.h`. This does not seem to be an issue on macOS.

I was also trying to program an Atmega using a Uno as ISP as in "Using an Arduino as an AVR ISP". I have done this in the past, but the instructions and the Arduino program seem to have changed; there is no longer "Upload Using Programmer" menu, but suggests the "Burn Bootloader" command. Does this upload both the Bootloader and Sketch?

# Answer
> Debian is always somewhat behind the latest software

No, when it comes to the Arduino IDE Debian is *frozen* on an ancient version.

1.0.5 is considered to be too old to use. Many many things have changed since then - bug fixes, optimisations, new API components. And not least the implementation of the Board Manager for installing support for more boards, both by Arduino and other makers, and support for multi-arch libraries (which your SdFat library is with a `src` folder in it).

You should never install the Arduino IDE from the Debian repositories. Instead you should download the current version of the Arduino website (http://arduino.cc/download) as a tar.\z file and extract it into a folder and run it from there.
> 6 votes

# Answer
Majenko answered why my sketch did not compile.

I decided to give it a try and downloaded `arduino-1.8.4-linux32.tar.xz`. I was somewhat concerned that there seemed to be no indication whether the `Linux ARM` supported ARM6, or ARM7.

The download itself contained absolutely no information, not even a README. I ran `install.sh` as outlined in https://www.arduino.cc/en/Guide/Linux and Arduino IDE installed alongside the existing Arduino IDE, and worked (at least on the PI3).

I also solved my issue using a Uno as ISP. The documentation on the Arduino site now describes "Use the Burn Bootloader command". I found the missing "Upload Using Programmer" menu under the Sketch menu.
> 1 votes

---
Tags: arduino-ide, raspberrypi
---


# Question
Title: EPS8266 ESP-01: LED manipulation seems to interfere with serial communication
I'm playing around with this udp-example. Both this and the blink-example work perfectly. Now I would like to use the LED to indicate what the ESP is currently doing, as well as reading some data over Serial. My code looks like this:

```
void setup(){
  Serial.begin(115200);
  Serial.setTimeout(500);
  while(Serial.available()==0){
  }
  String password = Serial.readStringUntil('.');
  Serial.println(password);
  WiFi.begin(ssid.c_str(), password.c_str());
  //pinMode(LED_BUILTIN, OUTPUT);
  while (WiFi.status() != WL_CONNECTED){
    //digitalWrite(LED_BUILTIN, LOW);
    delay(250);
    //digitalWrite(LED_BUILTIN, HIGH);
    delay (250);
  }
  Serial.println("connected");
  Udp.begin(localUdpPort);
}

```

It works fine, but if I uncomment the led-lines the serial communication doesn't seem to work anymore. All the stuff that is printed on the Serial Monitor is now messed up (missing characters, ...). Is there a problem with my code or what else could be possible going wrong here?

EDIT: I recently tried the same code again, but used an additional power supply (3.3V, 500mA) for the chip. However, this didn't resolve the problem.

# Answer
> 7 votes
I would bet that the built-in LED pin is also the TX pin for the serial interface.

Check here, **LED Pin** section: http://www.esp8266.com/wiki/doku.php?id=esp8266\_gpio\_pin\_allocations

> LED Pin
>
> GPIO1, which is also TX, is wired to the blue LED on many devices. Note that the LED is active low (connected to Vcc and sinks through the chip to ground) so setting a logical value of 0 will light it up. Since GPIO1 is also the TX pin, you won't be able to blink the LED and perform Serial communications at thew same time unless you switch TX/RX pins.

This would be confirmed if the LED blinks when serial communication is active.

If this is the case you would have to add your own LED on a different pin, or switch the RX/TX pins.

---
Tags: serial, esp8266, led, arduino-nano, wifi
---


title: Connecting Arduino to the ESP8266

text:
# Question
Title: Connecting Arduino to the ESP8266
I want to run more stepper motors and would like to know if there is a way to connect the Arduino and the ESP8266 NodeMCU together for more functioning.

# Answer
> 3 votes
Absolutely. I'll use the Arduino UNO and the ESP8266-01 WiFi module as an example:

---

1. The ESP8266 works with 3.3V and not 5V, so you need to connect the 3v3 pin on the Arduino to the VCC and CH\_PD pins on the ESP8266.
2. Connect the GND pin on the Uno to the GND pin on the ESP.
3. Connect the RESET pin on the Uno to GND. Grounding the RESET pin effectively causes your Arduino to work as a dumb USB to serial connector (which is what we want to talk to the ESP8266).
4. Connect the CH\_PD pin on the ESP8266 to the 3.3V line
5. Connect the RXD pin on the Arduino Uno to the RX pin of the ESP8266.
6. Connect the TXD pin on your Arduino Uno to the TX pin of the ESP8266.

Normally, when you want two things to communicate over serial, you'd connect the TX pin of one to the RX of the other (send --\> receive). In this case, however, the Arduino isn't talking to the ESP8266; the computer is talking to the ESP8266 via the Arduino.

---
Tags: esp8266
---


# Question
Title: User configuration file does not exist or is not a regular file, skipping
I am facing issues while uploading sketch to **Adafruit Feature 32u4 Bluefruit LE** devices. When i try to upload **Blink** demo it was working fine and my device also blinking, But bellow error i am getting every time when i upload sketch.

```
   System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
     User configuration file is "/Users/myMacmnin/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

```

I am using **Adafruit Feature 32u4 Bluefruit Le device,Arduion 1.8.3 version, MacMini with macOs Sierra(10.12.3).**

# Answer
> 0 votes
Finally i found answer for my question, It happen because of uploading sketch in selected pin.

```
// Neopixel
//#define PIN            6   /* Pin used to drive the NeoPixels */
#define PIN            13   /* Pin used to drive the NeoPixels */

```

I Changed Pin 6 to 13 , it's worked for me.

---
Tags: arduino-nano, adafruit
---