# Question
Title: How to stop transmission i2c on LCD 16x4 i2c
i want to try to stop communicaton I2C between arduino and lcd I2C but i don't see any command to stop this communication. I try with Wire.endTransmission or Wire.end but the transmission to the LCD continue without problem. I'm using this library NewliquidCrystal and inside no command for end transmission. I need to interupt that communicaton for have a good management of lcd or if know a new library with best features. Thank's for help

# Answer
> 2 votes
> I need to interupt that communicaton for have a good management of lcd or if know a new library with best features. Thank's for help

This sounds like a classical X-Y problem. You have decided on a solution and asking about some "magic" functionality without understanding the library or how the I2C bus works.

It would be better to try to describe the original issue, investigate, propose and discuss solutions. Basically better understand the original issue.

Back to your question:

> Wire.endTransmission()

does not really do what you think. It marks the end of a block to be transmitted (previous Wire.write()) and starts the actual transmission to the slave.

This is what the manual says:

> **Wire.endTransmission()**
>
> Description
>
> Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that were queued by write().

---
Tags: i2c, lcd
---


# Question
Title: Serial not displaying sketch for MPU6050
I followed this tutorial on youtube: https://www.youtube.com/watch?v=M9lZ5Qy5S2s

Where he provided the code below. The problem I'm having is the serial monitor shows nothing. I tried changing the baud to 115200 and still nothing showed up. I'm using an Arduino nano.

Update: I wrote a Serial.print in each function (printing the name of the function), and I found it just printed up to "recordAccelRegisters" then stopped. Then I put a Serial.print after each line in the function, and it prints until the line `while(Wire.available() < 6);` Is this a problem with the while function or I2C?

Ok, so I reinstalled Arduino and got this message on the serial print with the I2C test:

"Scanning... I2C device found at address 0x69 ! done."

```
#include <Wire.h>

long accelX, accelY, accelZ;
float gForceX, gForceY, gForceZ;

long gyroX, gyroY, gyroZ;
float rotX, rotY, rotZ;

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

void loop() {
  recordAccelRegisters();
  recordGyroRegisters();
  printData();
  delay(100);
}

void setupMPU(){
  Wire.beginTransmission(0b1101000); //This is the I2C address of the MPU (b1101000/b1101001 for AC0 low/high datasheet sec. 9.2)
  Wire.write(0x6B); //Accessing the register 6B - Power Management (Sec. 4.28)
  Wire.write(0b00000000); //Setting SLEEP register to 0. (Required; see Note on p. 9)
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x1B); //Accessing the register 1B - Gyroscope Configuration (Sec. 4.4)
  Wire.write(0x00000000); //Setting the gyro to full scale +/- 250deg./s
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x1C); //Accessing the register 1C - Acccelerometer Configuration (Sec. 4.5)
  Wire.write(0b00000000); //Setting the accel to +/- 2g
  Wire.endTransmission();
}

void recordAccelRegisters() {
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x3B); //Starting register for Accel Readings
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6); //Request Accel Registers (3B - 40)
  while(Wire.available() < 6);
  accelX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
  accelY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
  accelZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
  processAccelData();
}

void processAccelData(){
  gForceX = accelX / 16384.0;
  gForceY = accelY / 16384.0;
  gForceZ = accelZ / 16384.0;
}

void recordGyroRegisters() {
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x43); //Starting register for Gyro Readings
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6); //Request Gyro Registers (43 - 48)
  while(Wire.available() < 6);
  gyroX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
  gyroY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
  gyroZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
  processGyroData();
}

void processGyroData() {
  rotX = gyroX / 131.0;
  rotY = gyroY / 131.0;
  rotZ = gyroZ / 131.0;
}

void printData() {
  Serial.print("Gyro (deg)");
  Serial.print(" X=");
  Serial.print(rotX);
  Serial.print(" Y=");
  Serial.print(rotY);
  Serial.print(" Z=");
  Serial.print(rotZ);
  Serial.print(" Accel (g)");
  Serial.print(" X=");
  Serial.print(gForceX);
  Serial.print(" Y=");
  Serial.print(gForceY);
  Serial.print(" Z=");
  Serial.println(gForceZ);
}

```

https://github.com/VRomanov89/EEEnthusiast/blob/master/MPU-6050%20Implementation/MPU6050\_Implementation/MPU6050\_Implementation.ino

# Answer
> 1 votes
Ground the AD0 pin. I thought the address should be set to 0x68 without this, but from what I've seen it fluctuates between 0x68 and 0x69. If you want the address to be 0x69 short the AD0 pin to 5V. I guess this would be useful if you need to use 2 MPU6050s with different I2C addresses without doing something in software. Haven't looked into that yet

Still, the I2C scanner for arduino may be useful for detecting the address/debugging: http://playground.arduino.cc/Main/I2cScanner

---
Tags: serial, mpu6050
---


title: Serial read in ESP8266-01 not working

text:
# Question
Title: Serial read in ESP8266-01 not working
I am new to programming. kindly bear with me. I am trying to use ESP8266-01 device for serial read and write application. Before writing the full program for my application, i wanted to test how it functions. I programmed the ESP8266-01 device to read the data from its Rx pin and write it to Tx pin. I used a standard USB-TTL cable to send and receive data from PC using Hterm. The ESP device does not read the data available at the Rx pin. what am i missing ?. Also kindly help me in understanding the difference between serial.println and serial.write with respect to ESP8266-01 device. As per the program if i check the data from the Tx pin of the ESP8266 device, i get only "No data received". I am using arduino IDE 1.6.11. Kindly provide some guidance

regards

Sriniketh

```
#include <ESP8266WiFi.h>

void setup() {

Serial.begin(9600);
}

void loop()
{
  byte serin=0;
  if (Serial.available()>0)
  {
    serin=Serial.read();
    delay(100);
    Serial.println(serin);
    delay(100);
    Serial.write(serin);
  }
  else
  {
    Serial.println("No data received");
    delay(5000);
  }

}

```

# Answer
A circuit diagram or photo would help, but I would guess you have taken the lead from the PC that is marked Rx and connected to the pin on the ESP marked Rx. That's the wrong thing to do. Firstly the PC will use 5V and the ESP uses 3.3V, so you need a little board called a level shifter something like this 2 channel level shifter. This will let a 3.3v device talk to a 5V device. Some ESP boards are 5V tolerant, but I don't know what you have so ...

Then when you "talk" over serial you need to cross the Tx and Rx between the two devices, so the can 'hear' each other

```
 PC - Tx  ---> Rx - ESP
 PC - Rx <---- Tx - ESP

```

(Lots of other level shifters are available and a lot are cheaper than the example shown, a lot cheaper!)
> -1 votes

---
Tags: serial, esp8266
---


# Question
Title: Light up more than one LED connected to 74HC595 Shift Register
I have a 74HC595 Shift Register with a LED (and resistor) on each of the 8 output pins. I can light them all up I can light one up

How do I light two up? For example the one on pin 2 and the one on pin 7

I used this a my starting point. https://learn.adafruit.com/adafruit-arduino-lesson-5-the-serial-monitor?view=all

Is 74HC595 Shift Register the correct componet to use?

# Answer
> 1 votes
You don't mention if you are using and Arduino, but I will assume that is the case.

Using the shift register to light up LEDs is fairly straight forward.

You can use the ShiftOut() function to send out an 8bit binary value to the register. https://www.arduino.cc/en/Reference/ShiftOut

In summary however, if you want to light up the LEDs on the output pins 2 and 7 you would shift out b01000010 to the shift register. If you wanted pins 4, 5 and 7 to light up, you shift out b01011000. These assume the least significant bit is sent first.

Here's an example:

```
// set shift register output pins 2 and 7 to high
uint8_t data = 1<<2 | 1<<7; // use bit shifting

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, data); // send the data
digitalWrite(latchPin, HIGH);

```

# Answer
> 0 votes
> How do I light two up? For example the one on pin 2 and the one on pin 7

If the LEDs are active high, sending 0x82 lights up the two LEDs.

If they are active low, sending ~0x82 lights up the same LEDs

---
Tags: led, shift-register
---


# Question
Title: What difference between readString and while loop read
From Arduino code, I have a question for SoftwareSerial Class

First: when I use more example for Esp8266 those functions use while loop to read response string from Esp when we send AT\_Command to ESP.

```
getResponse(const uint32_t  wait) {
    String tmpData = "";
    long int time = millis();
    while ((time + wait) > millis()) {
        while (esp8266->available() > 0) {
            char c = esp8266->read();
            if (c == '\0') continue;
            tmpData += c;
        }
    }
    tmpData.trim();
    return tmpData;
}

```

I know that SoftwareSerial Class have a public method is **readString()** then I'm tried to use that and it return same result returned by while loop read:

```
getResponse(const uint32_t  wait) {
    String tmpData = "";
    tmpData = esp8266->readString();
    return tmpData;
}

```

Thanks for any. I'm working on improving my Eng. Regards

# Answer
> 1 votes
Your `while` loop reads all the characters up until it reaches character 0 (it also has a timeout, although the timeout has been coded wrong since it can't deal with clock rollover). The `.readString()` method reads characters until no characters arrive within a timeout period (1s if memory serves me correctly).

Your `while` loop is the more reliable method since it uses a specific delimiter to identify blocks of data (strings) rather than assuming that:

1. The string will all arrive with no delays greater than the timeout
2. The strings will be sent with a gap of at least the timeout length between them.

Personally I would never recommend using any of the "helpful" functions provided for reading from a `Stream` object other than the basic `.read()` function.

---
Tags: arduino-ide, softwareserial
---


# Question
Title: Using an esp8266, how can I create a circuit to measure 2 different analog inputs (not simultaneously) with only one ADC pin available (A0)
I'm currently using a circuit with 2 separate transistors that can be switched on or off to measure 2 separate voltage inputs.

The reason for this is because I'm using an esp8266 which has only one ADC input at pin A0 and I need to measure light intensity from an LDR as well as voltage from a solar panel.

The LDR is wired with a voltage divider. The voltage input from the solar panel is 0 - 5v, so I have that wired with a voltage divider to output a max of 3.3v (pin A0 is 0 - 3.3v). The problem is that in complete darkness, the ADC is still reading the LDR with a value of around 260 (should be close to zero) and with bright light reading around 850 (should be close to 1023). Also, the voltage measured from the solar panel (divided to 3.3v) is returning anywhere from 600 (0v) to around 840 (3.3v).

I've tried these input measurements separately with expected results. It's having the option to switch inputs is what is tripping me up.

So, is my approach correct or is there another way to do this?

Note: I would have included a circuit diagram if I knew anything about circuits and making diagrams.

# Answer
> 1 votes
There's two basic solutions, both of which require the addition of an external chip:

1. Use an analog multiplexer to select the different devices to connect to the ADC input
2. Use an external (I2C or SPI) ADC chip. These can give you higher resolutions than the internal ADC and many more inputs (depending on the chip you choose).

My recommended solution would be to get an external ADC chip.

---
Tags: esp8266, adc, transistor, digital-analog-conversion
---


# Question
Title: Can't send SoftwareSerial to Class Object
I have a problem when I try to use SoftwareSerial in a class..

**Here my detail** My class

```
class MyEsp8266
{
 protected:
     SoftwareSerial *esp8266;
 public:
     MyEsp8266(SoftwareSerial *_esp8266){
           esp8266 = _esp8266;
     }
     void begin(int baud){
        esp8266->begin(baud);
     }
     String testAT(){
          esp8266->println("AT");
          return esp8266->readString();
     }
}

```

**My Arduino code**

```
#include <SoftwareSerial.h>
#include "MyEsp8266.h"
// the setup function runs once when you press reset or power the board

SoftwareSerial _esp(10, 11);
MyEsp8266 wifi(&_esp);

void setup() {
    Serial.begin(9600);
    wifi.begin(115200);
    Serial.println(wifi.testAT());
}

```

It doesn't log anything **But** when I have used all code in Arduino code it worked.

```
#include <SoftwareSerial.h>
// the setup function runs once when you press reset or power the board

SoftwareSerial _esp(10, 11);

void setup() {
    Serial.begin(9600);
    _esp.begin(115200);
    _esp.println("AT");
    Serial.println(_esp.readString());
}

```

Thank any tips. Regards.

# Answer
> 1 votes
This is more of a work-around than a solution, but the code you're trying to get to work, worked for me once I changed

```
wifi.begin(115200);

```

to

```
wifi.begin(9600);

```

(sorry I don't have enough karma to just comment)

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


# Question
Title: Using Arduino's hardware serial to control SIM900
I have a SIM900 board which has a serial interface. I'm trying to control it using Arduino Uno. I've tried using SoftwareSerial on pins 10 (RX) and 11 (TX) to talk to my board. It works OK with different baud rates (SIM900 has auto-bauding). I'm connecting pin 10 directly to my board, but pin 11 is connected through a voltage divider in order to lower voltage from 5 V to 2.8 V (SIM900 uses 2.8 V CMOS logic levels).

But now I want to use Arduino's hardware UART to talk to SIM900. I'm using pins 0 and 1 with similar design as above (also using voltage divider). I just can't get it to work. No matter what I do I can't see any communication. I've tried different baud rates, but it just doesn't work. Here is my code:

```
void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);

  delay(10000);
  Serial.write("AT\r");
  delay(1000);
  if (Serial.available())
  {
    digitalWrite(13, HIGH);
  }
}

void loop()
{
}

```

So I should see a LED light up but nothing happens (SIM900 responds with "\r\nOK\r\n" to "AT\r"). What am I doing wrong?

# Answer
2.8V is not high enough to register as a high on an AVR input. You will need to use a level converter to raise the TX line of the SIM900 from 2.8V to 5V.
> 0 votes

# Answer
Arduino with sim900 module is disabled after a day or course sim900 module is completely safe and always receives sms but the Arduino module led after one or more days is no longer able to enable or disable.

```
#include <SoftwareSerial.h>
SoftwareSerial SIM900 (7, 8);
char incoming_char = 0; // Will hold the incoming character from the Serial Port.
int led_status = 0;
int led1 = 10;
int led2 = 13;
void setup () {
 pinMode (led1, OUTPUT);
 pinMode (led2, OUTPUT);
 SIM900power ();
  Serial.begin (19200); // Set the baud rate
 SIM900.begin (19200); // For GSM shield
 delay (20000); // Give time to log on to network.

 SIM900.print ( "AT + CMGF = 1 \ r"); // Set SMS mode to text
 delay (100);
 SIM900.println ( "AT + CNMI = 2,2,0,0,0 \ r");
 //SIM900.print("AT+CLIP=1\r "); // Turn on caller ID notification

 digitalWrite (led1, LOW); // Set led to LOW
 digitalWrite (led2, LOW);
// Serial.println ( "AT + CMGD = 1,4"); // Delete all SMS in box
}

void sendSMS (char led_status) {// SEND SMS

 SIM900.print ( "AT + CMGF = 1 \ r"); // AT command to send SMS message
 delay (1000);
 SIM900.println ( "AT + CMGS = \" + 9xxxxxxxx \ "\ r"); // Recipient's mobile number, in international format
 delay (1000);
 if (led_status == 0)
    {
      SIM900.println ( "ALARM ON");
      }
else

    {
      SIM900.println ( "ALARM OFF");
    }
  delay (1000);
 SIM900.println ();
 delay (5000); // Give module time to send SMS
}
void SIM900power ()
// Software equivalent of pressing the GSM shield "power" button
{
  digitalWrite (9, HIGH);
  delay (1000);
  digitalWrite (9, LOW);
  delay (7000);

}

void loop () {
// # A1s on & # a0s off
if (SIM900.available ()> 0)
{
incoming_char = SIM900.read ();
if (incoming_char == '#')
  {
  delay (10);
  incoming_char = SIM900.read ();
  if (incoming_char == 'a')
    {
  delay (10);
  incoming_char = SIM900.read ();
  if (incoming_char == '0')
  {
  digitalWrite (led1, LOW);
  digitalWrite (led2, LOW);
  }
else if (incoming_char == '1')
  {
  digitalWrite (led1, HIGH);
 digitalWrite (led2, HIGH);
  }
else if (incoming_char == 'S')
  {
  digitalRead (led1);
  led_status = digitalRead (led1);
  led_status = digitalRead (led2);
  Serial.print (led_status); // Prints status on serial terminal
  sendSMS (led_status);
  }
delay (10);
     }
                        // End AT command with a ^ Z, ASCII code 26

  delay (5000);

  led_status = digitalRead (led1);
  led_status = digitalRead (led2);
  Serial.print (led_status); // Prints status on serial terminal
  sendSMS (led_status);
  SIM900.println ((char) 26);
          }
   }
}

```
> 0 votes

---
Tags: gsm
---


# Question
Title: Cutting off OneWire/SDA line with transistors
I am developing a pcb for a design I am working on and I need to share a pin to be used by a ds18b20 (onewire) and some possible I2C sensors. There would be just one of each at a time.

I was thinking about using a couple of transistors. One would cut or enable ds18b20 data line and the other one, the same for SDA line. So I would enable the first one and disable the second one or viceversa.

Do you think this is possible? I don't have transistors right now to test it. I have to order some of them. I was thinking about a bd228. Would this add some errors/delays/whatever in signal information? A kind of distorsion I mean. Or should it work?

EDIT: I will try to explain a bit my project.

My idea is to have a box with 5 sockets. Each one of them will be a different data input. They should be able to use a wide variety of sensors, ds18b20, dht22, open/close door (1 or 0 signal)... Also I would want to include some I2C sensors.

I was thinking about BME280 for example.

My idea is that the user could set which sensor is connected each time so the arduino can switch transistor behaviour to allow the connectivity to the digital pin or the I2C SDA (or SCL) pin.

I was thinking about using an I2C multiplexer to allow multiple BME280 to be at the same time so the first line would go to the socket1, second line socket 2...

# Answer
> 1 votes
For multiple I2C busses, it is allowed to share a single SCL and have a separate SDA line for each I2C bus. That means that as long as the SDA is inactive (high), you can do with the SCL whatever you want.

It might even be possible to share the SCL signal for I2C and 1-Wire, and use both. The SCL signal would then also be the 1-Wire signal. The I2C pulses are probably shorter than the start pulse of the 1-Wire. You would also have to do it right in the software to switch the function of the pins. As far as I know that has never been done, so you might get into a lot of trouble.

Transistors are not the right choice to multiplex signals, and the BD228 is definitely not okay. The I2C bus is a open-collector or open-drain bus with a current of maximum 3mA. The 1-Wire bus is roughly the same. It is possible with mosfets or with multiplexers (see: Nick Gammon about multiplexers). However, if you are going to add extra hardware there are probably better solution than combining I2C with 1-Wire.

Have you thought about the voltage levels ? Are you using a 5V Arduino board ? Most sensors are 3.3V. The DS18B20 will work with voltages as low as 3.0V, so 3.3V is no problem for the DS18B20.

Tell us what else is connected to your Arduino board. I'm sure there are better solutions.

Could you better specifiy what it is that you want to achieve ? When there is only I2C sensors or only 1-Wire sensors connected, you could run a i2c-scanner to check for I2C sensors. If nothing is found, do a Wire.end() and start the OneWire using the SCL pin. That could be done during startup and then you don't need extra hardware.

How long are the wires ? The 1-Wire bus can have long wires, but the I2C bus can only have short wires.

---
Tags: i2c, transistor, 1-wire
---


# Question
Title: Instance does not name a type, in function void loop (8x8 matrix)
Hey guys I'm doing a beginners project 8x8 matrix and I have some errors when compiling

The Errors are;

* MyBlink:0: error: 'Instance' does not name a type
* MyBlink.cpp: In function 'void loop()':

-MyBlink:40: error: 'row1' was not declared in this scope

```
 Instance code:
//the pin to control ROW
const int row1 = 2; // the number of the row pin 9
const int row2 = 3; // the number of the row pin 14
const int row3 = 4; // the number of the row pin 8
const int row4 = 5; // the number of the row pin 12
const int row5 = 17; // the number of the row pin 1
const int row6 = 16; // the number of the row pin 7
const int row7 = 15; // the number of the row pin 2
const int row8 = 14; // the number of the row pin 5
//the pin to control COl
const int col1 = 6; // the number of the col pin 13
const int col2 = 7; // the number of the col pin 3
const int col3 = 8; // the number of the col pin 4
const int col4 = 9; // the number of the col pin 10
const int col5 = 10; // the number of the col pin 6
const int col6 = 11; // the number of the col pin 11
const int col7 = 12; // the number of the col pin 15
const int col8 = 13; // the number of the col pin 16
void setup(){
int i = 0 ;
for(i=2;i<18;i++)
{
pinMode(i, OUTPUT);
}
pinMode(row5, OUTPUT);
pinMode(row6, OUTPUT);
pinMode(row7, OUTPUT);
pinMode(row8, OUTPUT);
for(i=2;i<18;i++) {
digitalWrite(i, LOW);
}
digitalWrite(row5, LOW);
digitalWrite(row6, LOW);
digitalWrite(row7, LOW);
digitalWrite(row8, LOW);
}
void loop(){
int i;
//the row # 1 and col # 1 of the LEDs turn on
digitalWrite(row1, HIGH);
digitalWrite(row2, LOW);
digitalWrite(row3, LOW);
digitalWrite(row4, LOW);
digitalWrite(row5, LOW);
digitalWrite(row6, LOW);
digitalWrite(row7, LOW);
digitalWrite(row8, LOW);
digitalWrite(col1, LOW);
digitalWrite(col2, HIGH);
digitalWrite(col3, HIGH);
digitalWrite(col4, HIGH);
digitalWrite(col5, HIGH);
digitalWrite(col6, HIGH);
digitalWrite(col7, HIGH);
digitalWrite(col8, HIGH);
delay(1000);
//turn off all
for(i=2;i<18;i++) {
digitalWrite(i, LOW);
}
delay(1000);
}

```

# Answer
> MyBlink:0: error: 'Instance' does not name a type

Once I deleted the line `Instance code:` on the first line both errors went away.

Cheers
> 1 votes

# Answer
There is typo in your program. Exactly you should comment out the first line of your code. Adding two slashes at the beginning of the first lines.

```
Instance code:

```

As this is not a valid syntax for your code. The compiler is not recognizing what are you trying to do. So it generates a second error because everything that comes after may generate an unknown error. Next time try to solve these kind of problems by reading your console log as it describes exactly at which lines the compiler has found an error. You can see that it generates an error at line 0:

> Myblink:0:error....

You have multiples errors on this program because as i said before sometimes they are generated as a consequence of your previous error. So you should also try to fix your errors from top to bottom.
> 0 votes

# Answer
The colon is a bit misleading, it is used in C++ to denote inheritance like this:

E.g.

```
class Form
{
  int _area;

  public Form(area)
  {
    _area = area;
  }
}

class Circle : class Form
...

```

However, this is not your intention probably.

Also the colon is used for calling base constructors and for labels to go to (goto, never use this).
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Sending data from Arduino to laptop via bluetooth using java
I intend to establish communication between my laptop and Arduino via Bluetooth. I'm using BlueCove Java API. I'm unable to understand how to send data to Arduino using this. There are no clear examples available on the internet regarding how to establish the communication between these two. Could somebody provide any information on this? I just want to send some string to Arduino, based on which it must send back something to the laptop. Any help on this would be greatly appreciated. Thank you.

# Answer
> 2 votes
I was able to establish bluetooth communication between Arduino and my laptop successfully. I made some observations, which I'd like to share. BlueCove library which I've been using, ultimately communicates to the Arduino by constructing a bluetooth URL. This bluetooth URL is of the form ***btspp://bluetooth\_address\_without\_colon:1;authenticate=false;encrypt=false;master=false***. To find the bluetooth address of a device, enter the following command in the terminal

```
hcitool scan

```

This will display a list of devices along with their addresses. For instance, if my HC-05 has an address  20:16:10:09:47:93 then the bluetooth URL can be formulated as ***btspp://201610094793:1;authenticate=false;encrypt=false;master=false***. Note that the '1' here represents the rfcomm channel. By observation, I've found that HC-05 modules use rfcomm channel 1. In your project, ensure that you import the two jars of BlueCove libraries viz bluecove-2.1.0.jar and bluecove-gpl-2.1.0.jar (latest version). You can download them from here. This is the Java code for communicating with the Arduino to turn an LED ON/OFF:

```
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
public class HC05 {
boolean scanFinished = false;
String hc05Url =
"btspp://201610094738:1;authenticate=false;encrypt=false;master=false"; //Replace this with your bluetooth URL
public static void main(String[] args) {
try {
new HC05().go();
} catch (Exception ex) {
Logger.getLogger(HC05.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void go() throws Exception {
StreamConnection streamConnection = (StreamConnection)
Connector.open(hc05Url);
OutputStream os = streamConnection.openOutputStream();
InputStream is = streamConnection.openInputStream();
os.write("1".getBytes()); //'1' means ON and '0' means OFF
os.close();
byte[] b = new byte[200];
Thread.sleep(200);
is.read(b);
is.close();
streamConnection.close();
System.out.println("received " + new String(b));
}
}

```

This the Arduino code for controlling the LED:

```
int ledPin = 13;
int flag = 0;
int receivedData;
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(9600);
}
void loop() {
if(Serial.available()>0){
receivedData = Serial.read();
flag = 1;
}
if(flag == 1){
switch(receivedData){
case '0':
digitalWrite(ledPin, LOW);
Serial.println("LED Turned OFF");
break;
case '1':
digitalWrite(ledPin, HIGH);
Serial.println("LED Turned ON");
break;
default:
Serial.println("Nothing here");
break;
}
flag = 0;
receivedData = 12;
}
Serial.flush();
}

```

Thanks to @Sigma for sharing some valuable information

Reference:

https://stackoverflow.com/questions/33473926/best-practice-java-serial-bluetooth-connection-hc-05

# Answer
> 1 votes
Are using a bluetooth module like HC-05 or HC-06? Then first establish an connection to the module. Then start sending bytes(a string). But first thing first start the connection. Ive only done it with an Android to Arduino, but still the Android is written with Java.

---
Tags: bluetooth, java
---


# Question
Title: Possible error in CAN-Bus shield schematic?
This is a part of SeeedStudio CAN-Bus shield schematic. The vertical green line on the left seems suspicious to me. Am I missing something?

# Answer
No, it's not a mistake. It's related to this statement on their Wiki:

> When you use more than two CAN Bus Shield in one net, you should take the impedance into consideration. You should either cut P1 in the PCB with a knife, or just remove R3 on the PCB.

If you look closely at the pads of P1 you will see a small trace joining them together. That is the "rogue" green line you found. By cutting that trace you disconnect the termination resistor. You can then re-connect the termination resistor by soldering the pads together again.
> 2 votes

---
Tags: can-bus
---


# Question
Title: What Are The Differences Between Arduino Language and Standard C for MCU?
What the differences between Arduino language and standard C used for MCU programming (like AVR).I heard Arduino language is C.What happen if i use Arduino language with bare-bones AVR chips.Or with PIC mcu.Will it work? And, if i use just use AVR chip without arduino, will it work with sensor that designed for Arduino (lets say HC-SR04 ultrasonic sensor).And will sensor designed for arduino work with PIC mcu or other non AVR mcu? I'm a beginner mcu programmer and currenly learning Arduino.Which is good starting point learning Arduino first or just go straight to MCU programming (without Arduino, just bare bones chip)? Thank you

# Answer
> 7 votes
There's no "Arduino language", it is C++ with some pre-written libraries to provide an abstraction layer on top of the hardware. You cannot use that library on other microcontrollers because it was designed for the specific MCU (AVR).

Pretty much all microcontrollers on the market have compiler support for the C language, which is similar to C++. There is also often C++ compilers available. But overall, C is by far the most popular language to use when programming embedded systems, with the best tool support.

I would probably avoid spending too much time learning about the Arduino library, since that is not useful knowledge for other platforms. Focus on learning C and study at least one assembler (to grasp what happens underneath the hood of C).

---
Tags: avr, programming
---


# Question
Title: How to detect if the arduino wire is still connected
I have hall sensors connected to an arduino, because of mechanical movements there is some possibility that the input wire may accidentally slip out of the arduino analogin sockets. Is there any way I can detect if the wire is still connected to hall sensor ? I don't want to solder the cables yet.

# Answer
> 2 votes
You can maybe try to see if the value on analog pins when sensors are connected (while not sensing anything) is different when not connected.
Depending on your sensors and schematic, if analog input is fluctuating, you can use this command to use pull resistor to avoid this fluctuation.

```
digitalWrite(Ax, INPUT_PULLUP);

```

If the above gets true, then you can set up a threshold for detection. Below or beside threshold value, sensor is unplugged.

Otherwise, use some vinyl duct tape.... this would securize the thing a bit!

---
Tags: wires
---


# Question
Title: The working of a MFRC522 and its Interface protocols?
I've actually messed up and posted into the stackoverflow site, even though I'm probably not meant to. I've been given this datasheet, but even though it does explain somewhat how each host interfaces works, it does not fully answer the questions I have at the moment and I probably don't even know what I'm doing in the first place, hence I'm giving this question another shot in the right place.

I've enrolled recently into a programming course, and one of the subject seems to be embedded software development revolving around an Arduino. Now, I'm tasked with explaining to the class how the MFRC522 works and where it might be applicable, but before all that, I probably am lacking the basic knowledge before I can proceed with my work.

I have here the image of the pinout from a MFRC522 and I have the following questions:

* Theres UART, I2C and SPI. Are they all separate communication protocols or are they all involved somehow with each other on this device? If I plan to use only UART for example, is it possible that I just only use the RX and TX?
* Are there restrictions as to which pins on the Arduino or the MFRC522 I could possibly use, depending on the protocol or circumstances? I can see in the datasheet the pins D1 to D7 being referenced, but I cannot find it anywhere on the MFRC522 itself.
* In case they are separate protocols, I would like to know how each protocol is applicable for this specific device? Like a general idea as to why a protocol is suited for a certain every day device we have been using.
* The device itself uses only 3.3V, but is it also 5V resistant? Like, will plugging it into a 5V fry the circuit board or will it work just as fine?

Thanks everyone for your time.

# Answer
> 1 votes
Let's have a look at the datasheet of that chip:

Paragraph 8.1 says

> The MFRC522 supports direct interfacing of hosts using SPI, I2C-bus or serial UART interfaces. The MFRC522 resets its interface and checks the current host interface type automatically after performing a power-on or hard reset. The MFRC522 identifies the host interface by sensing the logic levels on the control pins after the reset phase. This is done using a combination of fixed pin connections.

But it seems that on **this specific board** the control pins are preconfigured for SPI. But, the supporting library only supports SPI so I guess that's OK. For other applications the control pins will be connected differently, and the pins will take up an i2c or serial async role. Applications for the other interfaces include microcontrollers without an SPI interface but with an i2c interface, or eg general purpose computers that have easy access to serial async interfaces, like PC's

* the pin names D1-D7 in the datasheet are not related to the Arduino's pins with the same names, that's just a coincidence. If you use the aforementioned library, the Arduino pins to use are documented:

```

     * Pin layout should be as follows:
     * Signal     Pin              Pin               Pin
     *            Arduino Uno      Arduino Mega      MFRC522 board
     * ------------------------------------------------------------
     * Reset      9                5                 RST
     * SPI SS     10               53                SDA
     * SPI MOSI   11               51                MOSI
     * SPI MISO   12               50                MISO
     * SPI SCK    13               52                SCK

```
* what the device will tolerate in terms of voltage on its pins is documented in chapter 11. Absolute max on most pins is 4.5 V, so the chance that 5V will fry the component is so high you probably don't want to try.

---

I think this is your board, and luckily they include a schematic on that page:

Here's it clearly visible that pin 1 is connected to ground, and pin 32 is connected to 3.3V, which shows that it's indeed hardcoded to SPI mode.

---
Tags: i2c, spi, uart, rfid
---


# Question
Title: Having some trouble incrementing counters
So, I have some simple code here. I'll just try and explain what I am trying to have my code do here.

I am trying to rotate my stepper motor by half a turn, and then move it back and forth by 200 steps or so.

The problem I have is in my loop function, where I have a variable called ctr. I am trying to increment this ctr when I execute an if statement. The ctr increments inside the if statement and I can see the result when I do Serial.println as it changes to 1. However, when I Serial.println(ctr) right below the if statement, it prints out as 0 even after the previous print statement prints out 1.

Why is this happening? I am a C/C++ noob, so is there something I am missing about variable scoping or pointers?

```
void loop()
{
    stepper1.run();
    int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      ctr++;
      Serial.println(ctr);
    }
    Serial.println(ctr);
    if(stepper1.currentPosition() == 824 && ctr > 0){
      forthMotion(stepper1.currentPosition());
    }
}

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}

```

# Answer
Make CTR static or place it in the global scope. As it stands you set it to 0 every time you go through loop.

The line:

```
int ctr = 0;

```

literally means "Create a new variable on the stack called 'ctr' and give it the value 0", and that happens *every time `loop()` is executed*.

Instead making it *static* will change it so that it only happens *the first time `loop()` is executed* so it retains its value across successive executions of `loop()`.

```
static int ctr = 0;

```
> 3 votes

# Answer
loop() != main()

when declaring a variable inside a function, it is cleaned up when returning from the function.

if cnt was in a main() function, it would have worked (as it's the only function that may have an infinite loop in a program. In the arduino world, it's not the case. The main() function is hidden, but loop calls the loop() function.

Workaround is to use the static quelifier when you declare variables inside loop() (or in any other function if you want the variable to remain inside the function scope, but don't want it to be initialized each time you enter the function).
> 0 votes

---
Tags: arduino-uno, stepper
---


title: Control a motor with a button

text:
# Question
Title: Control a motor with a button
Code:

```
int motorPin = 9;  // the pin the motor is connected to

void setup()
{
 pinMode(motorPin, OUTPUT);
}

void loop()
{
 motorOnThenOff(); //motorAcceleration
}

void motorOnThenOff(){
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  digitalWrite(motorPin, HIGH); // turns the motor On
  delay(onTime);                // waits for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turns the motor Off
  delay(offTime);               // waits for offTime milliseconds
}

void motorOnThenOffWithSpeed(){

  int onSpeed = 200;  // a number between 0 (stopped) and 255 (full speed)
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 50;  // a number between 0 (stopped) and 255 (full speed)
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
  delay(offTime);                   // waits for offTime milliseconds
}

void motorAcceleration(){
  int delayTime = 50; //milliseconds between each speed step

  //Accelerates the motor
  for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }

  //Decelerates the motor
  for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }
}

```

This code spins the motor. In the circuit, I have a button which I want to toggle the spinning of the motor.

This is the circuit:

https://circuits.io/circuits/4267039-spin-motor-spin/edit

How would I make it so that the button toggles the spinning of the motor? like a fan and its switch?

# Answer
> 1 votes
add this variable at the top of your program:

```
const int buttonPin = XX;   // the pin for the button
bool bState = false;

```

in the setup() function:

```
pinMode(buttonPin, INPUT_PULLUP);
// in case INPUT_PULLUP is not defined, comment the above line and uncomment below
//pinMode(buttonPin, INPUT);
//digitalWrite (buttonPin, HIGH);  // enable internal pull-up

```

in the loop() function, change your code with this:

```
update_bState();

if (bState) { digitalWrite(motorPin, HIGH); }
else        { digitalWrite(motorPin, LOW); }

```

then, at the end of your program, add the getButton function:

```
void update_bState(void)
{
    static bool buttonDone = false;
    static uint16_t timeButton;

    if (!digitalRead(buttonPin))
    {
        if ((!buttonDone) && ((uint16_t) (millis() - timeButton) > 100))
        { // Do once when button is pressed for at least 100ms (debounce)
            bState ^= true;     // Toggle button state
            buttonDone = true;
        }
    }
    else
    {
        buttonDone = false;
        timeButton = millis();
    }
}

```

Now that all the work is done, you should add acceleration when launching and deceleration when launching and stopping :D

By the way, I did not tested any code, so there may be some typo errors...

---
Tags: arduino-uno, motor, button
---


# Question
Title: Using two MIDI inputs with Arduino UNO (with one serial)
Would it be possible to use TWO MIDI inputs (and a MIDI output) on an Arduino having only one RX/TX serial port? Timing will be somewhat critical so a software serial port is not usable probably. I need to listen continuously to both MIDI (in) ports not to miss messages.

Or is it better to use an Arduino Mega having 4 serial ports?

# Answer
> 2 votes
Use a Mega. SoftwareSerial is shaky at best and cripples everything else while it runs, and there really is no substitute for real hardware UARTs.

Alternatively look around and see if you can find a board based around the ATMega328-PB (note the "B") which has a second UART built in.

---
Tags: arduino-uno, serial, midi
---


# Question
Title: Why isn't this pushbutton program working?
Here is my circuit:

and here is my code:

```
int LED = 13;
int BTN = 7;

void setup() {
pinMode(LED,OUTPUT);
pinMode(BTN,INPUT);
}
void loop() {
if(digitalRead(BTN) == HIGH) {
digitalWrite(LED,LOW);
}
else{
digitalWrite(LED,HIGH);
}
}

```

When I press the button, the LED is supposed to go low, but it doesn't. What is wrong with this circuit/code?

# Answer
Your code and schematic both seem to be wrong.

Try out this schematic:

And then code:

```
const int kPinLed = 6; // LED - Pin 6
const int kPinBtn = 7; // Push Button - Pin 7

void setup()
{
  pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
  pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT wiith pullup
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)  // When Push Button is pressed
  {
    digitalWrite(kPinLed, HIGH);   // LED ON
  }
  else digitalWrite(kPinLed, LOW); // LED OFF
}

```
> 2 votes

# Answer
Paul is correct. Your button is wired wrong. The GPIO pin should be connected to the same side as the resistor. Also the button needs rotating through 90 degrees.

Also check how your LED is wired up. At the moment it looks like it's set up so that the GPIO sinks the current (LOW turns the LED on) yet the LED looks like it's connected the wrong way around for that.

In fact, I can't actually find anything *right* about that circuit...
> 1 votes

# Answer
The Input port is going to always be at Gnd, because you have connected it to ground. Sorry to put it in such basic terms but this is the way I understand it. It needs to be more difficult for the output of the button to get to ground than to get to the BTN pin of your UNO. So put a bigger resistor (1K-10K) in place of your yellow wire between the button and ground.

And your LED is the wrong way round in the diagram.

(And Majenko is a quicker typist than me! :) )
> 0 votes

# Answer
In addition to the answers from Matt and Majenko, you code uses the wrong pin for the LED.

You have `int LED = 13;` whereas your LED is connected to pin 6.

NB: Pin 13 is connected to an LED soldered on to the Arduino board - as seen in the image below.
> 0 votes

---
Tags: arduino-uno, button, input
---


# Question
Title: Why the command noDisplay() clear all LCD screen?
i want to preserve video information for long time without communicating with arduino on lcd 1602, i'm tryng to use the command of liquidCrystal library `noDisplay()` but when i use it,this clear all display. On arduino website here is the description of this command "Turns off the LCD display, without losing the text currently shown on it." but i lose all on screen. Thanks for reply

there is my test code

```
#include <LiquidCrystal.h>

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

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

void loop() {
  // Turn off the display:
  lcd.noDisplay();
  delay(500);
  // Turn on the display:
  lcd.display();
  delay(500);
}

```

with this code display blinking and don't show continuos "hello word".

# Answer
I tried out your code. It's working absolutely fine.

Whenever `lcd.noDisplay()` executes then LCD not displaying `hello, word!`... And whenever `lcd.display()` executes then LCD displaying `hello, word!`...

So, that's why "hello word" not continuously displaying.

And you can also find `the display() and noDisplay() functions to turn on and off
the display` comment on top of arduino sketch.
> 4 votes

# Answer
> I tried out your code. It's working absolutely fine.
>
> Whenever lcd.noDisplay() executes then LCD not displaying hello, word!... And whenever lcd.display() executes then LCD displaying hello, word!...
>
> So, that's why "hello word" not continuously displaying.
>
> And you can also find the display() and noDisplay() functions to turn on and off the display comment on top of arduino sketch.

To follow on @Hasan's answer:
noDisplay() doesn't clear the previous displayed stuff, it just inhibits it, all displayed pixels are latched in the chip while it remains powered on.

In case you need to clear the display, you can use lcd.clear() function.
> 0 votes

---
Tags: lcd, library
---


# Question
Title: Servos stop after a while in case of 8 servo motor control
I recently purchased 10 units of MG996R servo motor and the 16 channel 12-bit PWM/Servo driver from Adafruit for a small project. I confirmed that all of my servos are functional and that my code is correct. My issue is that there seems to be a limit on the number of servos I can run. With 4AA batteries, I can power about 3 of the MG996R servos. Starting with the 4th one, they stop moving. I supposed that the current drawn from the servos is high, so I tried powering the servos by providing two 4AA batteries in parallel (8AA). This appeared to have increased the number of servos I can run. But after a few minutes, the servos stop responding and I have to disconnect the power for a while before the servos respond again. I read on Adafruit that I may need to add a capacitor to the PWM/servo drive if I have multiple servos. Is this my problem or I just need to provide more power? Why do the servos seem to respond initially but stop moving after a while? Thanks in advance.

# Answer
> 2 votes
If Adafruit say to use the kit to drive multiple servos you need to add a cap and without the cap you can't drive multiple servos, then yes your first port of call should be to add the cap.

However that's probably not all that's wrong. If it runs for a bit before dying then it could be a number of causes.

1. Not enough power.
2. Something is overheating.
3. Code problem.

1. Use a decent transformer with more than enough amps to power your motors.
    2. Use your nose, does something smell hot? If you use your fingers you will get burnt!
    3. We can't fix invisible code.

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


title: EEPROM write time

text:
# Question
Title: EEPROM write time
I will implements an emergency backup feature before power off, on Arduino Mega 2650. Arduino is powered by capacitor, for the time (I hope) of the EEPROM write.

On AVR2650 Datasheet is reported that the typical EEPROM writing time is 3.3ms. But 3.3ms for what? a byte? a word? the whole EEPROM?

I need the data for calculate the capacitors.

# Answer
> 2 votes
> On AVR2650 Datasheet is reported that the typical EEPROM writing time is 3.3ms. But 3.3ms for what? a byte? a word? the whole EEPROM?

That is per byte (erase and write 3.4 ms, only write is 1.8 ms). When writing multiple bytes there are a few clock cycles to be gained by preparing for the next byte during an ongoing EEPROM write. Or even better use an ISR for the EEPROM feed. Not faster but allows some additional processing while a block is written. The largest gain is to have the EEPROM erased before the write (1.8 ms per byte instead of 3.4 ms).

Please see http://www.nongnu.org/avr-libc/user-manual/group\__avr\__eeprom.html, http://www.atmel.com/images/doc2578.pdf and table 9-1, pp. 35, http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561\_datasheet.pdf.

Cheers!

---
Tags: eeprom
---


# Question
Title: Arduino LED Dimmer Proportionate to Ambient Light
I am trying to get an LED dimming reversely proportionate to natural light level in a room. So as the sun rises, the LED dims and vice-versa. I am using the standard LDR+ 10k Ohm resistor divider, an LED, and an Arduino Leonardo Clone.

The issue is, regardless of the values I adjust in `map()`, it does not change the flickering rate or brightness of the LED. What range of map shuold I be using?

The LED ought to shut off while the LDR takes a reading. I have two variations of the code; one uses PWM, the other simulates PWM using `delay()`

Here are my sketches:

```
/set pin numbers
//const won't change
const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K ohm resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  // KEEP LED OFF TIME BASED ON AMBIENT LIGHT LEVEL...
  int dim2 = map(ldrStatus, 0, 1023, 500, 0); //OFF FOR UP TO 0.50 seconds.
  digitalWrite(ledPin, HIGH);
  delay(dim2);

   }

```

Sketch two:

```
//set pin numbers
//const won't change
const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K OHM resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  int dim = map(ldrStatus, 0, 1023, 255, 0);     // scale it to use it with the LED (value between 0 and 255)
  digitalWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.

   }

```

# Answer
For certain Arduino models, the PWM pins are different. For the iteaduino lite, a usable PWM pin is pin D5.

Here is the code updated to use D5 instead of D1, which lacks PWM abilities:

```
//set pin numbers
//const won't change
const int ledPin = 5;   //D5 PWM the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K OHM resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  int dim = map(ldrStatus, 0, 1023, 0, 255);     // scale it to use it with the LED (value between 0 and 255)
  analogWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.
  Serial.println(dim);
   }

```

There is still flickering, but that is to be expected. `map()` ranges can be adjusted to set when the LED will be fully off or on.

It is still unclear how to allow the light sensor to take a reading while the LED is OFF, then power back on rapidly enough to not have a visible flicker. If anyone has thoughts on that, it would be appreciated! Thanks everyone for helping.
> 1 votes

---
Tags: led, pwm
---


title: Arduino Yun Analog Read Problem

text:
# Question
Title: Arduino Yun Analog Read Problem
I am having some major issues with my Arduino Yun.

When attempting to read a value from the analog pins, the Yun is giving me incorrect constant values.

I have attached everything to a common ground, and I am supplying 3.3 volts to the A0 pin on the Yun.

The weird thing is, the pins all give constant values in ascending order, no matter what is connected to them, or if nothing is connected at all.

* A0 - 18
* A1 - 19
* A2 - 20
* A3 - 21
* A4 - 22
* A5 - 23

The code I am running is a very simple script.

```
float i;

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

void loop() {
  i = A0;
  Serial.println(i);
  delay(1000);
}

```

# Answer
> 2 votes
You are not reading from any analog pins. You are just printing out the digital pin number of the analog pin.

Look at some basic examples on how to read analog values.

```
/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.
*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

```

---
Tags: arduino-yun, input
---


# Question
Title: Update Dynamically Tkinter Widget Scale from Arduino Ports using python and firmata
I'm having trouble trying to get Arduino digital ports values and set these values into a Python Tkinter Widget Scale.

I'm using Python and Arduino with Firmata. I'm able to access my arduino board with python code. For example in a label widget I'm getting and setting Arduino analog port value in real-time to a label as in following code without any problems:

```
import Tkinter
import pyfirmata

def onStartButtonPress():
    while True:
        if flag.get():
            analogReadLabel.config(text=str(a0.read()))
            analogReadLabel.update_idletasks()
            top.update()
        else:
            break
    board.exit()
    top.destroy()

def onExitButtonPress():
    flag.set(False)

port = 'COM7'
board = pyfirmata.Arduino(port)

it = pyfirmata.util.Iterator(board)
it.start()

a0 = board.get_pin('a:0:i')

top = Tkinter.Tk()
top.title("Reading Analog pins")

descriptionLabel = Tkinter.Label(top, text="Potentiometer input:- ")
descriptionLabel.grid(column=1, row=1)

analogReadLabel = Tkinter.Label(top, text="Press Start..")
analogReadLabel.grid(column=2, row=1)

flag = Tkinter.BooleanVar(top)
flag.set(True)

startButton = Tkinter.Button(top, text="Start", command=onStartButtonPress)
startButton.grid(column=1, row=2)

exitButton = Tkinter.Button(top, text="Exit", command=onExitButtonPress)
exitButton.grid(column=2, row=2)

top.mainloop()

```

Up to this point it's okay and the GUI shows me something like:

But what I'm trying to do and not getting is:

Here is the code:

```
import Tkinter
import pyfirmata
import serial;

def onStartButtonPress():
    while True:
        if flag.get():
            analogReadLabel.config(text=str(d8.read()))
            analogReadLabel1.config(text=str(d9.read()))
            analogReadLabel2.config(text=str(d10.read()))
            analogReadLabel.update_idletasks()

        pos1 = d8.read()
        if pos1 == True:
            pos1 = int(pos1)
            pos1 = 0
            brightnessScale.set(pos1)

        pos2 = d9.read()
        if pos2 == True:
            pos2 = int(pos2)
            pos2 = 100
            brightnessScale.set(pos2)

       ''' and so on '''

        brightnessScale.update_idletasks()
        top.update()
    else:
        break
board.exit()
top.destroy()

def onExitButtonPress():
    flag.set(False)

port = 'COM7'
board = pyfirmata.Arduino(port)

it = pyfirmata.util.Iterator(board)
it.start()

a0 = board.get_pin('a:0:i')

d4 = board.get_pin('d:4:i')
d5 = board.get_pin('d:5:i')
d6 = board.get_pin('d:6:i')
d7 = board.get_pin('d:7:i')
d8 = board.get_pin('d:8:i')
d9 = board.get_pin('d:9:i')
d10 = board.get_pin('d:10:i')

top = Tkinter.Tk()
top.geometry("800x600")
top.title("Reading Analog pins")

descriptionLabel = Tkinter.Label(top, text="Potentiometer input:- ")
descriptionLabel.grid(column=1, row=1)

analogReadLabel = Tkinter.Label(top, text="Level 1")
analogReadLabel.grid(column=2, row=1)

analogReadLabel1 = Tkinter.Label(top, text="Level 2")
analogReadLabel1.grid(column=3, row=1)

analogReadLabel2 = Tkinter.Label(top, text="Level 3")
analogReadLabel2.grid(column=4, row=1)

brightnessScale = Tkinter.Scale(top, from_ = 500,
                            to = 0,
                            length = 500,
                            width = "30",
                            tickinterval = 50,

                            bg = "lightskyblue",
                            highlightcolor = "darkblue",
                            highlightbackground = "royalblue",
                            troughcolor = "darkblue",

                            state = Tkinter.DISABLED,
                            sliderlength = 50,
                            relief = "sunken",
                            label = "Volume do Reservatorio em %",
                            orient = Tkinter.VERTICAL)
brightnessScale.grid(column=1, row=5)
Tkinter.Label(top,text="Volume da Caixa em (%)").grid(column=1, row=6)

flag = Tkinter.BooleanVar(top)
flag.set(True)

startButton = Tkinter.Button(top, text="Start", command=onStartButtonPress)
startButton.grid(column=1, row=2)

exitButton = Tkinter.Button(top, text="Exit", command=onExitButtonPress)
exitButton.grid(column=2, row=2)

top.mainloop()

```

To summarize: I have reed switches in each digital port declared in the code. These reed switches are normally open state, when I put a magnetic field near them it turn to close and I get a change in that value like from False to True. What I'm trying to do is update the Tkinter Scale Widget in real time as the labels but I'm not getting it.

Is there any trick in python code that can solve my problem ? Because I did a lot of research on the internet and I could not get done, as you can see in image 2 when the state of the second digital pin changes, a label changes to True, and in the scale code this corresponds to the value 100, but it's still on the 0 mark.

I'm not comfortable also with the usage of command, and variable parameters of scale widget.

In short, I want to update in real time python Tkinter scale widget according to values from digital ports from arduino using firmata.

I'm using Python 2.7

PS: for completeness:

This is my arduino code (Sketch) without firmata, which is working as expected.

```
int level;
int position;

void setup() {

pinMode(8, INPUT);
pinMode(9, INPUT);
pinMode(10, INPUT);
pinMode(11, INPUT);
pinMode(12, INPUT);

Serial.begin(9600); // ativa a porta serial

void loop() {
digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);

position = digitalRead(8);
if ( position == HIGH) {level=0;}

position = digitalRead(9);
if ( position == HIGH) {Level=100;}

position = digitalRead(10);
if ( position == HIGH) {level=200;}

position = digitalRead(11);
if ( position == HIGH) {level=300;}

position = digitalRead(12);
if ( position == HIGH) {level=400;}

Serial.println(level);
delay(500);

}

```

What I could do also here is get these values via serial in python and use them to update the scale in this way but I don't know if in this method it's gonna work also!

And what I thought in Python: But I still have much to learn in algorithms and Data Structures. Just the Pseudo Code:

```
def setScaleValue():
while True:
    if flag.get():
         pos1 = d4.read()
        if pos1 == True: #or 1
        #Here is the problem i don't know for sure what comes in my digital port
        #If is a True bool or a 1 as HIGH value from arduino
        #And probably i don't know if it's possible to change the values of a scale in this way !!!
        #or if i'm mistaken the Cast stuff in Python
            pos1 = int(pos1)
            pos1 = 0
            brightnessScale.set(pos1)

        pos2 = d8.read()
        if pos2 == True:
            pos2 = int(pos2)
            pos2 = 100
            brightnessScale.set(pos2)

        brightnessScale.update_idletasks()
        top.update()
    else:
        break
board.exit()
top.destroy()

return

d4 = board.get_pin('d:4:i')
d5 = board.get_pin('d:5:i')
d6 = board.get_pin('d:6:i')
d7 = board.get_pin('d:7:i')
d8 = board.get_pin('d:8:i')

brightnessScale = Tkinter.Scale(top, from_ = 500,
                            to = 0,
                            length = 500,
                            width = "30",
                            tickinterval = 50,

                            bg = "lightskyblue",
                            highlightcolor = "darkblue",
                            highlightbackground = "royalblue",
                            troughcolor = "darkblue",

                            state = Tkinter.DISABLED,
                            sliderlength = 50,
                            relief = "sunken",
                            label = "Volume do Reservatorio em %",
                            orient = Tkinter.VERTICAL)
brightnessScale.grid(column=1, row=5)
Tkinter.Label(top,text="Volume da Caixa em (%)").grid(column=1, row=6)

```

# Answer
> 1 votes
in your code:

```
pos2 = d8.read()
print("pos2 is {} type {}".format(pos2, type(pos2)))  # This way, you'll know the var type you're getting on the console
    if posX == True:
        posX = int(posX)          # You then cast to an integer
        posX = 100                # You discard pos2 value by setting it to 100
        brightnessScale.set(posX) # You set the scale always to value 100

```

By adding the print line, you can ensure the variable value and type.
Then, you may have to adapt your if statement accordingly.
Beware what you're doing then with those 2 lines reaffecting posX, this is probably not what you want to do before updating the scale.

---
Tags: arduino-uno, usb, analogread, python, firmata
---


title: Scheduled loops using same function

text:
# Question
Title: Scheduled loops using same function
I am using an Arduino due and have multiple schedules running at the same time. I am using this Library.

I have a function that 3 different loops use. Two of the loops are driven by user interaction so timing is not possible. The function does reset global variables and I would have no issue with the variables being reset multiple times as it wouldn't cause any problems for me.

What I was wondering, on the very slim chance that two loops called the function at the same time, is it possible for the loops to modify the same variable at identical times?

My understanding of the scheduler would lead me to believe that the scheduler will only yield to another loop after it has completed a line of code and thus the to instructions to reset the global variable could not happen at the very same time, just extremely quickly one after the other.

Would this be a correct assumption?

# Answer
From the \[Arduino Reference\]\[1\] pages:

> This is a cooperative scheduler in that the CPU switches from one task to another. *The library includes methods for passing control between tasks.*

\[emphasis mine\]

Which means that your code decides when it yields control to another scheduled loop (by calling `yield()`. At a quick glance, it appears that it also yields by returning. So yes, your assumption is correct.
> 1 votes

# Answer
It is a simple schedular. It only changes to another task when yield() is called. The delay() function uses yield() and a lot of code and libraries use delay().
That means that if you code does not contain a delay() then you need to call delay() or yield() now and then, or other tasks will never execute.
It is probably safe to use the same function, but every time a delay() is used, an other task could run or another task will continue from there.
> 0 votes

---
Tags: arduino-due
---


title: Using Arduino as a pc remote controller

text:
# Question
Title: Using Arduino as a pc remote controller
I would like to create a simple remote controller (IR) with my Arduino Nano that would control my PC. (Volume up/down, stop, play and that sort of things...) I have no problem with creating 'hardware part' and Arduino script, that would send commands through serial as a reaction to IR signals. I can imagine python script that would react to commands received on the serial port.

My problem is: "How can I detect on which port should I listen to?" What is the right way to do it?

# Answer
> 1 votes
Since I can not commemnt due to low reputation, I'm "commenting" here. You can search for LIRC and WinLIRC

---
Tags: serial
---


title: Custom DAC for Arduino UNO

text:
# Question
Title: Custom DAC for Arduino UNO
I am currently following this tutorial on building a Simple Audio Player for the Arduino. I was about to finish the circuit only to realize that the required board is an Arduino Due and I have the Uno.

Because the Uno does not have its own DAC port, I was wondering what other options are available for me to accomplish the same thing while keeping the circuit as similar to the one listed in the tutorial.

Thanks

# Answer
There are three basic ways of creating a DAC.

The simplest, though roughest, is to use PWM, then low-pass filter it. Not perfect, but rough and ready. Only needs a resistor and a capacitor.

The highest quality way, though slowest for interfacing, is to use an external DAC chip. Fine for low frequency response reproduction, and the linearity is second to none. The MCP4821/2 is a popular choice (SPI connected).

The third option is to build your own DAC using an R-2R ladder. You can make an 8-bit DAC with very fast response by using all 8 pins of a single IO port (such as pins 0-7 on the Uno are bits 0-7 of port D). However the linearity of an R-2R ladder very much depends on how well matched your resistors are.

The R-2R ladder should be buffered with an amplifier of some form before driving a low impedance device like a speaker.

None of them are really great for audio work - for that you need a chip with much more processing power and memory, and a high speed digital audio interface, such as I2S, to interface a proper audio CODEC chip. Personally I use PIC32MZ chips for audio work.
> 3 votes

# Answer
The major problem you have is that the Audio library functions are specifically written for the ARM based Due.
You could certainly add an I2C 10 bit (Mono or Stereo) DAC chip to an Arduino Uno capable of producing stereo signals through an LM386, but you would have to re-write the Audio library to support that functionality on the Uno.
> 2 votes

# Answer
You can probably use the same circuit and the PWM "Analog" output of the Duo (after adding a low pass filter) to play simple tones, and maybe do something on the input side to allow you to change the frequency in response to some user input.

I don't think you'll get the Duo to read from the SD Card and play the audio simultaneously.
> 1 votes

---
Tags: arduino-uno
---


title: Arduino Control TV over RS232

text:
# Question
Title: Arduino Control TV over RS232
I have a LG TV(LG 32SL800 ZB), which has a RS232-Port for Control and Service.

And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one RS232 Board?

How could I then control the TV? This is the Manual for the TV at page 124 there are the commands how to control it, but how can I send them?

My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

# Answer
> 1 votes
> And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one?

Yes, you can, though choose a board based around the MAX3232 for a 3.3V MCU board.

> How could I then control the TV? This is the Manuel for the TV at page 124 there are the commands how to control it, but how can I send them?

Exactly as they show in the manual. For example:

```
Serial.print("ka 0 01\r");

```

That would turn on every TV connected to the serial bus.

> My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

You can get away with no more than maybe 1 meter between the Arduino and the RS232 board. Keep that as short as possible. However between the RS232 board and the TV you can have up to 15 meters of cable.

---
Tags: arduino-uno, digital, nodemcu, rs232
---


title: HC-SR04 and LCD Circuit Problem

text:
# Question
Title: HC-SR04 and LCD Circuit Problem
I was designing a circuit that measure distance using HC-SR04 and display it into a LCD.This circuit also have 4 LEDs indicator.But i have a problem.The LEDs doesn't turn on.The LCDs backlight turn on, but it didnt display anything. Btw, i'm using LCD with I2C module.Here is the code:

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
#define trigPin 6
#define echoPin 7
int led5cm = 8;
int led7cm = 9;
int led10cm = 10;
int ledoor = 11; //ledoor means LED Out of Range
void setup() { // put your setup code here, to run once: lcd.begin(16,2); lcd.setCursor(0,0);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led5cm, OUTPUT);
  pinMode(led7cm, OUTPUT);
  pinMode(led10cm, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  if (distance <= 5)
  { lcd.println("Distance < 5 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, HIGH);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  } else if (distance >= 5 || distance <= 7) {
    lcd.println("Distance < 7 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, HIGH);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance >= 7 || distance <= 10) {
    lcd.println("Distance < 10 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, HIGH);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance > 10) {
    lcd.println("Out of Range");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
}

```

Can you please help me solve this problem? Thank you very much!!

# Answer
To make your LCD work, add code like the following in `setup()`. (Substitute appropriate values in place of `LCDcols` and `LCDrows`, or give them appropriate values via `const int ...` or `enum { ... };` statements.)

```
  lcd.begin(LCDcols, LCDrows);
  lcd.setBacklightPin(3,POSITIVE); // Might not need this, since info appears to be included in lcd declaration
  lcd.setBacklight(HIGH);
  lcd.clear();          // Clear the display
  lcd.home();

```

To make the LEDs work better, you may need to change the `||` connectives in some of the `if` statements to `&&`. An `if` condition with terms joined by `||`, OR, is true if *any* of its terms are true; with terms joined by `&&`, AND, *all* of its terms must be true for the condition to be true.

For example, the condition `(distance >= 5 || distance <= 7)` is true if distance is 5 or more, or 7 or less; in other words, is always true.
> 1 votes

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


title: How fast is a SD page read from a file?

text:
# Question
Title: How fast is a SD page read from a file?
For a project I would like to do, I asked a question about whether to use SD or EEPROM (see Question

I checked how much memory I would need without any restrictions which is like 2 MB (or more) so a SD card seems the best solution.

However, I'm a bit worried about the speed. In one of the answer comments is mentioned that 20 ms is an eternity for a microcontroller. However, I might need to do the following within 20 ms:

1. Parse a MIDI event (CPU power only, does not take long)
2. Read one or two SD pages (1/2 times block of 512 bytes)
3. Change/add/remove the MIDI event (CPU power only, negligible)
4. Send out MIDI data (barely no time, mostly hardware)

In worst case I can get like 10-20 MIDI events I need to handle within 20 ms. Especially for step 2 I don't know how much time it will. My plan is to create a big file with a PC program to be stored on the SD card. Than I can let the Arduino read pages of 512 bytes from predefined places (with seek in a file).

I'm intending to keep the file open at all times and use seeks to go to the right place and read 512 bytes every time (assuming it doesn't matter to read 1 or 512 bytes since the page size is 512 bytes anyway).

So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?

(btw, I want to try first on an Uno, but probably I will later go to a Mega (or add more SRAM to store temporary data).

# Answer
> So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?

Let us do the numbers: 50 * 512 = 25 Kbyte in 20 ms is 1.25 Mbyte/s. As the max speed for SPI is 1 Mbyte/s (on Arduino AVR, 16 MHz) we do not have to go any further. The answer is: No.

Cheers!
> 2 votes

# Answer
Just for reference for others:

I received my micro card reader (from Catalex, v1.0, 11/01/2013) today and used a 1GB micrSD card.

The times measured ar at 4 addresses (2000, 120000, 40000 and 12000) again and are a seek to the address, and the reading of the bytes mentioned before the colon and the time after the colon in micros.

Result: Seek is 25..2500 micros depending on the file position, reading below 256 bytes is approx. 2-3 ms, reading 256 bytes 4-6 and 512 bytes 7-8 ms.

```
Initializing SD card...card initialized.
---------
Address: 2000
seek    : 24
read   1: 2276
read   2: 2308
read   4: 2344
read  10: 2380
read 256: 4780
read 512: 7328
-----------
Address: 120000
seek    : 2536
read   1: 5008
read   2: 5040
read   4: 5084
read  10: 5120
read 256: 5312
read 512: 7888
---------
Address: 40000
seek    : 2468
read   1: 4940
read   2: 4972
read   4: 5016
read  10: 5052
read 256: 5252
read 512: 7828
---------
Address: 120000
seek    : 2504
read   1: 4992
read   2: 5024
read   4: 5060
read  10: 5104
read 256: 5296
read 512: 7864

```
> 0 votes

---
Tags: sd, speed
---


# Question
Title: Low Power Library 4 seconds ON, 10 minutes OFF
Could someone please demonstrate how to use a counter with the Arduino 'low power' library to wait for 10 minutes then digitalWrite 4000, HIGH and loop. (I don't mean the simple 'blink' sketch).

I'm trying to save as much power as possible, so any advice is appreciated.

Thanks!

# Answer
> 1 votes
Your problem here is your 10 minutes mark. If you're willing to take a somewhat more complex route, you could use a low-power, programmable, external timer like TPL5110. You can set an interval of up to 120 minutes by selecting the appropriate value of the programming resistor.

This kind of timers can be used to drive the gate of a logic-level P-channel MOSFET that acts as a switch for the power line of the Arduino.

Then, you simply you do all your stuff on the `setup()` function and leave `loop()` empty. You can switch off the Arduino by sending back a DONE signal to the TPL5110 at the end for your `setup()`.

If, for whatever reasons, you really want your Arduino to be running for exactly 3 seconds, then you should run a timer in it (beware: not related in any way with TPL5110). Set it up so you the ISR of the timer breaks a do-while waiting loop just before the line of code that sends back the DONE signal.

# Answer
> 1 votes
Agreed with what most others have already mentioned; The Arduino as-is is not suitable for low power operation - it is best to turn it off completely. The circuit below should do what you want, and is based on a very simple and cheap IC, the 555 timer.

simulate this circuit – Schematic created using CircuitLab

A similar version of this has been working for me for about 2 years in a remote sensing setup. A few things to note to make sure that it works;

1. This needs the TLC555 chip which is a CMOS IC. The TTL version (NE555) will not work with such high value timing resistors.
2. The timing capacitor (shown as 141uF, just use 3 x 47uF in parallel) needs to be a tantalum capacitor. The normal electrolytic version has too high a leakage current.
3. As shown, this should turn off the Arduino for about 580s, and on for 120s. To turn off the Arduino sooner, drive digital pin 5 high. This will discharge C1 through R3 and Q1 quickly (about 500ms).
4. To change the delay times, alter R1, R2, and C1. The datasheet has all the equations that you need for this.
5. it would probably be wise to put a bypass capacitor between the supply rails very close to the TLC555 chip. 10uF should do.
6. This circuit should draw around 360uA while the Arduino is off.

One final thing - the task that you are using the Arduino for sounds pretty simple - driving a digital line high for 4 seconds every 10 minutes. I guess that you have more to it than that, but if not, then you could save yourself the cost and complexity, and do away with the Arduino completely. In that case, R1 should be about 6M1, and R2 about 41K, you can remove Q1, D1, R3 and R6, and whatever you are driving goes in place of the Arduino.

---
Tags: arduino-uno, power, arduino-nano, code-optimization
---


# Question
Title: I would like to know the ATMEGA wiring to Arduino
I would like to know which pins are connected to the output of the Arduino.

For example:

* PC6 is digital 12
* PB5 is analog 13
* etc...

# Answer
Image searching for the term "arduino uno pinout" reveals a better pinout diagram.
> 5 votes

# Answer
I prefer this image, as it combines the arduino pin numbers and PWM capabilities, with the names and functions from the datasheet.
> 3 votes

# Answer
I usually preferred this image. It very useful for me every time.
> 2 votes

# Answer
I think this is the diagram you are seeking.
> 0 votes

# Answer
Or you could simply look at the Arduino Uno schematic, which has everything you should ever need to know.
> 0 votes

# Answer
Updated: Pins PB6 & PB7 while available as I/O pins (D6 & D7) are committed to the external crystal on this board and not brought out to the connectors.
> -1 votes

---
Tags: arduino-uno, pins
---


title: what is the use of Serial.begin(9600)

text:
# Question
Title: what is the use of Serial.begin(9600)
I mean what it does, why it is needed, what if we don't use it, similarly for Serial.println(sensorValue).

# Answer
As the name suggests, `serial.begin(9600)` is a command you give to the Arduino to begin serial communication. I'm assuming you're a beginner. Anyway, as you might've seen on the IDE, there's a serial monitor. It outputs data that you configure it to output. It won't work unless you begin the serial communication using. The `serial.begin(x);` command. X is a variable baudrate, and I highly suggest going with 9600. Okay, also, `serial.println(sensorValue)` is a command that the program gives to the Arduino to print the variable `sensorValue` to the serial monitor. Keep in mind that you can also print this through a Bluetooth module by connecting the tx to the rx and the rx to the tx pins. Hope this helped! :)
> 0 votes

# Answer
`Serial.begin(9600);` configures the UART interface and sets it to the right baud rate. If you don't to that you can't use the UART interface.

`Serial.println(sensorValue);` outputs the sensor value to the UART. If you don't use that you won't see the value of the sensor on the UART.

If you don't want to use the UART then don't use it. If you do want to use the UART then you must use the commands that control the UART.
> 0 votes

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


title: Pin identification for a salvaged LCD

text:
# Question
Title: Pin identification for a salvaged LCD
I salvaged an SPI interface LCD from an old CDMA telephone. It seems it uses SPI to display something on the screen. The pins marks are DATA, CS, SCLK, BL, VDD, GND, LED, A0, and RES. How do I wire it up to an Arduino?

# Answer
> 1 votes
They seem pretty self-explanatory. Data, sclk and cs are normal SPI MOSI, CLK and CS. A0 is probably equivalent to C/D. RES is reset - tie high to run. Power and ground are obvious. The others look related to the back light.

However... How are you going to operate it? Do you know the SPI instructions to send? They will be specific to the display, so without a datasheet you're pretty much stuffed.

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


title: Liquid level sensor

text:
# Question
Title: Liquid level sensor
We're currently working on a direct sketch to printed circuit board printer for our design project. We need a sensor for the ink level since we're using a pen. Can we use this ( https://www.dfrobot.com/wiki/index.php/Non-contact\_Liquid\_Level\_Sensor\_XKC-Y25-T12V\_SKU:\_SEN0204) as a sensor even if its non-conductive type ink (normal ink we use for writing)? Thanks for the response!

# Answer
Your link page says:

> There are no special requirements for the liquid

So, I would not concern about the conductivity of the liquid.
> 1 votes

---
Tags: sensors
---


# Question
Title: Time delay without using delay() and millis()
I am designing an industrial control panel using arduino. I have to use time delays as long as 10 seconds and since using delay() makes a halt in the controller I tried using millis(). But it is complicated and it will work only for 50 days. I want the system to work continuously without any maintenance and I need to control as many as 6 relays. So, I need a better solution (hardware or software based) to tackle this problem. How can I do this?

# Answer
> 4 votes
You misunderstand the 50 day thing. Yes it rolls over after 50 days but that doesn't mean it stops working. As long as you program your comparisons correctly (something people often don't do in online examples) then all it means is the *maximum delay* you can have is 50 days.

# Answer
> 2 votes
You may have to find a library that eases the use of what you're trying to do.
I made some timer library, called **SeqTimer**.
You can find it here: Link
or use the Arduino library manager, it's there too.

It's a simple library using millis(), without callback, so it's pretty straightforward.
If you need more advanced timer, search for 'timer' for example in the arduino library manager, there's a bunch of libs related to timers.

Yet, I'm not really sure what you mean by:

> work only for 50 days

# Answer
> 0 votes
> it will work only for 50 days.

it overflows in 50 days but comparisons based on it can be good even if it overflows. you just need to recognize the overflow and program accordingly.

so millis() is perfectly fine for what you are trying to do. no need to reinvent the wheels.

---
Tags: arduino-uno
---


title: SD card in Arduino

text:
# Question
Title: SD card in Arduino
Im connecting an SD card module to arduino pro with 3.3v , the card is getting initialized , but im getting an error message that FAT 32 partition is not available , but it is already in FAT 32 format , is this an voltage issue ? should i connect it to a 5v line? Ive tried it two libraries SD and sdfat libraries , im getting same results, im using 8gb memory card

# Answer
A SD card is 3.3V.
Have you read this: Arduino.cc forum about SD Formatter ?
Perhaps it is a cheap module with bad contacts.
Perhaps your 8GB card is not compatible. Do you have another memory card ? Preferably older and less memory.
Perhaps you use long wires, or a breadboard with bad contacts.

In most cases it should work without problem. When the initialization is okay then the wiring is probably okay. Therefor I suspect that the card itself or the partition on it, is not compatible.
> 0 votes

---
Tags: sd-card
---


# Question
Title: Global memory reduction when using SPI/SD
I want to use an SD card and when including the library both SPI.h and SD.h are included. Also later I want to use an external SRAM chip (probably using SPI.h as well). However, without the SRAM chip my sketch uses around 849 bytes of global memory, where I expect most of it taken by the SD.h / SPI.h combination. Without these includes only 9 bytes are used.

How can I reduce the amount of global memory (still I want to use the SD and SPI interface)?

Edit:

According to a remark below 512 bytes are used for the SD so that explains mostly of the 849 bytes. And some additional questions:

Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes ...I only need to read a file (128 KB) and copy it to an SRAM (external). And I don't mind if it will be transferred in 16 byte blocks. Actually, I could get rid of the buffer at all after the SD to SRAM copy.

My ultimate goal is to leave 1KB + some dynamic memory (for function call stacks/local variables). However, finally I need to move to the Arduina Mega anyway, but was hoping I could already start the project with my Arduino Uno.

# Answer
> Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes

The Arduino SD library uses an internal file block caching (512 bytes) to improve performance. It is possible to read directly from a file block on the SD but that would be very slow. Every 16 bytes read would require reading from file block, discharging all preceding bytes (as the file block is read serially), reading the 16 bytes, and then stopping the block read.

There are a few tiny SD libraries that actually use this technique. See for instance Petit FAT File System http://elm-chan.org/fsw/ff/00index\_p.html

Another technique is to block copy from the SD directly to the external SRAM without going through additional buffers. This requires a refactoring of the SD library so that it uses a callback instead of the internal buffer.

Cheers!
> 1 votes

---
Tags: arduino-uno, spi, memory, sram, sd
---


# Question
Title: How do I write and read internal EEPROM?
I am working on an Arduino Mega 2560. I want to read and write the internal EEPROM.

Can I use `EEPROM.get()/EEPROM.put()`?

I want to store 3 things in EEPROM:

1. Boolean status.
2. String password: length 5 digits.
3. String Mobile number: length 10 digits.

# Answer
> How do I write and read internal EEPROM? Can I use EEPROM.get()/EEPROM.put()?

Yes, the Arduino Reference for EEPROM contains an example of what you are asking for. Below is a simple rewrite of the example for EEPROMGet for your info.

```
struct MyObject{
  bool status;
  char password[6];
  char mobileNumber[11];
};

void setup()
{

  int eeAddress = 0; //EEPROM address to start reading from

  Serial.begin( 9600 );
  while (!Serial) ;

  MyObject customVar; //Variable to store custom object read from EEPROM.
  EEPROM.get(eeAddress, customVar);

  Serial.println(F("Read custom object from EEPROM: "));
  Serial.println(customVar.status);
  Serial.println(customVar.password);
  Serial.println(customVar.mobileNumber);
}

```

For more details and examples see https://www.arduino.cc/en/Reference/EEPROM.

Cheers!
> 1 votes

# Answer
Avoid the 'String' object, use a character array of fixed length. You might want to add one extra byte for the zero-terminator. Put everything in a 'struct' and then you can use the EEPROM.get() and EEPROM.put() to read and write the complete struct. I prefer a struct to keep the data from EEPROM together. That makes it easier to add a checksum and a version number for the data. When something is wrong with the data from EEPROM then default values could be used.

Instead of a struct, you can also read and write the seperate items. The EEPROM.get() and EEPROM.put() should be able to use a character array of fixed length.
> 3 votes

---
Tags: arduino-mega, eeprom
---


# Question
Title: Laser emitter + receiver for Arduino (Arduino to Arduino communication)
I'm working on a project using 2 Arduinos connected to 2 computers to demo Serial to Serial communication.

We're using Arduino Uno connected to the computer via Serial and software serial for inter-Arduino communication. We used wires to connect software serial RX & TX lines, but we'd like to connect these pins to a laser transmitter and receiver.

We're trying to show wireless communication using an optical medium, which is why we wanted to use a Laser transmitter and receiver.

We're trying something like the setup in this YouTube video $3 laser transmits audio over 100m (Arduino)

Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Receiver: Laser Sensor Module non-modulator Tube Laser Receiver

Transmitter: 5V ... Board For Arduino AVR ... KY-008 Laser Transmitter

# Answer
> Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Looks like the receiver module has a low-pass filter. That could reduce the baud-rate depending on the RC-factor (10 Kohm * 10 nF gives a cut-off frequency of 1.6 kHz). I would recommend checking the actual components. The above is a guesstimate.

Cheers!
> 0 votes

---
Tags: arduino-uno, serial, softwareserial
---


# Question
Title: A library for manipulate Intel Hex data?
For a project i need to extract some data from an external eeprom and then store it somewhere. Suddenly after some manipulations (not necessarly with Arduino board) i need to put them in an external eeprom.

What I would do is to convert the extracted data from the EEPROM in Intel Hex data and vice versa. To do this I wanted to know if there is already a library for that purpose "ready to use" made for Arduino boards.

thanks

# Answer
> 0 votes
Why does it have to be in Intel Hex format? You could write out the EEPROM to the serial port one byte to a line, or something. Something like this:

```
#include <EEPROM.h>

void setup ()
{
  Serial.begin (115200);
  Serial.println ();

  for (int addr = 0x0000; addr < 0x0010; addr++)
    {
    Serial.print ("Address = ");
    Serial.print (addr, HEX);
    Serial.print (", value = ");
    Serial.println (EEPROM.read(addr), HEX);
    }

}  // end of setup

void loop ()
{
}  // end of loop

```

I'm not personally aware of a library that happens to write out/read in, Intel Hex format from/to the EEPROM.

---

I have code that uploads and downloads files to the Arduino. Inside that is code to read/write Intel hex format. However it isn't a library.

Inside File\_Utils.ino are some comments that show the format:

```
/*
Line format:

  :nnaaaatt(data)ss

  Where:
  :      = a colon

  (All of below in hex format)

  nn     = length of data part
  aaaa   = address (eg. where to write data)
  tt     = transaction type
           00 = data
           01 = end of file
           02 = extended segment address (changes high-order byte of the address)
           03 = start segment address *
           04 = linear address *
           05 = start linear address *
  (data) = variable length data
  ss     = sumcheck

            * We don't use these

*/

```

---

In that file is code to write Intel Hex format (reading from Flash, not EEPROM):

```
void readFlashContents ()
  {
  if (!haveSDcard)
    {
    Serial.println (F("*** No SD card detected."));
    return;
    }

  progressBarCount = 0;
  pagesize = currentSignature.pageSize;
  pagemask = ~(pagesize - 1);
  oldPage = NO_PAGE;
  byte lastMSBwritten = 0;

  while (true)
    {

    Serial.println ();
    Serial.println (F("Choose file to save as: "));

    getline (name, sizeof name);
    int len = strlen (name);

    if (len < 5 || strcmp (&name [len - 4], ".HEX") != 0)
      {
      Serial.println (F("File name must end in .HEX"));
      return;
      }

    // if file doesn't exist, proceed
    if (!sd.vwd()->exists (name))
      break;

    Serial.print (F("File "));
    Serial.print (name);
    Serial.println (F(" exists. Overwrite? Type 'YES' to confirm ..."));

    if (getYesNo ())
      break;

    }  // end of checking if file exists

  // ensure back in programming mode
  if (!startProgramming ())
    return;

  SdFile myFile;

  // open the file for writing
  if (!myFile.open(name, O_WRITE | O_CREAT | O_TRUNC))
    {
    Serial.print (F("Could not open file "));
    Serial.print (name);
    Serial.println (F(" for writing."));
    return;
    }

  byte memBuf [16];
  bool allFF;
  unsigned int i;
  char linebuf [50];
  byte sumCheck;

  Serial.println (F("Copying flash memory to SD card (disk) ..."));

  for (unsigned long address = 0; address < currentSignature.flashSize; address += sizeof memBuf)
    {

    unsigned long thisPage = address & pagemask;
    // page changed? show progress
    if (thisPage != oldPage && oldPage != NO_PAGE)
      showProgress ();
    // now this is the current page
    oldPage = thisPage;

    // don't write lines that are all 0xFF
    allFF = true;

    for (i = 0; i < sizeof memBuf; i++)
      {
      memBuf [i] = readFlash (address + i);
      if (memBuf [i] != 0xFF)
        allFF = false;
      }  // end of reading 16 bytes
    if (allFF)
      continue;

    byte MSB = address >> 16;
    if (MSB != lastMSBwritten)
      {
      sumCheck = 2 + 2 + (MSB << 4);
      sumCheck = ~sumCheck + 1;
      // hexExtendedSegmentAddressRecord (02)
      sprintf (linebuf, ":02000002%02X00%02X\r\n", MSB << 4, sumCheck);
      myFile.print (linebuf);
      lastMSBwritten = MSB;
      }  // end if different MSB

    sumCheck = 16 + lowByte (address) + highByte (address);
    sprintf (linebuf, ":10%04X00", (unsigned int) address & 0xFFFF);
    for (i = 0; i < sizeof memBuf; i++)
      {
      sprintf (&linebuf [(i * 2) + 9] , "%02X",  memBuf [i]);
      sumCheck += memBuf [i];
      }  // end of reading 16 bytes

    // 2's complement
    sumCheck = ~sumCheck + 1;
    // append sumcheck
    sprintf (&linebuf [(sizeof memBuf * 2) + 9] , "%02X\r\n",  sumCheck);

    myFile.clearWriteError ();
    myFile.print (linebuf);
    if (myFile.getWriteError ())
       {
       Serial.println ();  // finish off progress bar
       Serial.println (F("Error writing file."));
       myFile.close ();
       return;
       }   // end of an error

    }  // end of reading flash

  Serial.println ();  // finish off progress bar
  myFile.print (":00000001FF\r\n");    // end of file record
  myFile.close ();
  // ensure written to disk
  sd.vwd()->sync ();
  Serial.print (F("File "));
  Serial.print (name);
  Serial.println (F(" saved."));
  }  // end of readFlashContents

```

---

That should give you some tips about how to write out the file. Look in my code to see the reading code as well. However as I said, you don't necessarily have to use that format if you just want to manipulate the data yourself.

# Answer
> 0 votes
Nick's answer assumes you just want to read/process/write the data from one place to another. If that's the case, there's no need to store the data into an Intel Hex Data formatted file – just keep it in a flat array, or a file that's formatted conveniently rather than in a form that requires parsing.

Of course, if you actually need the formatted file for some reason – such as an intermediate program only working with Hex files – you could edit the question and say so.

Note, Python Software Foundation's IntelHex page provides a

> Python library to read, write, create from scratch and manipulate data from HEX (also known as Intel HEX) file format.

To use it, you would write a Python program that (on your host computer) reads serial-port data with values to be stored, and uses the IntelHex library to write a Hex file. After the intermediate program fiddles with the Hex file, another Python program on your host computer uses IntelHex to read the modified Hex file and writes it to EEPROM or to serial for an Arduino to write it to an EEPROM.

# Answer
> 0 votes
avrdude himself is very good at providing/inferring the various formats. We are ourselves manipulating output - EEPROMs, for example - in an external editor.

Of course, avrdude is neither *external* nor a *library*, but...

---
Tags: arduino-uno, arduino-ide, eeprom, data-type, convert
---