title: Problem with load cell and ADS1262

text:
# Question
Title: Problem with load cell and ADS1262
I'm using PROTOCENTRAL ADS1262 32-BIT PRECISION ADC BREAKOUT BOARD to read the voltage in simple a load cell.

The connections follows the instructions on its library

But I cannot make it work, the readings has lots of spikes and i cannot discover what is happening.

Can someone help?

# Answer
This problem was solved on Texas Instruments Forum. Thanks.

http://e2e.ti.com/support/data\_converters/precision\_data\_converters/f/73/p/627185/2344271#2344271

---

From the TI forum:

> I noticed that you are polling data ready and then performing the data processing/serial output. The serial output operation is likely taking a long time and preventing you from capturing data at the faster data rates. You can try disabling the serial output and using an oscilloscope to see if you're able to reading data at the full throughput; however, when outputting this data over a serial interface you might not be able to capture and display all of the data...
>
> I would try capturing data to memory and outputting the serial data in batches (for example, output 10 samples of data at a time). This might give you a little more data throughput.
> -1 votes

---
Tags: arduino-uno
---


title: Arduino Mega 2560 serial port location

text:
# Question
Title: Arduino Mega 2560 serial port location
I am having trouble finding the serial input (or port whatever) on my mega can someone plz show me a pic of this pin thanks

# Answer
For information on an Arduino board your first stop should always be the product page, which contains some helpful documentation. For the Mega 2560 the page is https://store.arduino.cc/usa/arduino-mega-2560-rev3. If you had checked there you would see this:

> Serial: 0 (RX) and 1 (TX); Serial 1: 19 (RX) and 18 (TX); Serial 2: 17 (RX) and 16 (TX); Serial 3: 15 (RX) and 14 (TX). Used to receive (RX) and transmit (TX) TTL serial data. Pins 0 and 1 are also connected to the corresponding pins of the ATmega16U2 USB-to-TTL Serial chip.

You will find those pins on the rightmost header on the top edge of the board in this picture:
> 2 votes

---
Tags: arduino-mega
---


# Question
Title: Store RAM and PROGMEM strings in one variable
I want to store a number of strings in an object. Currently I have:

```
class MyClass {
  int numStrings = 0;
  ??? strings[20];

  public:
    void addString(const char str[]);
    void print();
};

void MyClass::addString(const char str[]) {
  strings[numStrings] = str;
  numStrings++;
}

void MyClass::print() {
  for (int i = 0 ; i < numStrings ; i++) {
    Serial.println(strings[i]);
  }
}

```

`Serial.println()` works with strings in RAM and in PROGMEM alike.

Is there a type that I can give to my `strings` variable that allows me to store both types of strings?

```
MyClass s;

s.addString("This should work");
s.addString(F("This should work, too"));

```

# Answer
> 1 votes
> Is there a type that I can give to my strings variable that allows me to store both types of strings?

No, but you could tag the pointer or add a vector with type information or ultimately use a class hierarchy (BaseString\<-SRAMString, PROMEMString).

As a pointer is 16-bit (Arduino Uno) and there is limited amount of SRAM it is possible to add a magic number to pointers to determine the address space.

Obviously the print() member function will have to use the right type and you will also need a new addString for F() strings. Check how F() is defined.

Cheers!

---
Tags: c++, progmem
---


# Question
Title: Problem : Trigger limit switch to stop DC motor
I want to make a project about automatic gate and garage door via Android app and connected by HC-05 bluetooth module. Each of the gate and garage door have two limit switches(located at each end of travel) to trigger the DC motor to stop.

I have made some code and do researches, but the DC motor will only stop when I pressed it, if I release it again it will start automatically. I want to make it stop until the bluetooth module send the code again. I have input the pull-down resistor into the limit switch.

Can anybody please help me?

Here's my current code, thank you

```
// Motor for Gate (MotorA)
int IN1 = 2;
int IN2 = 3;
int EnableMotorA = 9;

// Motor for Garage Door (MotorB)
int IN3 = 4;
int IN4 = 5;
int EnableMotorB = 10;

const int LimitSwitch1 = A1;
const int LimitSwitch2 = A2;
const int LimitSwitch3 = A3;
const int LimitSwitch4 = A4;

int state;

void setup(){
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(EnableMotorA,OUTPUT);

  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);
  pinMode(EnableMotorB,OUTPUT);

  pinMode(LimitSwitch1, INPUT);
  pinMode(LimitSwitch2, INPUT);
  pinMode(LimitSwitch3, INPUT);
  pinMode(LimitSwitch4, INPUT);

  digitalWrite(LimitSwitch1, LOW);
  digitalWrite(LimitSwitch2, LOW);
  digitalWrite(LimitSwitch3, LOW);
  digitalWrite(LimitSwitch4, LOW);

  Serial.begin(9600);
}

void loop(){
  if(Serial.available() > 0){
    state = Serial.read();
    }
    if(state == 'A') {
      OpenGate();
      if(digitalRead(LimitSwitch2) == HIGH){
      StopMotorA();
      }
    }
    else if(state == 'B') {
      CloseGate();
      if(digitalRead(LimitSwitch1) == HIGH){
      StopMotorA();
      }
    }
    else if(state == 'C') {
      OpenGarageDoor();
      if(digitalRead(LimitSwitch4) == HIGH){
      StopMotorB();
      }
    }
    else if(state == 'D') {
      CloseGarageDoor();
      if(digitalRead(LimitSwitch3) == HIGH){
      StopMotorB();
      }
    }
}

//******************   Motor A control   *******************
void OpenGate(){
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  analogWrite(EnableMotorA, 250);
  }
void CloseGate(){
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  analogWrite(EnableMotorA, 250);
}
void StopMotorA(){
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  analogWrite(EnableMotorA, 0);
 }
//******************   Motor B control   *******************
void OpenGarageDoor(){
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  analogWrite(EnableMotorB, 250);
}
void CloseGarageDoor(){
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  analogWrite(EnableMotorB, 250);
}
void StopMotorB(){
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(EnableMotorB, 0);
}
//**********************************************************

```

# Answer
DISCLAIMER: I haven't tested the code in this answer, but I hope there are no problems.

Your code has a major problem: what happens when one gate is moving and you trigger another movement? (reply: something bad). This design issue can be solved by using a standard way of designing these kind of state machine.

In your case a small state machine is what best fits your problem. Better give your states a meaningful name, no?

Ok, so just to start, let's define the states and how to transition through them.

You have basically an idle state, open gate, close gate, open garage door, close garage door. What should you do in these states, both when entering the state and during the time you are in the state? Here is a table to summarize

```
State       | Enter         | During time
----------------------------------------------
Idle        | Stop motors   | -
OpenGate    | Start A dir 1 | -
CloseGate   | Start A dir 2 | -
OpenGarage  | Start B dir 1 | -
CloseGarage | Start B dir 2 | -

```

The transitions are pretty straightforward. Exit from idle when you receive a (valid) command, exit from the others when you reach the endstop.

The implementation is pretty standard:

```
// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte State_Idle = 0;
const byte State_OpenGate = 1;
const byte State_CloseGate = 2;
const byte State_OpenGarage = 3;
const byte State_CloseGarage = 4;
byte currentState;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentState = 0xFF; // Force a change to enter the idle state
}

void loop(){
    // Check if we need to change state
    byte nextState = currentState;
    switch (currentState)
    {
    case State_Idle:
        { // If we received a valid command, start the operation
            if(Serial.available() > 0)
            {
                switch (Serial.read())
                {
                case 'A':
                    nextState = State_OpenGate;
                    break;
                case 'B':
                    nextState = State_CloseGate;
                    break;
                case 'C':
                    nextState = State_OpenGarage;
                    break;
                case 'D':
                    nextState = State_CloseGarage;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case State_OpenGate:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGate:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_OpenGarage:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGarage:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    default:
        nextState = State_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentState)
    {
        currentState = nextState; // Move in the new state
        switch (currentState)
        { // Entering the new state
        case State_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case State_OpenGate:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case State_CloseGate:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        case State_OpenGarage:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case State_CloseGarage:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

```

(Note: I changed some types because your poor 8-bit uC asked me to avoid complicating its calculations unnecessarily)

One modification to your algorithm is to detach the two loops, since they seem, well, detached.

```
// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte StateA_Idle = 0;
const byte StateA_Open = 1;
const byte StateA_Close = 2;
byte currentStateA;

const byte StateB_Idle = 0;
const byte StateB_Open = 1;
const byte StateB_Close = 2;
byte currentStateB;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentStateA = 0xFF; // Force a change to enter the idle state
    currentStateB = 0xFF; // Force a change to enter the idle state
}

void loop()
{
    byte readChar = 0;
    if(Serial.available() > 0)
        readChar = Serial.read();

    stateMachineA(readChar);
    stateMachineB(readChar);
}

void stateMachineA(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateA;
    switch (currentStateA)
    {
    case StateA_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'A':
                    nextState = StateA_Open;
                    break;
                case 'B':
                    nextState = StateA_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateA_Open:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    case StateA_Close:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    default:
        nextState = StateA_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateA)
    {
        currentStateA = nextState; // Move in the new state
        switch (currentStateA)
        { // Entering the new state
        case StateA_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            break;
        case StateA_Open:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case StateA_Close:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        }
    }
}

void stateMachineB(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateB;
    switch (currentStateB)
    {
    case StateB_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'C':
                    nextState = StateB_Open;
                    break;
                case 'D':
                    nextState = StateB_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateB_Open:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    case StateB_Close:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    default:
        nextState = StateB_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateB)
    {
        currentStateB = nextState; // Move in the new state
        switch (currentStateB)
        { // Entering the new state
        case StateB_Idle:
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case StateB_Open:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case StateB_Close:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

```

This second implementation has two parallel state machines (sharing only the serial input). This will allow you to control both gates at the same time (for instance when the gate is closin you can open the garage)
> 2 votes

---
Tags: arduino-uno, bluetooth, motor, switch
---


title: Serial Monitor and UART

text:
# Question
Title: Serial Monitor and UART
After uploading the code, can I connect a UART peripheral's RX, TX to TX, RX (D0 ,D1) and use the serial monitor of the arduino together ? Will data reception from the peripheral properly work in this case, or will it conflict with the serial monitor ?

# Answer
> 2 votes
You can *use* the serial monitor in this way, as long as you ensure you do not send anything from the serial monitor out to the Arduino or peripheral, only to monitor data.

That said, if you try to send debug prints from the Arduino to the serial monitor, they will also be sent to the peripheral device, where there may be conflict, depending on the peripheral.

So you technically can, but it's not advised because there are several ways it can go wrong.

One alternative is to use the SoftwareSerial library to create a second, bit-banged serial port. Note, however, that this library can't operate at high speed (probably best to keep at 9600 bps) reliably.

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


title: Overheating Shift-Register(74HC595)

text:
# Question
Title: Overheating Shift-Register(74HC595)
I am working on a project where I need to use around 50 LED's connected to an Arduino UNO board. To begin with i worked on the tutorial provided by Arduino (https://www.arduino.cc/en/Tutorial/ShiftOut) to connect two shift registers(74HC595). Everything works fine, but the shift registers get very hot in just a few minutes. Is this normal?

# Answer
> 4 votes
I can only think about two things:

1. (least probably): the entrance (VCC) voltage is too high.
2. (most probably): the resistors to the LEDs are (too) low .. Recalculate the values and check the max amperes which can be handled by the output pins of the shift registers.

---
Tags: arduino-uno, led, shift-register
---


# Question
Title: Sending Multiple Information from BNO055 IMU to BridgeClient on Yun
I have an **Arduino Yun** which is interfaces via **I2C** to a Adafruit BNO055 breakout board.

My Aim is to use **Python Flask** in conjunction with **BridgeServer** and **BridgeClient** to obtain the Sensor Information from the **ATmega32u4** microcontroller to the Microprocessor and use **HTML5 Server Side Event (SSE)** to display live sensor information on Network interfaces.

I would like to show the Euler angles and Linear Acceleration values:

1. heading
2. pitch
3. roll
4. linear\_accerlation\_x
5. linear\_acceleration\_y
6. linear\_acceleration\_z

An Example of similar concept can be obtained from Smart Measuring Cup by Adafruit. However, in the code sketch the user sends only one value :

```
BridgeClient client;
....
client.println(volume, 5);

```

And at the **Python Flask** end the code opens up a socket and uses `makefile()` method to read value

```
def yunserver_sse():
    try:
        # Connect to YunServer instance that's listening on localhost.
        soc = socket.create_connection(('localhost', 5678))
        socfile = soc.makefile()
        while True:
            # Get data from server.
            line = socfile.readline()
            # Stop if the server closed the connection.
            if not line:
                raise StopIteration
            # Send the data to the web page in the server sent event format.
            yield 'data: {0}\n\n'.format(line)
            # Sleep so the CPU isn't consumed by this thread.
            time.sleep(0)
    except socket.error:
        # Error connecting to socket. Raise StopIteration to quit.
raise StopIteration

```

Instead of sending just *one* measured parameter how can I send all above mentioned 6 at the same time?

**note**

I tried using **ArduinoJson** library but I find it difficult to parse the JSON on the Python Flask end as `readline()` expects a `\n` at the end of the string.

# Answer
Apparently the solution to my problem was a simple `client.println()` after my JSON was ready to be printed to the **BridgeClient**.

**Snippet**:

```
root.printTo(client); client.println();

```

where `root` is `DynamicJsonBuffer` from the **ArduinoJson** library. The `client.println()` would immediately print `\n` and this would be read by the `readline()` python code.
> 0 votes

---
Tags: arduino-yun
---


# Question
Title: Adding slave device to Arduino Uno-SPI | Configuring pins
I recently started an oled project. I use a small "128X64 OLED LCD LED Display Module" and I control it using SPI protocol(with my Arduino).

It is the only device connected to the microcontroller. But I have some questions regarding the pins. I found this tutorial and it uses pins 9 as DATA(known as MOSI) and 10 as CLK( or SCK). But the datasheet for my microcontroller(328) shows that pin 11 is MOSI and 13 is CLK.

Obviously..it works. So I think the program provided by the adafruit(that I used-Adafruit\_SSD1306) took care of MOSI and generated the clock impulses on pin 10.etc. . But then what are those pins on the board and why are called like that? I mean it seems to me that everyone can just use other pins for MOSI/CLK(at least).What is their purpose?

Question #2: What does DC (or D/C) means?

```
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

```

**VS**  (328\<=\>128)

# Answer
You can answer these questions by opening the library and looking "under the hood". This is the most beautiful advantage of open source projects.

Here are the links to the relevant files in the library, so I can comment on them.

Ok, first of all let's have a look at the example. you can see that the constructor is called as

```
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

```

When looking at the lines 144 and following of the source file, you can see

```
hwSPI = false;

```

Wait, this means that it is not using the hardware SPI? Sure! In the following overload, then, you can see that if you call the constructor as `Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS)`, you will use the hwSPI.

Now, I'm not sure whether you know the difference between HW and SW implementations, so here they are. The HW implementation is a peripheral which can run "on its own" and provide the microcontroller the results (automatically send and/or receive the bytes). The SW one, on the other hand, is an emulation done by the microcontroller.

You can also see it in the example:

```
// If using software SPI (the default case):
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

/* Uncomment this block to use hardware SPI
#define OLED_DC     6
#define OLED_CS     7
#define OLED_RESET  8
Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS);
*/

```

So you can use the second part to initialize a display which will use the hardware SPI (so MISO = 12, MOSI = 11, SCK = 13). If you want to free the microcontroller in order to be able to do other tasks, use the HW peripheral.

As fot the DC pin, it is labeled "DataCommand". I think it is a pin to tell the controller whether the data shared through the SPI port is a command or it is data
> 2 votes

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


# Question
Title: Problem using ICSC (by majenkotech) in RS485 bus
I want to communicate with an RS485 Bus consisting of 5 Arduino Pro Minis as slaves and one Arduino Mega 2560 as Master. I found a great library for this.

According to the documentation provided by the author of library I can use:

`ICSC icsc(1, 9600, 7); //ID, BaudRate, DEpin`

But I also have to define a Serial port for ICSC to work with:

`ICSC icsc(1, 9600, Serial1);`

I cannot mix these two sentences. I mean I cannot define both **DEpin** and **Serial port** for the ICSC in one sentence. But I need it to be defined. I don't want to use Serial for that, which I need for Serial Monitor. I want to use Serial1 for this. What can I do? I couldn't find any updated documentation about this.

**UPDATE**:

I found out how to define Serial port and DEpin for ICSC. The problem is I cannot get an answer!

Here is Master code:

```
#include <ICSC.h>
ICSC icsc(Serial1, 1, 7); //Stream, ID, DEpin

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  icsc.begin();
  icsc.registerCommand('R', &showTemperature);
}

void loop() {
  icsc.send(2, 'T', 0, NULL);
  icsc.process();
}

void showTemperature() {
  Serial.println("ACK");
}

```

And here is the Slave code:

```
#include <ICSC.h>
ICSC icsc(Serial, 2, 7); //Stream, ID, DEpin
String strAck = "ProMini2:ACK";

void setup() {
  Serial.begin(9600);
  icsc.begin();
  icsc.registerCommand('T', &sendTemperature);
}

void loop() {
  icsc.process();
}

void sendTemperature() {
  icsc.send(1, 'R', sizeof(strAck) + 1, (char*)&strAck);
}

```

Assume that there is just one slave and one master. I tried this code but got no answer. Where is the error?

# Answer
> 2 votes
The documentation for the constructors is out of date (I am re-writing as we speak, and is now here).

The constructors in the header file are like this:

```
ICSC(Stream *d, uint8_t station);
ICSC(Stream &d, uint8_t station);
ICSC(Stream *d, uint8_t station, int depin);
ICSC(Stream &d, uint8_t station, int depin);

```

That means you need to provide the serial object as the first entry:

```
ICSC icsc(Serial1, 'A', 5);

```

You need to manually start the serial object before ICSC.

```
void setup() {
    Serial1.begin(9600);
    icsc.begin();
}

```

This change was made to enable support for software serial and other Stream based devices.

---

Addendum for your update:

1. Don't spam the sending like you are. Send periodically, not constantly, or you will never be able to receive.
2. You cannot use String objects like that.
3. 1 and 2 aren't good choices of station IDs. Yes, they work, but not great, since 1 is the SOH character.

# Answer
> 1 votes
The documentation for the library notes a few different possible initialization methods:

```
ICSC.begin(stationId, baudRate);
ICSC.begin(stationId, baudRate, &SerialPort);
ICSC.begin(stationId, baudRate, &SerialPort, DEPin);
ICSC.begin(stationId, baudRate, DEPin);

```

So, if you need to define both a serial port and DE Pin, use the third option.

**EDIT:** Disregard this answer, as the library has changed initialization methods.

---
Tags: rs485
---


title: Identify UUID of HC-06

text:
# Question
Title: Identify UUID of HC-06
I'm currently learning about using BLE with Arduino and iOS. From what I understand (correct me if I'm mistaken), each type of BT device has a UUID. I'm using a HC-06 module connected to my Arduino. How do I find out what the UUID of a HC-06 is? I've been looking through data sheets to no avail.

# Answer
In Android, I used this UUID to connect to HC-06,

```
  socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

  inputStream = socket.getInputStream();
  outputStream = socket.getOutputStream();

```

You can use this UUID in your Android code, But over iOS, I think the Bluetooth is really a completely different hardware specs.

Hope I helped
> 3 votes

# Answer
Well guess what, HC-06 is not low energy so no iOS device will ever see that module despite whatever uUid you have, so go and get a bluetooth 4.0 aka BLE module
> 0 votes

---
Tags: bluetooth
---


title: cheap long lasting options for battery?

text:
# Question
Title: cheap long lasting options for battery?
I recently made a differential drive using Arduino UNO, two BO dual shaft 9v Motor and ld293d.To power Arduino, I am using a Hi-Watt 9 volt battery, to power the ld293d 5v pin (VCC1) I am using Arduino 5v Vout pin and to power its motor driver pins (VCC2) I am using Hi-Watt 9 volt battery.

The problem is its not long lasting and after moving just a bit like 30 seconds it slows down and stops ,or one of the motor stops working.I have tried this with multiple new 9v batteries, I don't understand why is this happening because the batteries still seems to be work on other projects.Should I use some other kind of battery if yes then what would be the cheapest option?

# Answer
> 3 votes
9V batteries are not meant for high-current discharge, as you would find when powering a motor. Not only that, they are low capacity. If you need to power motors, you should use batteries such as C or D cells in series to build the voltage required, or try Lithium-Polymer (LiPo) for a rechargeable option.

On a side note, the L293 H-Bridge is a poor choice of H-Bridge these days, especially for a battery-powered project, as there are more efficient motor driver ICs these days.

---
Tags: arduino-uno, motor, battery
---


title: what is arduino adc reference?

text:
# Question
Title: what is arduino adc reference?
I'm using arduino for the first time and don't really understand what am I suppose to plug to the ADC refernce PIN... or if I even have to use it while plugging analog sensor to the arduino, thanks!

# Answer
> 8 votes
The AD converter in the ATMega microcontroller (as used in Arduino) converts an **input voltage** to a **number**.

This ADC happens to be 10 bit that means 2^10 states which is 1024.

The number 0 (zero) means 0 Volt input voltage.

The number 1023 means the **maximum** input voltage.

Since 0 is also a value the scale runs from 0 to 1023 making 1024 values.

The scale is linear so 511 means half of that maximum voltage.

*What is this maximum input voltage?*

That is the **ADC Reference voltage**. By default the power supply voltage is used so if you run your Arduino on 5 V, then 1023 = 5 V. But if you run your Arduino on 3.3 V, then 1023 = 3.3 V.

There is also in internal reference of 2.56 V (or 1.1 V depending on your Arduino), if you use that then, you guessed it, 1023 = 2.56 V (or 1.1V).

You might have a very fancy external reference voltage already available and if you want to use that, use the external setting and connect that reference voltage to the AREF pin.

If your analog sensor gives 0 to 5 V and your Arduino is also powered by 5 V then you should use the default setting so that the VCC is used as ADC reference.

If your sensor gives a voltage between 0 and 1 V then you could use the internal reference so that more of the 0 to 1023 range is usable. Giving you get better resolution.

# Answer
> 3 votes
The default behaviour is for the analog reference to be Vcc which on many Arduinos is 5V. In that case *do not* connect anything to AREF.

However if you have a *precision voltage reference* then you can connect that to AREF (and GND) and specify in your sketch, **before doing an analogRead**:

```
 analogReference (EXTERNAL);

```

I have a page about the ADC converter which may help explain, or may be too much detail. :)

---

> or if I even have to use it while plugging analog sensor to the arduino

Unless you are planning to use some different reference voltage, don't use it at all.

For a 5V Arduino the voltage measured with the default AREF would roughly be 4.88 mV per unit of measurement (ie. 5V / 1024), but more accurately:

```
float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

```

---

The voltage you supply to VREF (if you supply any at all) must be between 1.0V and Vcc where Vcc would be 5V for an Arduino Uno.

# Answer
> 2 votes
The AREF is a reference voltage input pin.
The reference voltage is maximum voltage when you measure analog signal.
In other words, you can measure 0V ~ AREF voltage by using ADC port.

Be aware that the minimum voltage of AREF is 1.0V.

# Answer
> 1 votes
Well, I think you should read the manual first before you use (and even perhaps brake it).

Generally speaking, analog reference is a voltage value between 0.00 and 5.00V, which will be used as virtual reference for all the analog inputs, you connect to your arduino board.

About analog reference is on Arduino site: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/

---
Tags: analogread, adc, analogreference
---


title: Additional Digital Input Pins

text:
# Question
Title: Additional Digital Input Pins
I require additional digital input pins for 5 PIR sensors. Can I use the shift register (74HC165) to read these input? And will I be able obtain real time values from all the 5 sensors?

# Answer
> 2 votes
You could use a GPIO expander (MCP23017 or similar) which could give you 14 extra pins (16-2 for I2C bus), but this is putting extra load on the microprocessor. (you haven't said which one by the way).

Or another option might be to revisit you design and see if you can split it out to multiple processors. This is effectively the same as a GPIO Expander, just using an Uno or ESP8266 as the expander.

---
Tags: arduino-uno, shift-register, digital-in
---


# Question
Title: Save a fingerprint to the database of the fingerprint sensor
I'm using the Adafruit Kookye fingerprint module in my project. Since it can only allocate 256 fingerprints I need to make a program to free the memory and add additional users. I have made the following function at the library:

```
uint8_t Adafruit_Fingerprint::downloadModel(uint16_t id, uint8_t packet_1[], uint8_t packet_2[], uint8_t slot) {
  uint8_t packet[] = {FINGERPRINT_DOWNLOAD, slot};
  writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet);
  uint8_t len = getReply(recvPacket);

  if ((len != 1) && (recvPacket[0] != FINGERPRINT_ACKPACKET))
   return -1;
  if (recvPacket[1] == 0x00) {
    writePacket(theAddress, FINGERPRINT_DATAPACKET, sizeof(packet_1)+2, packet_1);
    writePacket(theAddress, FINGERPRINT_DATAPACKET, sizeof(packet_2)+2, packet_2);
    return recvPacket[1];
  } else {
    return recvPacket[1];
  }
}

```

This function is working, it puts the fingerprints to the buffer 1 and when I call the function to save with the ID it also works. When I print the fingerprints in the sensor, the structure is exactly the same as if they had been added directly from enrolling. However, when I serach the fingerprints the sensor always returns that the user does not exist.

I don't know what's the problem.

# Answer
The `sizeof()` operator doesn't do what you think it does. It's not a function that is executed at runtime, it's an operator that is interpreted at compile time.

It takes a variable and returns the size (in bytes) of that variable. Since you are passing it a pointer it gives you the size of that pointer. That's 2 bytes on an 8-bit system like the Uno.

In C an array is not a single entity with a size. It's a pointer to a block of memory that has been reserved at the time the array is declared. All you get is that pointer, and it's up to your program to remember the size.

You will have to pass the size of the arrays your `packet_1` and `packet_2` pointers are pointing to, or always assume that those arrays are the same size at all times.
> 3 votes

---
Tags: arduino-uno, c++, library
---


# Question
Title: Possibility to program the ATmega32u4 on the Arduino Yun using a configuration file
Is it possible to send a **Configuration File** viz. `conf.json` that can be sent to the Arduino Yun via Ethernet and a Python Program can parse the configuration and set for example **Sampling Rate** of a Sensor which is connected to the **32u4**?

The problem for me is that **Sampling Rate** in the Arduino Sketch is actually a preprocessor directive and I understand that C++/Arduino Sketches need to be compiled once before the changes take place.

However, how can I change the preprocessor directive in the sketch using a configuration file?

**e.g.**

```
#define SAMPLE_RATE (100)

```

in a `conf.json` file somewhere there might be:

```
{"sample_rate": 1000}

```

Once the `.json` file is parsed using python is it possible to change

```
#define SAMPLE_RATE (100) // to #define SAMPLE_RATE (1000)

```

# Answer
> 1 votes
You can't. You'll have to change your macro into a variable and change that variable when suitable data is received through the serial port.

You may also have to trigger a reconfiguration of whatever software is doing the sampling, or reconfigure the hardware, depending on what it is you are sampling.

---
Tags: arduino-yun
---


# Question
Title: Can't send serial data throught serial pins but it works with the usb port
I am just starting out a project and I am having a little bit of trouble. I want to send data collected from an IR distance sensor, and send it with an XBee Pro S2B to my computer so I can do other stuff with it. The code I am using right now is pretty simple:

```
void setup()
{
  Serial.begin(9600);
}
void loop(){
 int distance = analogRead(0);
  Serial.println(distance);
  delay(1000);
}

```

The problem I am having is that when I turn on the arduino with batteries and disconnect the usb cable, the tx light stops turning on and no serial data is sended, AND if I connect it to the computer via USB again it won't work anyway, only works right when I upload the code. The XBees are configured correctly, I have done the chat example on the Building Wireless Sensor Networks by Robert Faludy.

Is it some code error? I must be really obvious. By the way, when I upload the code and the serial data is sended throught usb, the data displayed on Arduino IDE's console is correct, so the sensor is wired correctly.

I am using an Arduino UNO and I have the XBee's and arduino's drivers installed correctly, and for the XBee I am using the XBee Explorer from Sparkfun

# Answer
I suggest you try to flash the pin 13 LED in your loop(). It seems like the Arduino is not booting correctly on the batteries?

The serial port on the uno is kinda messy, it shouldn't really be shared with the usb port like that. I prefer the Leonardo for these applications - where the USB serial and serial pins are totally independent.
> 1 votes

# Answer
You have an XBee shield on top of the Arduino UNO?

Do you have an XBee attached to the computer?

Can you describe your setup a little more.

The TX Led on the Arduino is only on the USB side, and doesn't signify TX on the XBee. The XBee itself should/could have a TX/RX leds itself. Check the Arduino schematic to confirm this.

How are you reading the Serial on the computer? Thru the Arduino serial monitor? That won't work for the XBee. You'll need another Serial monitor for the XBee attached to the computer. ie, Arduino with XBee shield. Then an XBee connected via some breakout board to the computer. The Arduino Serial monitor won't see the XBee (use hyperterm on windows or some serial port monitor on other systems).

Also, check your switch on the XBee (if you have one), most redirect the USB/Serial connection between computer/Arduino and Arduino/XBee. It's one or the other not both.
> 0 votes

# Answer
Try interchanging the Tx-Rx pins of your XBee-Arduino connection.

Since you are getting correct values on the Arduino IDE, this means that both sensor and serial is working, but it sends values only when connected via USB which means that problem lies in your link between Arduino-Serial Device (in this case XBee)
> 0 votes

# Answer
Ok, I have verified this behavior with a bare Uno on an external power supply driven from Vin.

The serial is outputting, but because of the way the TX and RX LEDs are wired in the Uno, they do not activate unless the USB processor is active.

This is super dumb and super confusing, but you can clearly see it's wired up this way:

I have confirmed that serial data is coming out of the Arduino with a logic analyzer, but the LEDs **do not** light up.
> 0 votes

# Answer
Finally found out how to get the Arduino Uno serial port to work without a USB cable! I used a scope to see what was going on and found that using an external power supply on the Arduino power port only showed +3.3 volts on the +5 line. I pulled the plug on the external power supply and put a regulated +5 VDC on the +5 VDC pin. Now, both software serial and the UART ports work fine - hope this helps!
> 0 votes

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


title: boolean always false after 32 seconds

text:
# Question
Title: boolean always false after 32 seconds
I have a boolean expression (I think it's called), and it will always return false after 32 seconds of running, and I'm very confused now.

```
if (millis() > stepTime+lightCmd[stepe][5]) {
  stepe = (stepe+1)%STEPS; //I'm bad at naming variables, sorry
  stepTime = millis();
  Serial.println("changing"); // debugging
}

```

This runs inside the main loop.

Also, I've tried using an exponent when trying to get some lights to appear to fade linearly and in about the same amount of time, 32 seconds, it would start fading in reverse.

EDIT:

millis(); wouldn't go backwards after it stopped working

# Answer
When dealing with `millis` and `micros` you must always use `unsigned long` variables; otherwise, values will be overflow/truncate.

When doing time arithmetic, you must always use differences, not additions, because of the nature of unsigned arithmetic.

Your updated sketch is this:

```
void setup()
{
    Serial.begin(9600);
    while(!Serial);
    Serial.println(); Serial.println("Test");
}

#define STEPS 3
unsigned long lightCmd[STEPS] = {4000, 60000, 90000};
int stepe = 0;
unsigned long stepTime = 0;

void loop()
{
    if(millis() - stepTime >= lightCmd[stepe]) {
        Serial.print(stepe);
        Serial.print(".- ");
        stepe = (stepe+1)%STEPS; //I'm bad at naming variables, sorry
        stepTime = millis();
        Serial.print(stepTime);
        Serial.println(" changing"); // debugging
    }
}

```
> 0 votes

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


title: Modifying Print.h on a Mac

text:
# Question
Title: Modifying Print.h on a Mac
Most of my Arduino work has been on a PC, but now I am on a Mac. I need to modify Print.h to give me printf facilities, as detailed here.

I can find Print.h buried within my application files, but changing it has no effect. A search across my disk reveals no further Print.h files.

Where on a Mac should I find and edit the Print.h file?

Can someone tell me what I am missing please?

Thanks,

Martin

# Answer
> 1 votes
There must be a print.h in the Arduino IDE. Try to reinstall. In this webpage, there is no specification about the platforms where it is neither where it's not.

And, of course, you don't need to edit anything: use a medium/big sized string with `sprintf`and you could use the printf capabilities.

# Answer
> 1 votes
Each hardware package has its own version of Print.h in the cores folder. The Arduino IDE installation includes a copy of the Arduino AVR Boards hardware package but that package will not be used if you installed a different version via Boards Manager (**Tools \> Board \> Boards Manager**) or if you have a board selected from the **Tools \> Board** menu that is not part of the Arduino AVR Boards package. Operating systems seem to like to hide the folder that Boards Manager installs the hardware packages to by default, which makes things more confusing.

The easiest way to find the location of the active hardware package, and thus the Print.h you want to edit is this:

1. Select a board of the hardware package you want to locate from the **Tools \> Board** menu.
2. **File \> Examples \> SPI \> BarometricPressureSensor** (or any other example sketch of the SPI library)
3. **Sketch \> Show sketch folder** \- this will open the BarometricPressureSensor example sketch folder.
4. Navigate up 4 folder levels to the architecture folder.
5. Open the `cores` subfolder of the architecture folder.
6. If there are multiple folders inside the `cores` folder you will need to open boards.txt (which is located in the architecture folder) and find which core library your board is using, which is specified by the `build.core` property. Most hardware packages only have a single core library so this should not be necessary.
7. Open the core folder. There you will find Print.h.

The reason I selected the SPI library example is because this is a hardware specific library that is bundled with all hardware packages I've encountered. If you encounter a hardware package that does not bundle an SPI library you would want to open the example for another hardware specific library such as Wire, SoftwareSerial, or EEPROM.

---
Tags: arduino-ide
---


# Question
Title: Is this a good function for I2C receive?
I'm trying to fix my I2C code:

Is the following function correct because it has multiple returns. I don't know if that would work.

```
uint8_t I2C_rx(uint8_t ack_rx)
{
    uint8_t i;
    if (ack_rx)
    {
        TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA); // sending ACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
    else
    {
        TWCR = (1<<TWINT)|(1<<TWEN);           // sending NACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
}

```

# Answer
> 1 votes
No problem with multiple returns but it could be reduced to:

```
uint8_t I2C_rx(bool ack_rx)
{
  uint8_t cr = (1<<TWINT) | (1<<TWEN);
  if (ack_rx) cr |= (1<<TWEA);
  TWCR = cr;
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

```

or

```
uint8_t I2C_rx(bool ack_rx)
{
  TWCR = (1<<TWINT) | (1<<TWEN) | (ack_rx<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

```

Cheers!

---
Tags: i2c, c, data
---


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

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

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

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

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

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

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

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

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

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

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

```

and you can read the encoder simply as

```
uint8_t ecoder_value = PIND & 0xf0;

```

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

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

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

```
int32_t absolute_position;

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

```

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

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

Lastly, you have to define the limits:

```
int32_t left_limit = INT32_MIN;
int32_t right_limit = INT32_MAX;

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

```

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

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

```

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

# Answer
It is quite difficult to say any thing without the actual code, but if you are reading the position of the cam regularly you can implement a "if/else" condition. Some thing like this:

```
if(position==A)
reverse();
else
continue;

```

(this is very crude and undefined and there are many ways to improve it) Here position is assumed to be the position of the cam and A is the maximum that can be traversed to. A same condition can be applied in case of the other end as well. (also reverse() is a function that reverses the direction of motion. In addition to this, you can replace reverse() by some thing like stop() and after that check "position" is greater than A call the reverse function till the condition is met. Hope this helped.
> 0 votes

---
Tags: arduino-uno, programming, sensors, motor, rotary-encoder
---


# Question
Title: How do I import data from serial monitor to excel document without copying and pasting?
I need to be able to import incoming data from a motion sensor and then from the serial monitor (where the data is) import the data to an excel document or file.

Any suggestions would help,

Thanks.

# Answer
> 4 votes
The Arduino IDE's serial monitor is just one of many tools that can open a serial port and collect information from it.

The first step is to make sure the data you are writing to the `Serial` object in the Arduino is in a format suitable for importing into Excel. Separate multiple values on one line with a comma `","` or tab `"\t"` character.

If you are running windows, you can often just use the built-in `type` command from a command prompt to write the serial port to a file:

```
type COM4 >> log.txt

```

(Assuming the Arduino is on COM4 and you want to write the data to a file called `log.txt`.)

If you're on a Mac, open the Terminal app and type:

```
screen -L /dev/tty.usbmodem1441335 9600

```

(Assuming your Arduino is on serial port named `tty.usbmodem1441335` and your port speed is 9600 bps.) The session will be written to a file called `screenlog.0`.

Then you can open the text/log file in Excel. If you rename it to end in `.csv`, that may also help Excel recognize it as tabular data.

---
Tags: arduino-mega, serial-data
---


title: What is FaryLink? [Access Point]

text:
# Question
Title: What is FaryLink? [Access Point]
When powering up my WeMos D1 ESP8266, I suddenly find this hotspot named "FaryLink". What is this? I programmed the ESP to work as a web server, thus connecting to an existing hotspot and not providing any beacons or acting as an access point.

Google could not provide any information to this behaviour.

What is the purpose of this AP and how can I use / disable it?

# Answer
> 4 votes
Did you use `setmode()` to put it in station mode?

**wifi.setmode()**

Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

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

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

NOTE: WiFi Mode configuration will be retained until changed even if device is turned off.

**Syntax**

```
wifi.setmode(mode)

```

**Parameters**

mode value should be one of

* wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
* wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
* wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
* wifi.NULLMODE to switch off WiFi

**Returns**

current mode after setup

---
Tags: esp8266
---


title: PWM help (input changing duty cycle)

text:
# Question
Title: PWM help (input changing duty cycle)
Is there a way to adjust the duty cycle (PWM) based upon input gained by a sensor. For example, if the sensor picks up a really high value, it would increase the duty cycle for an LED making it brighter. Can we also do this task without a potentiometer? Can all of this be done "hands-free" by the Arduino?

# Answer
> 1 votes
The example at the bottom of this Arduino reference page does exactly that. If you want to change the way the value varies, you can just modify the variables in a loop or in whatever approach you prefer instead of analogread'ing it.

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

# Answer
> 1 votes
There is a simple project that can be done with a photo-resistor for an analog input, a light levels sensor circuit, and an LED for an output.

The software requirement is to have a loop with a delay that reads from the analog pin the photo-resistor is attached and use that value to set the Duty Cycle for the PWM output pin driving the LED illumination level.

You can then test by shading the photo-resistor from the ambient light (I used a sheet of paper rolled up into a tube and placed over the photo-resistor on the breadboard), putting it into darkness, and by using a flashlight to provide more light than ambient in order to test the range and watch the LED dim and brighten.

I have done this project with a Raspberry Pi, which required an MCP3008 Analog to Digital Converter to interface to the photo-resistor circuit since the Pi has only digital pins. Arduino has analog pins so the ADC is not necessary.

The project that I did with my Raspberry Pi is at URL: https://github.com/RichardChambers/raspberrypi/tree/master/project08 with C source code and a link to the manufacturer of the experiment kit I am using which has the details for the actual circuit. What I did was to make the LED illumination level track to the inverse of the value reported by the photo-resistor circuit. So when the light level was low as reported by the photo-resistor then I made the LED brighter.

---
Tags: arduino-uno, pwm
---


# Question
Title: Project structure to build for PC and Arduino
Recently I have started developing for Arduino Uno. I have 10 years experience in software development (C#, Delphi), but not much with C/C++. Compiling the Arduino sketches seems a little slow, and debugging isn't as convenient as it could be on a PC (compile, upload, watch the serial monitor, modify code, start over.... way too slow with lots of unnecessary steps) So what I would like to achieve is to organize my code in a way to be able to compile my code either to Arduino, or to PC for debugging purposes (to a small console app). I know that there are libraries that cannot be used on a PC, but those can be abstracted away (hidden behind a facade or something like that). Unfortunately I could not find any tutorials, or articles how to do this. So I hope you can help me out.

BTW I'm using Visual Studio (with Visual Micro) on a Windows 10 computer.

# Answer
I haven't done it yet, but you could do the following things to get a somewhat close approximation:

* Make three different projects, one for the PC (only), e.g. Visual Studio, and one for Arduino (with the default Arduino IDE or e.g. Visual Micro). The last will be a generic library to be used for both the PC and Arduino.
* Use the Arduino specific libraries only for the Arduino project.
* Create facade/wrapper classes for each Arduino library.
* Use a mock/stub for the Arduino libraries in the PC only project.
* Put all non-hardware related code in separate classes, to be used by both projects.
* Write unit tests for the PC only project.
* The PC project will be tested by unit tests, and can be debugged on a PC
* Only the specific Arduino libraries/interfaces have to be tested using the 'hard way', e.g. with Serial.

So the projects (including testing) will look like:

* PC Project
    + References common code
    + Stubs for Arduino libraries, stubs can possibly be reused by PC Unit tests
* PC Unit Tests
    + Unit tests
    + References common code
* Arduino Project
    + Containing Arduino libraries
    + References common code
* Common Code
    + All domain specific classes
> 2 votes

---
Tags: arduino-uno, programming, windows, visualstudio
---


# Question
Title: Not clear code procedure in Arduino wire library
The application code of sparkFun, has the following line which is difficult to understand.

It's requested 6, because it's requesting 6 bytes for HMC5883L module.

```
Wire.requestFrom(address, 6);
if(6<=Wire.available())

```

Where:

```
int TwoWire::available(void)
{
  return rxBufferLength - rxBufferIndex;
}

```

So, the available function should return `return rxBufferLength - rxBufferIndex;` where `rxBufferIndex` is modified in `read` function:

```
int TwoWire::read(void)
{
  int value = -1;

  // get each successive byte on each call
  if(rxBufferIndex < rxBufferLength){
    value = rxBuffer[rxBufferIndex];
    ++rxBufferIndex;
  }

  return value;
}

```

But, my current question is why decrementing `return rxBufferLength - rxBufferIndex;` where `rxBufferIndex` is initialized to 0 all the time, and there's no chance the returned value would be less than 6, because that would terminate the if statement?

# Answer
> 1 votes
`rxBufferLength` is the number of bytes that have been received. `rxBufferIndex` is the byte you would next be handed with a `read()` function call.

So if you have received 6 bytes from the slave (which you will, since that is how many you requested) but not read any the `available` would be 6. Ergo, 6 \<= 6. I.e., you asked for 6, it collected 6, and you are checking that it got at least 6 (it can never be \>6 since you only asked for 6, so why they look for at least 6 I don't know).

`rxBufferIndex` is never decremented. It is incremented when you read a byte, up until `rxBufferLength == rxBufferIndex` at which point there is 0 bytes available.

---

> But, my current question is why decrementing return rxBufferLength - rxBufferIndex; where rxBufferIndex is initialized to 0 all the time, and there's no chance the returned value would be less than 6, because that would terminate the if statement?

The way that Wire.h works is that `available()` will always return the number of bytes you requested if the call to `requestFrom()` succeeded until you first read some of that data. If you request 6 and the call worked then you have 6. The `if` could just as well be written as:

```
if (Wire.available()) {...

```

since it will always be 6 immediately after a successful call. However, that makes assumptions about how the Wire API works and could be subject to change in the future or operate differently on different platforms.

So it checks that, right after the call to `requestFrom()` for 6 bytes it actually got *at least* 6 bytes. Without seeing what is inside the conditional `if`, all I can do is make assumptions, but I would assume that it is then reading those 6 bytes, and so it wouldn't care if there happened to be more for some reason. But it doesn't want there to be 5 or fewer bytes available when it is reading 6 of them.

An `if` statement doesn't "terminate" if its condition becomes false once it has been executed. It's not like a `while` that keeps running until it's false - it's a single decision made at a single point in time. If anything changes in the future that would have caused a difference decision to be made (e.g., you `read()` a byte, so `available()` would now return 5), the decision that has been made still stands.

An analogy for you:

You want to go out for a good healthy walk - but only if it's not raining.

```
if (!raining) {
    walk_to_shop();
    walk_to_cafe();
    drink_coffee();
    walk_to_shop();
    walk_home();
}

```

You go out for your walk to the shops, get a coffee, do some more shopping, and then walk home - but you only *start* doing that if it's not raining. If it starts raining while you're out you don't suddenly teleport back home. You *could* make the decision, when you come out of the cafe and see it's raining, to cut your shopping trip short, but you have to actively make that decision. Just because `raining` becomes true doesn't affect the fact that you are outside and walking.

---
Tags: c++, i2c, c, wire-library
---


# Question
Title: someVariable = { somethingThatLooksLikeAFunction }; possible?
Wasn't sure how to title this question...

I was curious whether the title example is possible somehow, and are there any good tricks to using it?

I have been using something similar quite a lot:

```
newBool = (someTest) ? true:false;
newInt  = (x + (y / z));
[...]

```

However, I was curious if it was possible to add far more conditions, almost like a function?

For some simple(\*) examples:

```
someThing = {
    int _x = aFunction(_x);
    if(_x) {
        something = somethingElse;
        for(...){ ... }; // etc
    } else {
        /* otherStuff */
    }
};

```

Or

```
someThing = {
    for(_x=0;_x<y;_x++){
        z++;
    }
    someThing = (z>y) ? a:b;
};

```

I understand it's worth just separating it off into functions most of the time, although I'm trying to get away from a function/library-fest as much as possible... It's getting annoying crawling through everything when I could just have the useful stuff right there, where I need it, instead of 1000 lines away, or in another library. It also allows the text editor to fold the code out of sight, starting from one variable, instead of on each clause.

With the few tests I have tried, I've not been successful in achieving what I'm experimenting with, so, is this kind of thing possible in any way? and if so, what are the rules/possibilities/different ways you could implement this?

* Emphasis on simple! And a semi-pointless/completely useless "function" alert too! I'm just curious about the "proof of concept" in the examples...

# Answer
> 1 votes
You can do it with a `lambda` function, though the syntax is somewhat cryptic:

```
int someThing = [](int y, int z, int a, int b){
    for (int _x = 0; _x < y; _x++) {
        z++;
    }
    return (z > y) ? a : b;
}(100, 0, 10, 20);

```

In that you are defining a lamda function `[]` with four parameters, `y`, `z`, `a` and `b`. Then calling that function with four numbers `(100, 0, 10, 20)` and assigning the return value to `someThing`.

It's the same as writing a normal function but there's a lot more brackets around.

---
Tags: programming
---


# Question
Title: How to get Velocity and Displacement from IMU sensor?
I have an imu mounted bot.I want to get the speed of the bot using imu i dont want to use the encoders. Imu gives acceleration how should i integrate that to get velocity and how much error would be there??

# Answer
The error in this method would be massive.

Velocity is the integration of acceleration over time. However, you don't have acceleration over time - you only have acceleration at discrete points in time - the times that you actually sample the acceleration.

You would want the total acceleration between two points in time, which you just don't have.

Take the following timeline of acceleration points:

```
+3 +2 +5 +2 -3 -4 +3 -5 +3 +2 +6 -4 -2 +3 -4 -5 +6 -3 -1 -2 +7 -2
 ^           ^           ^           ^           ^           ^

```

The carets are the points where you are actually sampling the acceleration.

Assuming you start from 0m/s, and those are all changes in m/s, your calculated speed from your samples would be 3-3+3-2+6+7 = 14m/s. However, the real velocity would be 7m/s.

In reality, there aren't discrete points of acceleration - just a single smooth waveform.

The faster you can sample the closer to reality you get, but there's always a chance that you would miss some critical brief change in velocity.

On top of that, you have noise. Quantisation noise, vibration, electrical noise, etc - all of which add a certain amount of uncertainty of their own.
> 2 votes

---
Tags: arduino-mega, speed
---


title: Code is not working (Matrix keypad)

text:
# Question
Title: Code is not working (Matrix keypad)
I am new to Arduino. I am learning from Arduino Cookbook. I was using tinkercad.com for running my Arduino code. But it is not working. The Serial monitor should show the key which I have pressed on the keypad. I think there is some syntactical error in the code, I believe the connection is all right. Any suggestion will be appreciated. Please look into this:

```
const char keymap[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
 };
const int rpin[]={9,8,7,6};
const int cpin[]={5,4,3,2};
void setup()
{
  Serial.begin(9600);
  Serial.println("Program starting");//for debugging purpose and canbe removed later
  for(int i=0;i<4;i++)
  {
    pinMode(rpin[i],INPUT);
    digitalWrite(rpin[i],HIGH);
  }
  for(int j=0;j<4;j++)
  {
    pinMode(cpin[j],INPUT);
    digitalWrite(cpin[j],HIGH);
  }
}
void loop()
{
  char key=getkey();
  if(key!=0)
  {
   Serial.println(key);
  }
}
char getkey()
{
  char key=0;
  for(int i=0;i<4;i++)
  {
    digitalWrite(rpin[i],LOW);
    for(int j=0;j<4;j++)
    {
      if (digitalRead(cpin[j])==LOW)
      key=keymap[i][j];
    }
    digitalWrite(rpin[i],HIGH);
  }
  return key;
}

```

and the connection pic:

update 1:

# Answer
> 4 votes
Cited comment:

> Check pin modes. Should be INPUT\_PULLUP and OUTPUT. Also, consider debouncing. – Mikael Patel

Please, try:

```
const char keymap[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
 };
const int rpin[]={9,8,7,6};
const int cpin[]={5,4,3,2};
void setup()
{
  Serial.begin(9600);
  Serial.println("Program starting");//for debugging purpose and canbe removed later
  for(int i=0;i<4;i++)
  {
//Should be INPUT_PULLUP and OUTPUT
    pinMode(rpin[i],OUTPUT);
    pinMode(cpin[i],INPUT_PULLUP);
  }
}
void loop()
{
  char key=getkey();
  if(key!=0)
  {
   Serial.println(key);
   delay(200);              // Also, consider debouncing.
  }
}
char getkey()
{
  char key=0;
  for(int i=0;i<4;i++)
  {
    digitalWrite(rpin[i],LOW);
    for(int j=0;j<4;j++)
    {
      if (digitalRead(cpin[j])==LOW)
      key=keymap[i][j];
    }
    digitalWrite(rpin[i],HIGH);
  }
  return key;
}

```

---
Tags: arduino-uno, sketch, code-review
---


title: Where can I storage a local database?

text:
# Question
Title: Where can I storage a local database?
I want to create a website where the users can have their own database. An example: \- An user will receive some data from HTTP POST and I want to storage all the information into a local database to access to it. For example, the URL that the user has visited in the last month.

I know that the best option will be to create a database in my server and put each user in it, but it will be very long database and the information between users is not shared, therefore it will be more secure using a local database, but I don´t know if that can be done.

My project is about ESP8266 and uploading data to a server, so this can be done using a microcontroller instead the computer. I have seen the raspberry to use it as a server and storage there the database, but it is so expensive. Can be done using another board as Arduino, Texas Instruments, etc...

The main aim is to create a main hub to storage all the values received from the ESP8266 and then share over internet, but I don´t know how to build a hub where I can store a database inside and a HTML website to show the values. Any ideas? I would like to avoid a computer to do it.

I think in something for less than 10 GBP, because I bought and Arduino and Ethernet shield for 5 GBP both, fake version, but useful for my project

# Answer
You can use the Sparkfun data project:

https://data.sparkfun.com/

they build an open source tool called `phant` (https://github.com/sparkfun/phant) that you use to host on your own or use their free version online
> 1 votes

# Answer
As I understand the question, you want a 'mini' database for your ESP8266, without the need to connect to the internet.

One way I can think of is that you could use your ESP8266 flash memory to store the database. Use SPIFFS with, say, 1 MBytes flash size, leaving 3 MBytes for your actual program (assuming the ESP8266 has 4 MB flash memory). More than 20 thousand record files for 50 bytes each.

But you'll need to write your own create, read, update, delete (CRUD) function to handle the files.

If someone has already written such functions, that would be useful to share here.
> 1 votes

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


# Question
Title: Connecting two analog multiplexers (CD4051b)
Is it possible to connect two CD4051b analog multiplexers together so that I can receive 14 analog inputs through them? Just by using one analog pin and three digital pins on the Arduino UNO.

# Answer
Each CD4052B multiplexes 8 input to one output, and you need three digial pins to control it. You have the six analogue input pins available and those pins can also serve as digital outputs, so you should be able to use them to do what you need.

I would do as follows:

Assign three of your spare pins to be digital outputs. Use these three to address both CD4052Bs together -- so both devices will receive the same addressing.

Connect the output of one CD4052B to the fourth analogue pin, and the output of the second CD4052B to the fifth analogue pin. These will be your inputs.

On both CD4052Bs, tie the INHIBIT pin low, so they are permanently on. (If you want to be able to switch them off, for some reason, you an use your sixth pin to control the INHIBIT line on both devices.)

Now when you want to read from sensor 1, you set `000` on the address lines (`A`, `B` and `C`) and read from the first input. At the same time you'll have sensor 9 on the second input.

It would be well worth reading the data sheet
> 1 votes

---
Tags: arduino-uno, analogread, digital, shift-register
---


# Question
Title: Serial Monitor not properly interpreting data from my NodeMCU V3
I've just received several LoLin NodeMCUs from a 'cheap Chinese ebay vendor'. They're working well except for the fact that I'm getting garbage in the Arduino IDE Serial monitor.

**I am able to:**

1. Load and run sketches
2. Use the NodeMCU as a webserver and connect to it from a computer/smartphone/etc
3. Everything you else you would expect an ESP8266 to do EXCEPT

**I am not able to** get readable data to display in the Serial Monitor.

Some Details: -My computer is running Linux Mint so I understand that drivers shouldn't be a problem

-The NodeMCU board has instructions printed on it to 1) Install CH340G driver 2) Use 9600 baud rate 3) Connect to WiFi

-I **have not** tried issuing an AT command to slow the default baud rate down to 9600 (as suggested in answer to another question on this forum). Since the NodeMCU standard rate is 115200 and it's only talking to my computer and not another Arduino, I didn't think that would be required. {Could that be the answer to my problem?}

-I've tried all the standard baud rates between 9600 and 115200. None produced readable outputs.

-I've connected stabilized external 5 and 3.3 V power sources to the board and added some caps for extra smoothing.

I'm running the simplest sketch I could think of to send data back the Arduino Serial Monitor:

```
int LEDState = LOW;
int pinNum = D7;  //LED on D7 will flash while loop is running

void setup()
{
  Serial.begin(15200);
  pinMode(pinNum, OUTPUT);
}

void loop()
{
  digitalWrite(pinNum, HIGH);
  Serial.println("T");  // send the Letter T to the serial output
  for (int c = 0; c < 10; c++)
  {
    Serial.println(c); // send the count 0 to 9 to the serial output
    delay (200);
    LEDState = blinkLED(pinNum, LEDState); // blink the LED to demonstrate that the loop is running
  }
}

int blinkLED(int pinNum, int State)
{
  if (State == LOW)
  {
    digitalWrite(pinNum, HIGH);
    State = HIGH;
  }
  else
  {
    digitalWrite(pinNum, LOW);
    State = LOW;
  }
  return State;
}

```

---

I've tried all the various line endings (CR/LF, CR, LF, nothing at all). No success with any of them.

# Answer
> 1 votes
That's not the simplest sketch to send serial data to Serial Monitor. Instead, try this:

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

void loop(){
    delay(500);
    Serial.println("Hello World");
}

```

Upload and open Serial Monitor at 9600 baudrate. Your AT firmware is already erased, never expect 'OK' response for 'AT' command. If Serial Monitor displays 'Hello World', then your board is okay. Then, you have to reflash AT firmware if needed.

# Answer
> 1 votes
I seem to have found a solution to my own problem. I poached a code snippet from another post on this forum (which I don't seem to be able to find now or I would happily give credit for) and inserted it into my sketch. Works like a charm.

The code snippet resets the baud rate to 9600 within the program itself. I upload the sketch at 115200 baud, but then switch to 9600 baud to talk to the Serial Monitor.

I've been running this code on the NodeMCU for 14 hours now and it's still going strong.

My next steps will be to insert this code into the rest of the Example Sketches that use the Serial Monitor and see if they all work on the NodeMCU V3 now.

```
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

int LEDState = LOW;
int pinNum = D7;  //LED on D7 will flash while loop is running

void setup() {
//   ***  Additional Code that fixed my problem  ****
  Serial.begin(9600);
  ESPserial.begin(115200);
  ESPserial.println("AT+IPR=9600");
  delay(1000);

  // Start the software serial for communication with the ESP8266
  ESPserial.begin(9600);

  Serial.println("Ready");
  ESPserial.println("AT+GMR");

// ***   End of additional code

  pinMode(pinNum,OUTPUT);

}

void loop() {
  digitalWrite(pinNum, HIGH);
  Serial.println("T");  // send the Letter T to the serial output
  for (int c = 0; c<10;c++)
  {
    Serial.println(c); // send the count 0 to 9 to the serial output
    delay (200);
    LEDState = blinkLED(pinNum, LEDState); // blink the LED to demonstrate that the loop is running

  }

}

int blinkLED(int pinNum, int State)
   {
      if (State == LOW)
        {
          digitalWrite(pinNum, HIGH);
          State = HIGH;
        }
        else
        {
          digitalWrite(pinNum,LOW);
          State = LOW;
        }
        return State;
   }

```

---
Tags: serial, esp8266, nodemcu, linux
---


# Question
Title: ESP8266 12e Arduino IDE outputs garbage values on serial monitor
I recently started using the ESP8266 12E <sup>(Amazon link)</sup> and hooked the board up to the Arduino IDE.

When trying to run any of the example sketches, all sketches compile and upload correctly. The blink sketch correctly causes the LED to blink, however, in the serial monitor a varying and large quantity of junk characters appear:

The first thing I investigated was of course the baud rate. Online, documentation for the ESP8266 indicate 115200 as the correct baud rate, but on the bottom of the device, the baud rate is listed as 9600.

The junk characters, of course, appear whether the baud rate is 9600 or 115200. Using trial-and-error, I tried each other option. I've also tried several USB to micro-USB (c) cables. They're the same ones I use to charge my phone - is that the issue?

Am I missing something simple here? I searched each of the other Stack Exchange questions about garbage serial monitor values and they all seemed to indicate that the baud rate was the culprit, or that the CL / NR values needed to be changed. Experimentation with these did not result in removing the characters.

# Answer
> 2 votes
The baud rate you specify in your program and the baud rate in the serial monitor *must* match. The ESP8266 outputs a boot message at its own baud rate (varies from model to model - try 57600) before it executes your sketch.

For example:

You can choose any (within reason) baud rate in your program as long as you also choose the same baud rate in whatever is communicating with it (such as the serial monitor in the IDE). If you want to see the boot messages then the serial monitor will have to be set to the right baud rate.

# Answer
> 0 votes
I had what I think is the same problem you did. I posted my solution to it here:

Link to my solution

It seems that the ESP can upload code at 115200, but it can't talk to the serial monitor at that baud rate. The solution is to programatically change the baud rate within your sketch. The change in baud rate doesn't 'stick'. You have to include it in your sketch so it is set every time the sketch is run.

Hope that helps.

---
Tags: serial, esp8266, baud-rate
---


title: For loop not running

text:
# Question
Title: For loop not running
I've been trying to get a for loop to run 9 times using the below code but can't get the loop to run.

```
void output() {
  int r;
  r = 1;
  Serial.println("Output");
  digitalWrite(Latch, LOW);
  for (int r=1; r >= 9;  r = r + 1) {
    Serial.println("Test");
    digitalWrite(DataOutput, Q[r]);
    digitalWrite(ClockPin, HIGH);
    digitalWrite(ClockPin, LOW);
  }
  Serial.println("Done For");
  digitalWrite(Latch, HIGH);
  digitalWrite(Latch, LOW);
}

```

# Answer
Change

```
for (int r=1; r >= 9;  r = r + 1) {

```

to

```
for (int r=1; r <= 9;  r = r + 1) {

```

The for loop will only run while the second part is true.
> 7 votes

# Answer
The middle expression r =\> 9 in the for loop is wrong. This will only loop whilst r is greater than 9 and you are starting from r = 1. Change it to r \<= 9.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: SPI Temperature sensor interface with Arduino Uno
I want to interface with an AD7314 Temperature Sensor. I want to only read the temperature value from the sensor and output the value on to 8 LEDs connected to the Arduino. But so far I have not been able to read from the sensor. The datasheet says that the temperature readings are in 10 bit 2's complement, so I plan to convert to 8 bit before putting it out on the LEDs. Here is my code so far.

I am new to SPI and clearly don't understand the temperature sensor's datasheet. Please can anyone elaborate or explain where I am going wrong?

**Note: I have chosen pin A0 (PIN 23 of ATMEGA328P) as slave select and not pin 10**

```
#include <SPI.h>

byte val;

void setup (void) {
  pinMode(0, OUTPUT); //LED 1
  pinMode(1, OUTPUT); //LED 2
  pinMode(5, OUTPUT); //LED 3
  pinMode(6, OUTPUT); //LED 4
  pinMode(7, OUTPUT); //LED 5
  pinMode(8, OUTPUT); //LED 6
  pinMode(9, OUTPUT); //LED 7
  pinMode(10, OUTPUT);//LED 8
  pinMode(11, OUTPUT); // MOSI
  pinMode(12, INPUT); //MISO
  pinMode(13, OUTPUT); //CLOCK PIN
  digitalWrite(A0, HIGH);  // ensure Slave select stays high
  SPI.begin ();
  Serial.begin(9600);
} // end of setup

void loop (void) {
  // enable Slave Select
  digitalWrite(A0, LOW); // enable communication with slave
  delay (0.425);// wait for conversion
  val = SPI.transfer(0x00);// read from sensor
  Serial.println(val); // display reading on serial monitor
  // disable Slave
  digitalWrite(A0, HIGH);
}

```

# Answer
> 2 votes
```
delay (0.425);// wait for conversion

```

You can't delay a fraction of a millisecond. You can use delayMicroseconds though:

```
delayMicroseconds(425);

```

However, you don't need to sleep at all.

> The conversion clock for the part is internally generated so no external clock is required except when reading from and writing to the serial port. In normal mode, an internal clock oscillator runs the automatic conversion sequence. A conversion is initiated every 400 ms. At this time, the part wakes up and performs a temperature conversion. This temperature conversion typically takes 25 ms, at which time the part automatically shuts down. **The result of the most recent temperature conversion is available in the serial output register at any time.**

You have your chip select pin backwards:

> To ensure that the serial port is reset properly after power-up, the CE must be at a logic low before the first serial port access. **The serial clock is active only when CE is high.** For correct data synchronization, it is important that the CE be low when the serial port is not being accessed

So it should start LOW, and be set HIGH before you read, and back to LOW afterwards.

You need to read 2 bytes, not one, then combine them in the right way to make a proper 8-bit value:

```
digitalWrite(A0, HIGH);
uint8_t b1 = SPI.transfer(0x00);
uint8_t b2 = SPI.transfer(0x00);
digitalWrite(A0, LOW);

int8_t = (b1 << 1) | (b2 >> 7);

```

The reason for that is that the first bit of the first byte is a "leading zero" so you need to discard it, then add the first bit of the second byte as the last bit of your value, discarding the remainder of the second byte, since you specified only an 8-bit resolution in your question.

---
Tags: arduino-uno, programming, c, spi, electronics
---


title: ESP01 + Arduino UNO

text:
# Question
Title: ESP01 + Arduino UNO
I spent on this question more than 2 weeks of googling with no success. I do not get a response from ESP8266 version 01 on AT commands. I need to access Wi-Fi from Arduino via ESP8266-01. I know that ESP8266 can be programmed to work without Arduino and so on, but I need it to be a Wi-Fi module for Arduino. On most of the websites Arduino is used as UART for direct programming of ESP8266-01, but I am making this setup to make it work as a Wi-Fi support for Arduino:

```
  esp       Arduino
  ---       -------
   RX <---> pin 6 (TX) via voltage divider (5V-3.3V)
   TX <---> pin 5 (RX) (3.3V)
  Vcc <---> 3.3v
  GND <---> GND
CH_PD <---> 3.3V via 10k resistor
GPIO0 <---> 3.3V via 10k resistor
GPIO2 <---> 3.3V via 10k resistor

```

Then I upload this code on Arduino:

```
SoftwareSerial espSerial(5, 6);

const int COM_BAUD = 9600;

void setup() {
  espSerial.begin(COM_BAUD);
  Serial.begin(COM_BAUD);
  Serial.println("Setup done");
}

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

```

It prints on AT monitor: Setup done

But when I send AT command it is not even printed on AT monitor.

One more point -\> New wifi called "AITHINKER..." is being created and I even connect to it, of course, this does not grant me access to the web. But this is a good sign telling that ESP8266-01 is working, both current and voltage are enough for operation.

So it does not respond or receives AT commands. There is no documentation for correct connection of esp01 as wifi of Arduino Uno and I will be very happy if you could share some websites using ESP8266-01 as Wi-Fi of Arduino Uno correctly.

There are some points which are usually resolved other problems of such kind, but did not resolve mine: \- External power supply with common to Arduino ground -\> done \- Change RX, TX pins -\> done \- Replace ESP8266-01 -\> having 5 of them, protecting from over voltage

Please, help me... Losing any hope on this...

P.S. It responds to AT commands when I connect it directly to the computer via USB UART cable. The problem comes when I connect it to Arduino as the module...

# Answer
The AT command firmware for the ESP8266 modules have not always been set to 9600 bps. You might try 115200 and 57600 bps settings and see if that shows the result.

Also, connect the ESP8266 module directly to an FTDI or similar UART-USB bridge, temporarily eliminating the Arduino, so you can do more experimentation with the baud rates, etc. Then you would be able to easily see if the startup output from the ESP8266 looks garbled (which might indicate a serial speed mismatch), or if there is no output at all.

Another possibility is that the AIThinker module doesn't have the AT command firmware on it. From what source did you obtain the module -- what documentation is provided by that vendor?
> 2 votes

# Answer
I have previously written an Instructables article about how to set up an ESP8266 ESP-01 Wi-Fi module available here: Definitive Guide to Setting Up Your New ESP01 Module, which includes more or less everything you need to know to set up and interface your ESP8266 chip with either your computer or your Arduino Uno (on step 4, which mentions that you should reduce the baud rate).

The main problems you might be facing right now are:

* The Arduino Software Serial ports only support speeds up to 57600 baud if I'm not wrong, but the ESP-01 module typically comes out of the box with 115200 baud.
* The Arduino 3.3V regulator may not have enough current to supply the ESP8266. It's a very power hungry chip relative to an Arduino. If you don't mind, do post a picture of your Arduino Uno (or compatible) so I know if it's a power supply issue.
* The Arduino 3.3V pin does not provide adequate power supply decoupling, which may cause the ESP8266 to malfunction with cheap power supplies.

I designed a PCB called the ESPBlaster which you may be interested in. It takes a USB-TTL module on one side and has a socket for an ESP8266 module on the other to facilitate direct communications from your computer to the ESP8266 so you can set it to the correct baud rate so that you can interface it with an Arduino Uno, and contains a specially designed voltage regulator which does provides adequate current and decoupling.
> 1 votes

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


# Question
Title: Are lambdas a good way to improve readability in this instance?
Disclaimer: The following code hasn't been compiled, and probably won't work in any way. This is just for opinions relating to this Arduino question as I'm still learning and experimenting with different coding techniques.

As I understand it (and please feel free to offer a (4.)), the following code could be written in numerous ways, including:

1. No lambdas, and each following lambda as a separate function of its own.
2. No lambdas, no external functions, and having it all flow within the same function.
3. Using lambdas in a similar way to the code provided below.
4. ?

As my programs are getting sizeable, I'm currently finding it difficult to keep track using (1.) and/or (2.) when writing programs, especially if bugs show up. This has led me to question if there was a way to reduce a great many `if` and `for` (etc) into a single, text-editor-foldable "*seed*" (i.e. a single variable).

In my original question it was suggested that a possible way to do this could be option (3.) using lambdas. However, it was also pointed out that it may be overkill/not practical, and without any examples of what I'm trying to achieve, it was difficult to make a more informed judgement. So with this in mind, I have thrown together an example showing how lambdas could help me achieve some readability to my code.

If this is an acceptable technique, or not, I would be extremely grateful for any advice.

Code, lambda example, unfolded:

```
// Structs data, fans;
void temperatures(int _temperaturePin) {

  data.cTemp = [](int _tPin) { // current temperature
    float _finalReading = 0.0f;
    for (int i = 0; i < temperatureResolution; i++) {
      float _currentReading = analogRead(_tPin);
      _finalReading += ( 10000 / ( ( 1023 / _currentReading ) - 1 ) );
    }
    _finalReading = (_finalReading / temperatureResolution);
    return (uint8_t)_finalReading;
  }(_temperaturePin);

  bool fanState = []( int rOne, int rTwo, int rThree ) { // fans on or off
    int _lowMin = data.tempTarget - ((data.tempTarget - data.tempMin) / 2);
    int _medMax = data.tempTarget + (( data.tempMax - data.tempTarget) / 2);
    bool _fanState = false;
    if (data.cTemp < data.minTemp) {
      digitalWrite(rOne, LOW);
      digitalWrite(rTwo, LOW);
      fans.off = !_fanState;
    } else {
      _fanState = true;
    }
    if ((data.cTemp > data.tempMin) && (data.cTemp > _lowMin)) {
      digitalWrite(rOne, LOW);
      digitalWrite(rTwo, HIGH);
      fans.low = _fanState;
    }
    if ((data.cTemp < data.tempTarget) && (data.cTemp < _medMax)) {
      digitalWrite(rOne, HIGH);
      digitalWrite(rThree, LOW);
      fans.medium = _fanState;
    }
    if (data.cTemp > data.tempMax) {
      digitalWrite(rOne, HIGH);
      digitalWrite(rThree, HIGH);
      fans.high = _fanState;
    }
    return _fanState;
  } (relayOne, relayTwo, relayThree);

  bool overloadProtection = [](bool _fState, int _lCount, int rCount) { // overload protection on or off
    bool _protect;
    int _pwmValue = 255;
    if (_fState) {
      _protect = ((_lCount > MAXLEDS) || ((_lCount > (MAXLEDS / 2) && (_rCount > MAXRELAYS) ))) ? true : false;
    }
    if (_protect) {
      for (int i = 0; i < _lCount; i++) {
        _pwmValue -= 10;
      }
    }
    for (int i = 0; i < _lCount; i++) {
      if (ledPins[i] == HIGH) {
        analogWrite(ledPins[i], _pwmValue);
      } else {
        digitalWrite(ledPins[i], LOW);
      }
    }
    return _protect;
  }(fanState, sizeof(ledPins), sizeof(relayPins);
}

```

Code, lambda example, folded:

I can see that methods vs lambdas don't appear to make a huge difference to overall word count in this case, however, I can happily fold away `temperatures()` and know that's the root of everything I need for anything temperature related (without having to break off into another library; as far as I am aware), instead of having potentially 3 more functions sitting there and cluttering up screen space.

This also makes working within `temperatures()` a less daunting task than having potentially 100's of `for` and `if` (etc) statements permanently in view.

I'm only a hobbyist programmer at the moment, learning in my own time with no formal programming education, so I am 100% completely open to any suggestions or advice, especially due to ignorance regarding this subject on my part.

Much appreciated!

P.S. codereview.stackexchange requires working code to post there otherwise I would have.

# Answer
**Standard method using normal functions**

Quickly tell me, what does the `temperature()` function do?

```
// Structs data, fans;
void temperatures(int _temperaturePin)
{
  data.cTemp = getTemperature(_temperaturePin);
  bool fanState = getFanState(relayOne, relayTwo, relayThree);
  bool overloadProtection = getOverloadProtecton(fanState, sizeof(ledPins), sizeof(relayPins);
}

```

Well, it get the temperature, fan status and overload protection status. No need to know about lambdas, or even know C/C++: if you know *any* programming language (PHP, Javascript), you will able to understand what this code do.

Of course, `getTemperature` and others are implemented as traditional functions elsewhere. It's not important or relevant to know how they work, just what they do/return. I can write it in another source file and forget about them, never to be seen again.

**Lamba method**

Same question (with your original code), what does the `temperature()` function do?

```
   // Structs data, fans;

    void temperatures(int _temperaturePin) {

      data.cTemp = [](int _tPin) { // current temperature
        float _finalReading = 0.0f;
        for (int i = 0; i < temperatureResolution; i++) {
          float _currentReading = analogRead(_tPin);
          _finalReading += ( 10000 / ( ( 1023 / _currentReading ) - 1 ) );
        }
        _finalReading = (_finalReading / temperatureResolution);
        return (uint8_t)_finalReading;
      }(_temperaturePin);
// More code ...

```

You have made one giant monolithic block of code, which is anatema by any standard. And code folding doesn't really solve that.

This not so easy to read. You have to scan searching for the each lambda end, taking mental notes about what is finally executing inside `temperatures()`. To much work, to much visual clutter, merging the *what to do* with the *how to do it*.

Think about testing. How do you test your lambdas? You can't do it easily. You need to extract the code from your application, to start with. And add all those external variables your are accessing from inside the lambda.

With traditional functions, no need to change your application to test your functions; just write a test program to exercise your code.

Think about code reuse. It's dificult with your code identify common code to refactor/reuse it.
> 1 votes

# Answer
There is a reason, why the lambda concept was added to the C++ standard. This isn't it. This is called obfuscation.

```
void temperatures(int pin)
{
  // read the temperature with higher precision than single adc read:
  data.cTemp = 0.0f;
  for (int i = 0; i < temperatureResolution; i++) {
    data.cTemp += ( 10000 / ( ( 1023.0 / analogRead(pin) ) - 1 ) );
  }
  data.cTemp /= temperatureResolution;

```

Even this is a much better than misusing the lambda.

The main goal should be readability (= self docummented code), so anyone can quickly understand what is going on there.

That is also one of the reasons why the functions exists. The primary goal is you don't have to use the same snippets of code again and again (copy-paste). Try to fix the same bug on many places instead of one function.

In this code you should learn about concepts of finite state machines and ring buffers/floating averages, ...

Anyway, I've always hated parts of code in 10000 lines long file with only two methods or so. It's freaking hell to maintain that kind of code. Yes, having many tabs is also hard, but not harder than scrolling in mile long file. (I hate folding)
> 0 votes

---
Tags: programming, arduino-ide
---