# Question
Title: When the TX and RX pins for Bluetooth are connected the LCD screen will not update. Why is that?
I have connected a Bluetooth shield and LCD screen to an Arduino Uno. I have two active low push buttons to increase or decrease the variable `desiredTemp`. This value is meant to be displayed on the LCD screen, and on my smartphone over the Bluetooth serial connection.

This works as intended for my smartphone, however, when my transmission and receive pins are connected to the board the LCD screen is frozen until the pins are removed. Additionally, I'm not able to update the `desiredTemp` variable through the Bluetooth serial connection.

Attached is my code:

```
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>

LiquidCrystal LCD(10,9,3,2,1,0);
double inIRPin = A0;
double inThermPin = A1;

int LED = 4;
char recvChar;

int increaseTemp = 7;
int decreaseTemp = 6;
int increaseTempState = 0;
int decreaseTempState = 0;

#define RxD         13
#define TxD         12
SoftwareSerial BTSerial(RxD,TxD);

double valIR = 0;
double valTherm = 0;
double val = 0;
double temp = 0;
double const tempRatio = 0.125;
double desiredTemp = 40; //Degrees Celcius

void setup() {
 // put your setup code here, to run once:

 pinMode(increaseTemp,INPUT);
 pinMode(decreaseTemp,INPUT);

pinMode(RxD, INPUT);
pinMode(TxD, OUTPUT);
pinMode(LED, OUTPUT);
setupBlueToothConnection();

pinMode(inIRPin, INPUT);
pinMode(inThermPin, INPUT);
LCD.begin(16,2);
LCD.setCursor(0,0);

}

void loop() {
  // put your main code here, to run repeatedly:
   valIR = analogRead(inIRPin); //IR Sensor Output
  valTherm = analogRead(inThermPin);

   increaseTempState = digitalRead(increaseTemp);
   decreaseTempState = digitalRead(decreaseTemp);

   if(increaseTempState == LOW){
    desiredTemp++;
  }
   if(decreaseTempState == LOW){
     desiredTemp--;
   }
   if(BTSerial.available()){
      recvChar = BTSerial.read();
      Serial.print(recvChar);
      BTSerial.println(desiredTemp);
      if(increaseTempState == LOW){
         desiredTemp++;
         updateLCD();
       }
       if(decreaseTempState == LOW){
         desiredTemp--;
         updateLCD();
       }
       if(recvChar == '1'){
         BTSerial.println("Increasing Temp");
         desiredTemp++;
       }
       if(recvChar == '0'){
         BTSerial.println("Decreasing Temp");
         desiredTemp--;
       }
   }
    updateLCD();
  }

 void setupBlueToothConnection()
 {
    BTSerial.begin(9600);

    BTSerial.print("AT");
    delay(400);

    BTSerial.print("AT+DEFAULT");             // Restore all setup value to
    factory setup
    delay(2000);

    BTSerial.print("AT+NAMESmartCoaster");    // set the bluetooth name
    delay(400);

    BTSerial.print("AT+PIN0000");             // set the pair code to connect
    delay(400);

    BTSerial.print("AT+AUTH1");             //
    delay(400);

    BTSerial.flush();

  }

 void updateLCD(){
      LCD.setCursor(0,0);
      LCD.print("Current Temp:");
      LCD.println(temp);
      LCD.setCursor(0,1);
      LCD.print("Desired Temp:");
      LCD.println(desiredTemp);
      delay(100);
  }

```

# Answer
You connected the LCD module to serial hardware pins 0 (RX) and 1 (TX).

When you receive the data from the Bluetooth module, through the software serial, you send it to the hardware serial.

```
if(BTSerial.available()){
      recvChar = BTSerial.read();
      Serial.print(recvChar);
...

```

This messes up the communication with the LCD module. Remove `Serial.print(recvChar);` and it should work.

---

A more sensible solution would be to use hardware serial for the Bluetooth module and the other pins for the LCD module.

Software serial should only be used, if you really can't use the hardware serial, e.g. you need the hardware serial to communicate with another device (a PC or some other module).
> 3 votes

---
Tags: serial, bluetooth, lcd
---


title: Does the Arduino Uno have two crystals?

text:
# Question
Title: Does the Arduino Uno have two crystals?
Take a look at this picture:

I think most of use agree that the "big silvery" thing on the board (red) is the famous 16 MHz crystal of the Arduino. That's what I've believed until very recently.

I was bored so I looked at my Arduino Uno, and saw that it has what seems like another crystal (yellow). It looks like the one that is on the Pro Mini. It's also located near the XTAL pins. After I inspected the schematic a second time, it also appears that there are two crystals on the board.

Which one out of those two is actually connected to the XTAL pins and why are there two?

# Answer
The **ceramic resonator** in yellow is connected to the main MCU, and the crystal in red is connected to the other MCU. USB requires tighter tolerances than is available from a resonator therefore a crystal must be used instead.
> 14 votes

# Answer
There are 2 that you can see, but there are **internal resonators** in both chips. You can use the ATMega328's one if it's on a breadboard (it's half the frequency tho), and much more temperature-dependent. Just need to give it a fresh bootloader.
> 2 votes

---
Tags: arduino-uno, oscillator-clock
---


title: ESP8266 not working. No response

text:
# Question
Title: ESP8266 not working. No response
Hello. I have begun working with an ESP8266 and an Arduino Uno. The connection I used is shown below, except I am using an Arduino Uno. The rest of the connection is the same.

The code I'm using is:

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

void setup() {
  Serial.begin(9600);
  ESPserial.begin(9600);
  Serial.println("");
  Serial.println("Remember to to set Both NL & CR in the serial monitor.");
  Serial.println("Ready");
  Serial.println("");
}

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

```

But the serial monitor is only printing:

> Remember to to set Both NL & CR in the serial monitor.
>
> Ready

What to do?

# Answer
> 2 votes
ESP8266 WiFi modules typically have a baud-rate of 115200. This not only won't work with a 9600 baud host but SoftwareSerial can't go that fast. Or, more precisely, it can generally push out characters at that speed but it can't keep up with incoming ones. See this answer for how to change the speed of your module to 9600 baud.

Short answer: You have to reconfigure your ESP module to 9600 baud to use it with SoftwareSerial. You can do it blind (transmit a baud-change command to it at 115200 baud, even though you won't be able to read the reply). Once done, it will remain at 9600 baud and successfully communicate in both directions.

# Answer
> 1 votes
ESP01 has two variants (blue PCB and black PCB), the old is configured to use 9600 baud (blue PCB) and the newer one uses 115200 baud (black PCB) as default.

There is also a difference in memory, 512kByte (4Mbit) or 1MB (8Mb) between the old and new version.

So try to change

```
ESPserial.begin(9600);

```

to

```
ESPserial.begin(115200);

```

And preferably both 9600 to 115200.

# Answer
> 0 votes
You need to pull RST high - that is, connect a 10k between +3.3v and the ESP8266-01's RST pin.

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


title: I2C broadcast and reply on Arduino M0+

text:
# Question
Title: I2C broadcast and reply on Arduino M0+
I am trying to set up several ATSAM-based AVR chips in a master/slave broadcasting arrangement. I want the master to be able to send a broadcast message to I2C address 0, and then for slaves to respond with different information. I have seen other implementations where this has been successful since I2C devices will typically self-arbitrate and if they are configured to back-off when arbitration is lost, the master can repeat its request and iterate over all addresses on the bus.

The challenge is that while I have Wire.beginTransmission(0) working to reach my slaves from the master, I cannot get Wire.requestFrom(0,6) to work. The slave acts as though no message had arrived in the reply case. This is in the reduced case of one master and one slave.

In the example below, changing RequestFrom to the slave address will work.

I am aware that on the SAMD architecture, ArduinoCore does not configure the SERCOM for I2C broadcasts so I made a one-line modification as follows to enable it:

```
sercom->I2CS.ADDR.reg = SERCOM_I2CS_ADDR_ADDR( ucAddress & 0x7Ful ) | // 0x7F, select only 7 bits
                      SERCOM_I2CS_ADDR_ADDRMASK( 0x00ul ) |
                      SERCOM_I2CS_ADDR_GENCEN // added by JAG

```

My master code:

```
#include <Wire.h>

void setup() {

  Serial.begin(9600);
  Serial.println("Sketch start" );

  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {

  Serial.print("-- Top of loop:" );
  Serial.println( millis() );

  Wire.beginTransmission(0); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission(true);    // stop transmitting

  // delay( 500 );

  uint8_t recvSize = Wire.requestFrom(0, 6);    // request 6 bytes from slave device #8

  Serial.print( "Got bytes: " );
  Serial.print( recvSize );
  Serial.print( "---> ");

  while (Wire.available()) { // slave may send less than requested
    char c = Wire.read(); // receive a byte as character
    Serial.print( "[") ;
    Serial.print(c);         // print the character
    Serial.print( "]" );
  }
  Serial.println();

  x++;
  delay(500);
}

```

My slave code:

```
#include <Wire.h>

void setup() {
  Wire.begin(9);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent); // register event
  Serial.begin(9600);           // start serial for output
  Serial.println( "Starting up" );
}

void loop() {
  delay(500);
    Serial.print( "In top of loop (slave): " );
    Serial.println(millis() );
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    SerialUSB.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  SerialUSB.println(x);         // print the integer
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Wire.write("hello"); // respond with message of 6 bytes
  // as expected by master
  Serial.println( "<<<< Writing a response." );
}

```

# Answer
If you broadcast data using Wire.send(data), the slaves would receive this in there onReceive handler but as far as I can remember, the I2C slave will not respond on a Wire.requestFrom(...) broadcast from the master.

Imagine x slaves responding all at the same time to the request...
> 1 votes

# Answer
The I2C protocol supports bus arbitration only for masters sending (if more than one master in the bus starts sending at the same time). So, if any slave device would really respond to the General call address 0 with data, the data would geht corrupted if another slave would send data too. With this background it is reasonable, why an I2C slave device wouldn't respond to a request at the General call address.

If you have too many chips in the bus or don't want to address Thema directly due to another reason, you can send a trigger message to the General call address and let the other chips send their data as masters. Keep in mind, that in this case all involved chips must implement correct bus arbitration (and I'm not sure if the Wire library supports this).
> 0 votes

---
Tags: i2c
---


title: Can I support all these sensors?

text:
# Question
Title: Can I support all these sensors?
I'm new to arduino's and am currently working on a project which requires a lot of different sensors. I was just wondering if its possible to use all the following sensors on a single Arduino Uno:

* 2 Separate Load sensors (i.e giving different readings) controlled with an load cell amplifier
* a Gyro Sensor
* an Accelerometer
* and an ESC

If its not possible, could someone please tell me what hardware I would need to run all these sensors together. Thanks :).

# Answer
> 1 votes
Yes, it should work. The HX711 need two pins each (one for clock and one for shifting out the data). The MPU6050 seems to have an I2C interface, which needs two lines (SCL and SDA). And lastly an ESC uses a PWM pin.

All in all this needs 7 pins, way less than an Arduino UNO has.

Note that having enough pins doesn't mean, that you can usw all the sensors at the same time. You might habe to disable one for a short time to do something else.

# Answer
> 0 votes
It really depends on how many pins each sensor uses. The signal pins of all the sensors used would have to be equal to or less than the total number of I/O pins on the arduino, which would be 20. So you can control 20 sensors if they each have one signal pin.

However, to control more sensors (or use a lower pin count on arduino) you can use multiplexing. See Two sensors on one input or MULTIPLEXING WITH ARDUINO AND THE 74HC595.

Theoretically, you can control an infinite number of sensors with the use of multiplexing.

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


# Question
Title: card.init(SPI_FULL_SPEED,SD_CS_PIN) returns false for Arduino Mega
I am working with a music shield, I have got my code from this site https://www.waveshare.com/Music-Shield.htm it works fine with arduino UNO but when I try to use it on MEGA it give me errors, Well I found that the problem is with this line

```
card.init(SPI_FULL_SPEED,SD_CS_PIN)

```

in uno `SD_CS_PIN=10` I tried to change it to `53` based on this map

```
SPI   Uno   Mega
SS   10   53
MOSI   11   51
MISO   12   50
SCK   13   52

```

which is available on https://forum.arduino.cc/index.php?topic=165170.30 but still it returns false. What other options do I have to make it work on `MEGA`?

Thing that I am trying

```
#define SD_CS_PIN=10
#define VS_XRESET A0
#define VS_DREQ   A1
#define VS_XDCS   A2
#define VS_XCS    A3
void VS10XX::init(void)
{
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  pinMode(53, OUTPUT);

  pinMode(VS_XRESET, OUTPUT);
  pinMode(VS_DREQ, INPUT);
  pinMode(VS_XDCS, OUTPUT);
  pinMode(VS_XCS, OUTPUT);
  digitalWrite(VS_XDCS, HIGH);
  digitalWrite(VS_XCS, HIGH);

  reset();
}

```

In setup I added used this code but still does not work

```
void setup()
{
  Serial.begin(115200);
  pinMode(53, OUTPUT);//setting pin 53 to input
  player.begin();
}

```

the error code when I attempt to `init` sd card is `0` which says

```
/** timeout error for command CMD0 */

```

# Answer
53 is a SS pin if the Mega is SPI slave. Pin 10 is connected to shield to select it as a listening slave. So let the parameter set to pin 10. Additionally on Mega set pin 53 to output, otherwise the Mega can 'fall' into SPI slave mode.

SPI pins 50, 51 and 52 are connected to the ICSP header too. The 6 pin ICSP header is on the same place relative to Uno an Mega common pin headers.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: how can I break from this case by IRremote even if it's not finished yet?
I want to give a pause to case 0xFF02FD or at least to break from that case by entering the case 0xFFA25D even if the 1st case not finished, when I press power button wich has hexa code ( 0xFFA25D) I turn On the led and when I press playButton(0xFFA25D ) I turn on the piezoo and turn off the led (as you can see in my code) but I can't get out from that case by pressing powerButton again I should wait till it ends .

```
void loop() {
  if (irrecv.decode(&results)) {
    // If it's been at least 1/4 second since the last
    // IR received, toggle the relay
    Serial.println(results.value,HEX);
    irrecv.resume();
  }

  switch(results.value){
    case 0xFFA25D:
      digitalWrite(redPin,HIGH);
      break;

    case 0xFF02FD:
      digitalWrite(redPin,LOW);
      firstSection();

      //Play second section
      secondSection();

      //Variant 1
      beep(f, 250);
      beep(gS, 500);
      beep(f, 350);
      beep(a, 125);
      beep(cH, 500);
      beep(a, 375);
      beep(cH, 125);
      beep(eH, 650);

      delay(500);

      //Repeat second section
      secondSection();

      //Variant 2
      beep(f, 250);
      beep(gS, 500);
      beep(f, 375);
      beep(cH, 125);
      beep(a, 500);
      beep(f, 375);
      beep(cH, 125);
      beep(a, 650);
      delay(500);
      break;
  }
}

```

# Answer
> 0 votes
You are not asking to simply exit a switch-case statement, but to react to your IR remote button press during the execution of other code. With a normal push button directly connected to the Arduino you would normally do this through an interrupt routine. Maybe the library, that you are using, supports decoding IR signals trough interrupts.

If not, you have one more option: From your code it seems, that the IR receiving part is non-blocking. This means, that it only executes, if there is really something to receive, else it would let the program execute the rest of the code, not blocking the execution. Then you have to program your piezo code (the code in the `case 0xFF02FD:`) as non-blocking code (maybe using PWM hardware or timer interrupts to output the right frequency and just setting trigger variables in your switch-case statement).

When the piezo code is non-blocking, the decode function of the IR library is executed also during your beep sequence, so your program can react to the results of it.

# Answer
> 0 votes
Because you only check `if (irrecv.decode(&results))` at the top of `loop()`, that is the only point in your code that you can change your action based on a new IR input.

While not an ideal solution, you could just insert `if (irrecv.decode(&results)) {return;}`in between all `beep()` calls.

```
//Variant 1
beep(f, 250);
if (irrecv.decode(&results)) {return;}
beep(gS, 500);
if (irrecv.decode(&results)) {return;}
beep(f, 350);
if (irrecv.decode(&results)) {return;}

```

and so on.

A better solution would be to avoid re-typing the same code by using loops and functions. You call `beep()` repeatedly with only the note and duration changing. You could put your sequence of notes and durations in an array and writing a new function that calls `beep()` for one element in the array and then increments a pointer to the next note to play. Your `loop()` calls this function and checks to see if there is any IR code ready also.

An even better solution would be to set up a hardware timer to produce regular interrupts and the ISR would check if there is IR data ready and set a global flag that is checked in the program.

---
Tags: ir, atmega2560, piezo
---


title: I2C Interrupting Loop?

text:
# Question
Title: I2C Interrupting Loop?
Imagine i have a code, that loops, and at one point there is i2c request.

Is loop() paused right away when there is Wire.onReceive() or loop is finished then Wire.onReceive() is called?

# Answer
The onReceive callback is called from an interrupt service routine (ISR). As the name says, interrupts are "interrupting" the currently executing code almost immediately. And "almost immediately" means that it only will take a few clock cycles. (This is the reason why changing data in an ISR can corrupt data, since the ISR may change a variable, when the main code tries to read it)

So the Arduino will not wait for the `loop()` function to end. It will interrupt in the line, where it was when the interrupt occured, and return to it after the ISR returns.
> 2 votes

---
Tags: i2c, interrupt
---


# Question
Title: What is the minimum wattage of resistors for breadboarding with Arduino Uno?
I'd like to buy new resistors for breadboarding with my Arduino Uno. There are 0.25W, 0.4W, 0.6W, 1W, 2W, 3W, 5W, 10W resistors in the shop. What is the most suitable for this operation?

# Answer
> 5 votes
The answer is: It depends what you want to use them for.

You need a wattage that is higher than the power it will dissipate. What that power is depends on what you are doing with them. There are standard formulae that tell you the power in any given situation.

For instance, if you know the current and the resistance you can use: P=I²×R. If you know the voltage across the resistor it's P=V²÷R.

Take as an example the common resistor for an LED. Assume a 2V LED and a 220 ohm resistor. With a 5V total voltage the voltage across the resistor would be 5-2=3V. So the power would be (3²)/220 = 9/220 = 0.041W so you could quite happily use a 0.125w (⅛w) resistor for that job.

To be honest though most common Arduino jobs can be accommodated by ⅛W or ¼W resistors. ¼W is better for breadboarding since the leads are fatter than ⅛W, but ⅛W can take two leads at once direct into an Arduino's headers. Also if you fold the leads in half and squash them with pliers they fit better.

# Answer
> 2 votes
Go with 1/4 Watt resistors but be prepared to use 1/2 Watts if the leads don't press down cleanly into the breadboard which is what I think you are asking about. If you need anything in the higher wattage range and you are working with an Arduino, then you are doing it wrong. An Arduino could not smoke a 1/4 watt if it tried.

I have fought for years with our purchasing agent over this at the college I work for. He buys 1/8th watt resistor in bulk, but fails to heed the advice that you cannot use these on standard classroom breadboard without bending the leads at best and failing to even make a good connection at worst. You need reliable connections and 1/8th and smaller are useless on breadboards. Just my two cents from years and years of experience.

# Answer
> 0 votes
The smaller the better for the most part. On 1/4 or 1/8 W resistors the leads size is small enough to work well in bread boards. Rarely do you need to dissipate large amounts of power so 1/8 is a good size for logic, maybe 1/4-1/2 for power supply areas. See Majenko's answer for the heavy math, mostly applicable in power supply areas as he points out.

---
Tags: arduino-uno, resistor
---


# Question
Title: How to measure voltage with Arduino analog input
I'm totally new to Arduino and to electrodynamics in general.

I'm wondering what happens if I connect my digital pin to an analog input on Arduino, and make digitalWrite and analogRead on the according pins. Here are the options I can think about:

* Just connect them directly - *it is not a short circuit, is it?*
* Connect a resistor in between - *the voltage should still be 5v, right? Whatever resistor I use?*
* Make a circuit: digital output -\> resistor -\> ground, and connect the analog input in parallel (in between the resistor and ground) - *Does it make sense? What is the difference with the previous option?*

As you see, I'm really confused now. I would highly appreciate if someone could explain in detail what is happening in all the cases, with corresponding values for the *current*, *voltage* and *resistance*.

# Answer
You can connect digital pin to analog input directly. That's not very interesting though, since you'll only see two values from the analog input (at least theoretically).

The digital pin gives out 0 or 5 Volts. The analog pin expects 0 to 5 Volts input. The only thing that matters to the analog input is the *voltage* with respect to ground. That can be between 0 to 5 volts (returned as 0...1023 by `analogRead` function).

> Just connect them directly - it is not a short circuit, is it?

No, it's not a short circuit. In general, connecting *anything* to an input is not a short circuit. Connecting output to another output is potentially a short circuit.

> Connect a resistor in between - the voltage should still be 5v, right? Whatever resistor I use?

This makes no difference compared to connecting them directly, unless the resistor value is very high (should be hundreds of kOhms or even MOhms to see a difference, I suppose), because almost no current flows to the input.

> Make a circuit: digital output -\> resistor -\> ground, and connect the analog input in parallel (in between the resistor and ground) - Does it make sense? What is the difference with the previous option?

This makes no other difference than that the resistor loads, i.e. draws current from, the digital output. If the resistor value is too small, then the digital output is unable to supply enough current so the 5 V voltage could become less than 5 V, or you could even burn the chip.
> 3 votes

# Answer
If you have a 250 ohm resistor from the digital pin to Gnd, and connect the digital pin to an analog input pin, then 20mA will flow thru the resistor to Gnd (5V/250 ohm = 20mA), while almost nothing flows into the analog input, as the max input current is 1uA per the datasheet, implying the input acts like a large resistor to Gnd: High input of 5V/.000001A = 5Meg-ohm.

I say acts because the input pin is the gate of a MOSFET, and a diode protection clamp to +5 and another to Gnd to limit the input voltage to -0.5 and Vcc+0.5V (so 5.5V with Vcc = 5V).

The diode clamps are only good for ~1mA (not shown in the data sheet, but discussed in an application note on detecting AC zero crossing), exceed that and you risk blowing the diode and/or the input pin and/or the chip (which will then feel warm or hot to the touch when it is powered up).

That's why you don't apply signals to unpowered chips - to prevent damaging the diode clamp circuits.
> -1 votes

---
Tags: arduino-uno, electricity
---


# Question
Title: How to detect an read buttons pressure on touchscreen
I made simple 3 red buttons like this:

```
#include <SPI.h>

#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include "URTouch.h"

#define TFT_DC 9
#define TFT_CS 10
#define TFT_RST 8
#define TFT_MOSI 11
#define TFT_CLK 13
#define TFT_IRQ  7

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK,

#define t_SCK 3
#define t_CS 4
#define t_MOSI 5
#define t_MISO 6
#define t_IRQ 7

URTouch ts(t_SCK, t_CS, t_MOSI, t_MISO, t_IRQ);

void setup() {

  tft.begin();
  tft.fillScreen(BLACK);

  tft.fillRoundRect (12,15,30,80,5,RED);//50,100,30,80,5,RED
  tft.fillRoundRect (50,15,30,80,5,RED);
  tft.fillRoundRect (88,15,30,80,5,RED);

  delay(500);
}

```

And this the part where I need help:

```
void loop()
{
  int x, y;

  while(ts.dataAvailable())
  {
    ts.read();                //-----------> this is the whole thing
    x = ts.getX();
    y = ts.getY();

  }

```

What I need is, to know how to detect and read the pressure of the button area, so that I can run different tasks.

# Answer
> 2 votes
The `fillRoundRect` function format is `(initial_Xpoint,initial_Ypoint,length,width,corner_radius,color)`

Therefore, you already have the information about the location of the button itself. Next, check if the `x` and `y` value is within the button area.

```
void setup() {

  tft.begin();
  tft.fillScreen(BLACK);

  tft.fillRoundRect (12,15,30,80,5,RED);  //button1
  tft.fillRoundRect (50,15,30,80,5,RED);  //button2
  tft.fillRoundRect (88,15,30,80,5,RED);  //button3

  delay(500);
}

void loop()
{
  int x, y, pressedbutton=0;

  if(ts.dataAvailable())
  {
    ts.read();                //-----------> this is the whole thing
    x = ts.getX();
    y = ts.getY();

    if ((x>=12) && (x<=12+30) && (y>=15) && (y<=15+80)) pressedbutton = 1; else
    if ((x>=50) && (x<=50+30) && (y>=15) && (y<=15+80)) pressedbutton = 2; else
    if ((x>=88) && (x<=88+30) && (y>=15) && (y<=15+80)) pressedbutton = 3;
  }

  ...
  ...
  ...
 }

```

# Answer
> 0 votes
I'm not 100% sure what you ask, but I assume you want to perform a task depending on what button has been pressed.

You can do this by checking x and y, e.g.

```
switch (x)
{
case 0:
   switch (y)
   {
   case 0: // Button (0,0) is pressed)
      perform_task_A();
      break;
   case 1:
      perform_task_B();
      break;
   ... // etc.
   }
   break;
case 1:
   switch(x)
       // Etc. as above but use different tasks.

```

Than create for each task a function

```
void perform_task_A()
{
   // Do your code
}

```

If you want to change 'functionality' depending on a button press, e.g. assume perform\_task\_A should read a digit, than create a new switch statement there to read a digit key.

If you want more complicated menu structures/input entering, check into state diagrams to keep track where you are in the UI-flow and act on the current state AND the pressed button.

---
Tags: arduino-uno, lcd, adafruit, tft
---


title: Change the baud rate of HC-05

text:
# Question
Title: Change the baud rate of HC-05
```
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);
  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);
  // HC-05 default speed in AT command more
}

void loop() {
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

```

I have tried this code but I am not able to change the baud rate. Please suggest me a solution.

# Answer
> 2 votes
I played a lot with HC-05 and HC-06 until I understand the way they work. Now i've big Android App communicating with HC at 115200 bauds and sending and receving heavy data.

I hope these tips will help you and other guys and save you time:

1) the way the HC-05 and HC-06 detect end of AT command is different:

HC-05 (can be slave and master): each AT command must end by CRLF. So or you add CRLF in your Android code or you select the option "CRLF line ending" in your console.

HC-06 (only slave): need a "time" between AT Command. According to the data sheet if there is more than 1 sec, the HC consider this is the end. Even if your question is about the HC-05 I think it can be VERY interesting to understand the big problem which can happened with the "delay" between AT. If you use a communication at 9600 bauds and type AT commands on serial monitor and echo both what HC reply and what you send, you will have such things: type AT+VERSION and see on serial monitor AT+OVKERSION Why ? Because as the delay between each char is long, as soon as the HC had receive "AT" he thinks that's the command and start to reply "OK". So with a HC-06 you must send the AT command in one "shoot" and then add a delay of 2 sec to be sure.

2) Problem of settings. The HC save the speed you set as the name and the pin code. So trying to set the pin, name and speed in the setup funcion is not usefull as at each time the Arduino will reset, each time you'll try to set the data. Also, factory setting of HC seems to be 9600 bauds. So you have to create a small sketch, which you'll use only ONE time to set the HC. Like this:

```
Serial.begin(9600);
delay(2000);

// AT+NAMEXXX where XXX is the new name
Serial.print("AT+NAMEJOHNDOO");
delay(2000);

// AT+PINXXXX where XXXX new code (4 number)
Serial.print("AT+PIN1999");
delay(2000);

// AT+BAUDX where X from 1 to 8
// 1 -> 1200 Bauds
// 2 -> 2400 Bauds
// 3 -> 4800 Bauds
// 4 -> 9600 Bauds
// 5 -> 19200 Bauds
// 6 -> 38400 Bauds
// 7 -> 57600 Bauds
// 8 -> 115200 Bauds
Serial.print("AT+BAUD8");

```

This for HC-06. For HC-05 you must add CRLF and you don't need the delay.

Important: as, at the end of this sketch, the HC is now at 115200 bauds, you must havea serial.begin(115200) for comunicating with it. If you run this sketch two time, the second run will do nothing as the Arduino will try to comunicate at 9600 bauds with a HC listening at 115200.

3) Problem of speed. On the Arduino, you can use the software serial lib only if you plan to send and receive at up to 19200 bauds. Some say it work at 38400 but I've had problems at this speed. The best way it to avoid Software serial and use directly the basic RX and TX of the Arduino. Using that you can run at 115200 without any problem.

Even if this answer is a bit "outside the question" I hope this will help you working with the HC.

# Answer
> 0 votes
**HC-05+Arduino+Android**

The problem is the baud rate of devices. The default baud rate of HC-05 is 38400. First of all set baud rate of HC-05 by using the AT commands (i.e. AT+UART=9600,0,0) to 9600. This baud rate will work with serial in Arduino as well as in android Bluetooth libraries/app without any problem.

---
Tags: arduino-uno, programming, code-review, android
---


# Question
Title: cannot resolve overloaded function... error
I started to learn Arduino and I want to get an input from user to blink LEDs. I wrote under the void loop() section input codes. After i compiled it and Arduino IDE gave me this: "Arduino:1.8.5 (Windows 10), Kart:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

```
C:\Users\Yunus Emre ERYILMAZ\Documents\Arduino\sketch_feb17a\sketch_feb19a\sketch_feb19a.ino: In function 'void loop()':

sketch_feb19a:27: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

 numBlueBlink=Serial.parseInt;

             ^

sketch_feb19a:31: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

 numYellowBlink=Serial.parseInt;

               ^

exit status 1
cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

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

```

What should i do, how can solve this problem? Thanks.

The code that i wrote:

```
int blueLEDPin=9;  // Declaring blue led's pin is 9.
int yellowLEDPin=10;  //Decllaring yellow led's pin is 10.
int blueOnTime=250;  // Bue led ontime
int blueOffTime=250; // Blue led offtime
int yellowOnTime=250; // Yellow led ontime
int yellowOffTime=250; // Yellow led offtime
int numBlueBlink=0;
int numYellowBlink=5;
String blueMessage="The blue LED is blinking...";
String yellowMessage="The yellow LED is blinking...";

void setup() {
  String wm1 = "Welcome to";
  String wm2 = " My Program";
  String wm3;
  wm3 = wm1+wm2;
  Serial.begin(115200);
  Serial.println (wm3);
  pinMode (blueLEDPin,OUTPUT);
  pinMode (yellowLEDPin, OUTPUT);

}

void loop() {
Serial.println ("How many times do you want the blue LED to blink? ");
while (Serial.available()==0){ }
numBlueBlink=Serial.parseInt;

Serial.println ("How many times do you want the yellow LED to blink? ");
while (Serial.available()==0){ }
numYellowBlink=Serial.parseInt;

Serial.println (blueMessage);
for (int j=1; j<=numBlueBlink; j=j+1) {
  Serial.print ("   You are on Blink #: ");
  Serial.println(j);
  digitalWrite (blueLEDPin,HIGH);  // Turn first led on
  delay (blueOnTime);  // Wait
  digitalWrite (blueLEDPin,LOW); // Turn first led off
  delay (blueOffTime); // Wait
}

Serial.println (" ");

Serial.println (yellowMessage);
for (int k=1; k<=numYellowBlink; k=k+1){
  Serial.print ("   You are on Blink #: ");
  Serial.println (k);
  digitalWrite (yellowLEDPin,HIGH); // Turn second led on
  delay (yellowOnTime); // Wait
  digitalWrite (yellowLEDPin,LOW);  // Turn second led off
  delay (yellowOffTime);  // Wait
}
Serial.println (" ");
}

```

# Answer
The function parseInt is a function and you have to add parameters with ( and ), even when it has no parameters, thus instead of

```
 numBlueBlink = Serial.parseInt;

```

you have to write

```
 numBlueBlink = Serial.parseInt();

```

See Serial.parseInt for a reference.
> 3 votes

---
Tags: arduino-mega
---


# Question
Title: Why would the resistor be after the LED in this project?
This is project 2 of their official arduino projects book called "Spaceship interface". I understand resistors normally reduce voltage so the LEDs don't burnout but here 5v is coming from either digital 3, 4, or 5 and it seems like it goes right into the LED before going through a resistor as it goes back to ground. This makes no sense to me.

# Answer
It does not matter if a resistor is before or after a component, see the circuits below.

The resistor reduces the current, and this is true for the path where the resistor is in (until the interconnections before/after the resistor). In the examples there is only one path.

simulate this circuit – Schematic created using CircuitLab
> 8 votes

# Answer
It doesn't matter where the resistor is located (before and after are meaningless concepts). What is important is that the resistor is in **series** with the LED.

This produces an approximation to a constant current source (I = V/R). The actual current is lower due to the voltage drop across the LED, so is actually I = (V- VLED)/R. VLED varies; red LED is lower ~1.2V blue significantly higher.

The resistor serves 2 functions; to limit the current from the Arduino and to limit the current through the LED (either to limit brightness or protect the LED)
> 3 votes

# Answer
The resistor is to limit the *current flow* through the LED. A LED *will* burn itself out if given too much current and the maximum Arduino output current is 40 mA per leg (output). A quick calculation of V=I\*R where V is 5 Volts, I = 40 mA leaves R = 5/.04 or 125 Ohms. You don't want to pull that much current from the Arduino so using 220 resistors is a safe bet at 22mA current draw per leg.

That 10K resistor keeps pin #2 at the ground potential until the button is pushed. Then the input to pin #2 is 5 Volts.

FWIW - that is an ugly drawing.
> 1 votes

# Answer
Most single or RGB LEDs can't take more than 20mA without risking overheating/burning up. Modern LEDs need as little as 5mA to be really bright. I use 1K resistors on boards where the LED is being used as an indicator (like Power, or Rx or Tx active, or for the L (SCK activity) LED. Sometimes 2.2K when 1K seems too bright still. Depends on the LED. Test first before soldering thinks up.

To calculate a resistor value for a desired current, use Ohms Law, V=IR, Voltage = current x resistance. Rearranged, Voltage/current = resistance.

If you know the Voltage, Vf, of the LED when it is on, and you are driving from an Arduino pin that outputs 5V, then: (5V - Vf)/current = resistor. With 5mA and say a Vf of 2.5V: (5V - 2.5)/.005A = 500 ohm.

You can determine Vf of an LED by using a 5V source and a 1K resistor. Connect the LED and resistor in series between 5V and Gnd. Measure the voltage across the LED, that is Vf. 5V - Vf = voltage across the resistor, Vr. 5V = Vf + Vr.

If you know the voltage across the resistor, Vr, you can calculate current flow: Vr/resistor ohms = current Amps. Say you measured Vr of 2.7V and used a 1K resistor. Then current = 2.7V/1000ohm = .0027A, or 2.7mA.
> 1 votes

---
Tags: arduino-uno, electronics
---


# Question
Title: Is it possible to upload a file with GPS values onto my arduino?
I am absolutely new at arduino but ok with writing code. I am trying to upload 20 points of interest lat/long as a static file that sits on my arduino. Then I want to use my GPS sensor and a function which uses the haversine formula to constantly measure distance between all 20 points and the GPS data from the arduino and output the distance to the nearest point on an LCD screen.

I cannot figure out how to store and reference that list of GPS points of interest.

# Answer
The Arduino does not have a file system per-se, to which you could upload files, unless you create the code that does that. There is "EEPROM" space on the Arduino processor that can hold 1024 bytes of data and survives power-cycles. That should be sufficient to hold 20 lon/lat pairs of sufficient precision.

As for how to get the waypoint data onto the Arduino, you could transfer them over the serial port from your computer, either by manual entry from your computer over the serial monitor of the Arduino IDE or by writing a script in Python or some other language to read the waypoint file and transmit the data according to the protocol you invented.

There are are also SD Card peripherals you can add to an Arduino, so you could potentially just load the waypoint file onto the SD Card from your computer, and then insert the card into the SD Card reader on the Arduino and have it read the data from there.
> 1 votes

---
Tags: arduino-uno, gps
---


# Question
Title: Can I use this power supply with my Arduino?
I am new to Arduino and electronics in general.

I am working on a project where I would ultimately like to power the project from 220V AC (Wall light switch) (I want to replace the light switch with one of my own design).

I will want to feed power to the arduino directly from the 220V connecting wires in the light switch cavity.

This power source is 5V (I know the Arduino needs 9-12V), but I will use a USB connector, wired onto my AC/DC power source, to power the Arduino.

Power Source

**Ratings:**

```
AC85 - 264V or  DC110 - 370V wide voltage input
DC 5V(+/ -0.2V) 600mA isolated output
Input Current: 0.0273A/115VAC  0.014A/230VAC
Input surge current: 20A (230VAC)
Frequency range: 50/60 Hz
Operating Temperature: -30 - 70 ℃
Relative humidity: 20%- 90%
Rated power: 3W
Output efficiency: 80%

```

I don't really know why yet (this is part of figuring that out), but I have the feeling that the arduino would want a linear power source, rather than a switching power source. (Because linear is cleaner power?)

Regardless, I am asking the question as if this power source will do the job, and if not, why not? (Why not a switching PSU) ?

# Answer
> 1 votes
Yes, that power supply is ideal for powering an Arduino (an Arduino doesn't care if it's linear or switching, and a linear regulator that goes from 220V to 5V is called a *furnace*, and you don't want one of those...)

**HOWEVER** unless you have a very strange wiring setup in your house, under normal circumstances *there is no 220V supply in the switch*. You normally have *live in*, *switched live out* and ***NO*** neutral connection.

That means you don't have the connections you need to wire your power supply up to.

By the way: *if you didn't already know that then you are not qualified to mess around with home wiring and you should leave it to the professionals.*

---
Tags: power
---


# Question
Title: Doubt with the library esp8266wifi and Station Mode
I have been working for a while with the **ESP8266** I have a question:

According to the online documentation of GitHub from the esp8266wifi library I can initialize the WiFi in *Station* mode to (obviously) connect to a nearby AP, I can initialize the station mode in 3 "different ways":

* `WiFi.begin ()`: The module initializes the *Station* mode and connects to the last network that is connected, because the credentials (SSID and Password) are stored in its internal memory (flash?).
* `WiFi.begin (ssid, password)`: The module initializes the *Station* mode and connects to the network with "ssid" and "password".
* `WiFi.begin (ssid, password, channel, bssid, connect)`: The same as the previous one, only that you pass more parameters: the one that interests me is the bssid, which is the **MAC address** of the AP to which I am going to connect.

Now comes the question: if I wanted to use the *last* mode, because I want to make sure that the **ESP** connects **ONLY** to an AP (a kind of MAC filtering), I also have to specify the channel and set the connect parameter? Or I can simply use something like this:

```
WiFi.begin ("MyOwnNetwork", "123456789", "00: 1B: 44: 11: 3A: B7")

```

I can not prove it right now, I do not have the module in my hands.

# Answer
This is the function prototype:

Per C++ rules, in order to supply an argument for `bssid`, you have to pass an argument for `channel` as well, but `connect` is optional since it's positioned after your target argument. This should not be a problem though since you can just pass the default value of `channel` (i.e. 0) into the function; the `channel` argument is only relevant if you enter a value between 1 and 13 inclusive.

So your call should basically look like:

```
char ssid[] = "ssid";
char pwd[] = "pwd";
uint8_t bssid[] = {0x00, 0x1b, 0x44, 0x11, 0x3a, 0xb7};
WiFi.begin(ssid, pwd, 0, bssid);

```
> 0 votes

---
Tags: esp8266, wifi
---


title: what is welding plate?

text:
# Question
Title: what is welding plate?
I was looking at arduino nano boards here. Description says the arduino board is without welding plate. What does it mean for the user? If I buy this product will there be any issue? I understand that this board does not come with two headers soldered and I am OK with that.

# Answer
> 3 votes
Probably a mistranslation of soldering. As far as I can tell, it just means that the headers are not soldered on.

(see https://www.aliexpress.com/store/product/Nano-V3-0-ATMEGA328P-improved-welding-plate-without-wiring-module-board/630494\_32807228948.html for one with "welding plate")

---
Tags: arduino-nano
---


# Question
Title: LoRa stops working after several hours. Arduino reset button ineffective
I am designing a master-slave LoRa link between two Arduino Pro Minis. The goal is to control a car heater a few hundred meters from my home. The master sends a command to the slave as needed. The slave acknowledges the command.

If no ACK is received in 5 sec the command is resent. In addition to this the master queries the slave every minute to verify the link.

This library is used to control the DRF1278F

I presume that a receive callback or a call to LoRa.parsePacket() returns either nothing or a complete packet, so I do not ever have to handle partial packets.

Chinese Arduino Pro Mini 3.3V 8MHz boards are used.
I am using a module DRF1278F module which contains an RFIC SX1278

Connections

```
Arduino --> LoRa module
----------------------------------
  SS 10 --> NSEL 10k pullup to Vcc
 SCK 13 --> SCK
MISO 12 --> SDO 100k pulldown to GND
MOSI 11 --> SDI
 INT  3 --> IO0
 RST  6 --> RST

```

The device is built on a piece of PCB acting as a ground plane, all GND connections are done to this plane.
It is constructed with short direct wiring.  **Problem.**

After several hours of operation either the master or the slave sort of hangs up. No radio operations any more. There is activity on the SPI but very different to normal operation. I have tested for weeks and not yet survived for one night.

Pushing the reset button does not restore operations. Removing 3.3V power always restore normal operation, even a very brief short circuit of 3.3V. There is no need to rest in power down, so probably not an overheat issue.

It can be either the master or the slave end that hangs up. Power cycling only the hung up unit will restore communications. My simple protocol will then resyncronize itself and continue running.

The arduino watch dog timer is activated, however it does not trigger when the hangup occurs as the arduino program loop still runs.

**Things tested.**

The 3.3 V supply has less than 50mV p-p ripple as checked with an oscilloscope set to infinite persistence for 8 hours, while a hangup occurred.

The interface can be run either polled or interrupt driven, no difference. No String objects are used.

Using different Vcc like 3.0V and 3.6V makes no difference.
Extra Vcc decoupling made no improvement.
Lowering SPI speed from 8MHz to 4MHz made no difference.
Removed Arduino LED on pin 13.

My problem symptoms are similar to this old question

What can I do to resolve this issue?

Slave code:

```
/*
Relay controller, remote end of link
*/
#include <SPI.h>
#include <LoRa.h>
#include <avr/wdt.h>

//#define TTT

#define csPin 10
#define resetPin 6
#define irqPin 3         // must be a hardware interrupt pin
#define myLED 8
#define GNDRET 7
#define powerPin 9

unsigned long LEDtime;
const unsigned long LEDonTime = 500;

char outgoing[40];
byte msgCount = 0;
unsigned long lastLoopTime = 0;
unsigned long heaterStarted = 0l;
const unsigned long heaterTime = 60 * 60 * 1000L; // One hour in ms
unsigned interval = 2000;
int temp = 2310;
byte localAddress = 0x11, destination = 0xAA;
unsigned long ttt;

volatile char incoming[40];
volatile int recipient;
volatile byte sender, incomingMsgId,
incomingLength, gotMsg, ovrn;

void setup()
{
    Serial.begin(9600);
    while (!Serial);
    pinMode(myLED, OUTPUT);
    digitalWrite(myLED, LOW);
    pinMode(GNDRET, OUTPUT);
    digitalWrite(GNDRET, LOW);
    pinMode(powerPin, OUTPUT);
    digitalWrite(powerPin, LOW);

    Serial.println("LoRa Switch 0.1");

    LoRa.setPins(csPin, resetPin, irqPin);
/*
    LoRa.setTxPower(10);
    LoRa.setSpreadingFactor(12);
    LoRa.setCodingRate4(8);
    LoRa.setSPIFrequency(4E6);
    LoRa.enableCrc();
*/
    wdt_enable(WDTO_1S);

    if (!LoRa.begin(433E6))
    {
        Serial.println("LoRa init failed. Check your connections.");
        {
            // blinking in panic
            LEDtime = millis();
            while (millis() - LEDtime < 75)
            {
                digitalWrite(myLED, HIGH);
            }
            while (millis() - LEDtime < 150)
            {
                digitalWrite(myLED, LOW);
            }
        }
    }

    LoRa.onReceive(onReceive);  // Assign callback
    LoRa.receive();
    Serial.println("LoRa init succeeded.");
}

void loop()
{
    if (millis() - lastLoopTime > 1000)
    {
        // Once per second loop
        lastLoopTime = millis();
    }

//  onReceive(LoRa.parsePacket()); // Polling

    if (gotMsg)  // Flag from CallBack routine
    {
        digitalWrite(myLED, HIGH);
        LEDtime = millis();

#ifdef TTT
        Serial.print("Received from: 0x");
        Serial.println(sender, HEX);
        Serial.print("Sent to: 0x");
        Serial.println(recipient, HEX);
        Serial.print("Message ID: ");
        Serial.println(incomingMsgId);
        Serial.print("Message length: ");
        Serial.println(incomingLength);
        Serial.print("Message: <<");
        for (int i = 0; incoming[i] != 0; i++)
            Serial.write(incoming[i]);
        Serial.println(">>");
        Serial.print("RSSI: ");
        Serial.println(LoRa.packetRssi());
        Serial.print("Snr: ");
        Serial.println(LoRa.packetSnr());
        Serial.println();
#endif
        // Command processing
        if (incomingLength == 4)
        {
            // Start heater, it will either timeout or be stopped by a message
            if ((byte)incoming[0] == 0x55 && (byte)incoming[1] == 0xAA)
            {
                Serial.println("Set on");
                digitalWrite(powerPin, HIGH);
                heaterStarted = millis();
            }

            if ((byte)incoming[0] == 0xCC && (byte)incoming[1] == 0x99) // Stop heater
            {
                Serial.println("Set off");
                digitalWrite(powerPin, LOW);
                heaterStarted = 0L;
            }
            // Build ack answer

            if (heaterStarted > 0L)
            {
                // Compute session time in minutes
                ttt = millis() - heaterStarted;
                ttt /= (1000L * 60L); // minutes since start
            }
            else
                ttt = 0L;
            outgoing[0] = (heaterStarted > 0L) ? 'T' : 'F'; // Heater state
            snprintf(outgoing + 1, 30, "%3lu", ttt);

            incoming[0] = 0; // We are done, clear flags
            gotMsg = 0;

            sendAck(outgoing);
        }
        LoRa.receive();

    }

    if (LEDtime) // LED timeout
    {
        if (millis() - LEDtime > LEDonTime)
        {
            digitalWrite(myLED, LOW);
            LEDtime = 0;
        }
    }

    if (heaterStarted) // Heater timeout
    {
        if (millis() - heaterStarted > heaterTime)
        {
            digitalWrite(powerPin, LOW);
            heaterStarted = 0L;
        }
    }
    wdt_reset();
    // END of loop
}

void sendMessage(char *outgoing)
{
    LoRa.beginPacket();                   // start packet
    LoRa.write(destination);              // add destination address
    LoRa.write(localAddress);             // add sender address
    LoRa.write(msgCount++);                 // add message ID
    LoRa.write(bsize(outgoing));        // add payload length
    LoRa.print(outgoing);                 // add payload
    LoRa.endPacket();                     // finish packet and send it
}

void sendAck(char *outgoing)
{
    Serial.println("Send ACK");
    LoRa.beginPacket();
    LoRa.write(destination);
    LoRa.write(localAddress);
    LoRa.write(incomingMsgId);            // report ID
    LoRa.write(bsize(outgoing));        // add payload length
    LoRa.print(outgoing);                 // add payload
    LoRa.endPacket();
}

byte bsize(char *ooo)
{
    byte i = 0;
    while (ooo[i++]);
    return i - 1;
}

byte bsize(volatile char *oo)
{
    return bsize((volatile char *)oo);
}

byte insptr;
void onReceive(int packetSize) // has to be a non blocking function
{
    if (packetSize == 0) return;     // if there's no packet, return
    if (gotMsg) ovrn = true; // gotMsg should be reset by consumer by now

    // read packet header bytes:
    recipient = LoRa.read();         // recipient address
    sender = LoRa.read();            // sender address
    incomingMsgId = LoRa.read();     // incoming msg ID
    incomingLength = LoRa.read();    // incoming msg length

    insptr = 0;

    while (LoRa.available())
    {
        if (insptr < 38)
            incoming[insptr++] = (char)LoRa.read();
        else
            LoRa.read();  // Flush
    }
    incoming[insptr] = 0;  // End of C string
    gotMsg = true;

}

/*
void setTxPower(int level, int outputPin = PA_OUTPUT_PA_BOOST_PIN);
void setFrequency(long frequency);
void setSpreadingFactor(int sf);
void setSignalBandwidth(long sbw);
void setCodingRate4(int denominator);
void setPreambleLength(long length);
void setSyncWord(int sw);
void enableCrc();
void disableCrc();
*/

```

Master code:

```
/*
Relay controller, Controller and GUI base
*/
#include <SPI.h>
#include <LoRa.h>
#include <avr/wdt.h>

#define TTT

#define csPin  10
#define resetPin 6
#define irqPin 3         // must be a hardware interrupt pin
#define ackLED 9
#define LEDGND 8
#define remoteLED 7

unsigned long LEDtime;
const unsigned long LEDonTime = 500;

char outgoing[40];
byte msgSequ = 0, mincnt, ack_TO;
unsigned long lastLoopTime = 0;
unsigned interval = 2000;
byte localAddress = 0xAA, destination = 0x11;
unsigned long ttt;

volatile char incoming[40];
volatile int recipient;
volatile byte sender, incomingMsgId, incomingLength, isACKed, gotMsg, ovrn;

char cc;

void setup()
{
    Serial.begin(9600);
    while (!Serial);
    pinMode(ackLED, OUTPUT);
    digitalWrite(ackLED, LOW);
    pinMode(remoteLED, OUTPUT);
    digitalWrite(remoteLED, LOW);
    pinMode(LEDGND, OUTPUT);
    digitalWrite(LEDGND, LOW);
    isACKed = 1;
    Serial.println("LoRa Master 0.1");

    LoRa.setPins(csPin, resetPin, irqPin);
/* no specials
    LoRa.setTxPower(10);
    LoRa.setSPIFrequency(4E6);
    LoRa.setSpreadingFactor(12);
    LoRa.setCodingRate4(8);
    LoRa.enableCrc();
*/
    wdt_enable(WDTO_1S);

    if (!LoRa.begin(433E6))
    {
        Serial.println("LoRa init failed. Check your connections.");
        {
            // blinking in panic
            LEDtime = millis();
            while (millis() - LEDtime < 75)
            {
                digitalWrite(ackLED, HIGH);
            }
            while (millis() - LEDtime < 150)
            {
                digitalWrite(ackLED, LOW);
            }
        }
    }

    LoRa.onReceive(onReceive);  // Assign callback
    LoRa.receive();
    Serial.println("LoRa init succeeded.");
}

void loop()
{
    digitalWrite(ackLED, isACKed == 0);

    if (millis() - lastLoopTime > 1000)
    {
        // Once per second loop
        lastLoopTime = millis();

        if (isACKed == 0)
        {
            if (ack_TO++ > 5)
            {
                sendMessage(outgoing); // Resend
                LoRa.receive();
                ack_TO = 0;
                Serial.println("Resend...");
            }
        }

        if (mincnt++ > 60)
        {
            // Once per minute loop
            mincnt = 0;
            if (isACKed)  // Free to ask
            {
                // Heartbeat
                cmdAsk();
                isACKed = 0;
            }
        }
    }

    if ((cc = Serial.read()) > 0)  // Test version, cmd
    {
        if (cc == '1')
        {
            cmdOn();
            isACKed = 0;
        }
        else if (cc == '0')
        {
            cmdOff();
            isACKed = 0;
        }
        else if (cc == 'Q')
        {
            cmdAsk();
            isACKed = 0;
        }
    }
//  onReceive(LoRa.parsePacket()); // Polling

    if (gotMsg)  // Flag from onReceive routine
    {
#ifdef TTT
        Serial.print("Received from: 0x");
        Serial.println(sender, HEX);
        Serial.print("Sent to: 0x");
        Serial.println(recipient, HEX);
        Serial.print("Message ID: ");
        Serial.println(incomingMsgId);
        Serial.print("Message length: ");
        Serial.println(incomingLength);
        Serial.print("Message: <<");
        for (int i = 0; incoming[i] != 0; i++)
            Serial.write(incoming[i]);
        Serial.println(">>");
        Serial.print("RSSI: ");
        Serial.println(LoRa.packetRssi());
        Serial.print("Snr: ");
        Serial.println(LoRa.packetSnr());
        Serial.println();
#endif
        // Command processing
        if (incomingLength == 4)
            if (incomingMsgId == msgSequ - 1) // Ack is on last sent
            {
                if (incoming[0] == 'T') digitalWrite(remoteLED, HIGH);
                if (incoming[0] == 'F') digitalWrite(remoteLED, LOW);
                isACKed = 1;
            }
        incoming[0] = 0; // Message is processed, clear flags
        gotMsg = 0;
    }

    if (LEDtime) // LED timeout
    {
        if (millis() - LEDtime > LEDonTime)
        {
            LEDtime = 0;
        }
    }
    wdt_reset();
}   // END of loop

void cmdOn()
{
    outgoing[0] = 0x55; // Heater  on
    outgoing[1] = 0xAA;
    outgoing[2] = 'X';
    outgoing[3] = 'Y';
    sendMessage(outgoing);
    LoRa.receive();
}

void cmdOff()
{
    outgoing[0] = 0xCC; // Heater  off
    outgoing[1] = 0x99;
    outgoing[2] = 'A';
    outgoing[3] = 'B';
    sendMessage(outgoing);
    LoRa.receive();
}

void cmdAsk()
{
    outgoing[0] = 0x0F;
    outgoing[1] = 0xF0;
    outgoing[2] = '7';
    outgoing[3] = '7';
    sendMessage(outgoing);
    LoRa.receive();
}

void sendMessage(char *outgoing)
{
    LoRa.beginPacket();                   // start packet
    LoRa.write(destination);              // add destination address
    LoRa.write(localAddress);             // add sender address
    LoRa.write(msgSequ++);                 // add message ID
    LoRa.write(bsize(outgoing));        // add payload length
    LoRa.print(outgoing);                 // add payload
    LoRa.endPacket();                     // finish packet and send it
}

byte bsize(char *ooo)
{
    byte i = 0;
    while (ooo[i++]);
    return i - 1;
}

byte bsize(volatile char *oo)
{
    return bsize((volatile char *)oo);
}

unsigned char insptr;
void onReceive(int packetSize) // is a non blocking function
{
    if (packetSize == 0) return;     // if there's no packet, return
    if (gotMsg) ovrn = true; // gotMsg should be reset by consumer by now

    // read packet header bytes:
    recipient = LoRa.read();         // recipient address
    sender = LoRa.read();            // sender address
    incomingMsgId = LoRa.read();     // incoming msg ID
    incomingLength = LoRa.read();    // incoming msg length

    insptr = 0;

    while (LoRa.available())
    {
        if (insptr < 38)
            incoming[insptr++] = (char)LoRa.read();
        else
            LoRa.read();  // Flush
    }
    incoming[insptr] = 0;
    gotMsg = true;
}

/*
void setTxPower(int level, int outputPin = PA_OUTPUT_PA_BOOST_PIN);
void setFrequency(long frequency);
void setSpreadingFactor(int sf);
void setSignalBandwidth(long sbw);
void setCodingRate4(int denominator);
void setPreambleLength(long length);
void setSyncWord(int sw);
void enableCrc();
void disableCrc();

RSSI always a value between -30 ( very close) and - 120
SNR 0 is noise floor… max = 10

*/

```

# Answer
I feel I want to report the probable solution to this problem.
I hope an answer to my own question is appropriate.

After much testing I found an interaction between the boot loader and the watchdog. This post describes it well: Watchdog timer blog post
So, replacing the boot loader seems to remove the hangup, so far ... Why the watchdog triggers in the first place remains to be found out but presently it does little or no harm.

A side note, the reset button seems to reset the ProMini if pushed reasonably soon after the hangup. If pushed hours later it has no effect.
> 2 votes

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


title: Can the DHT11 give reasonable readings?

text:
# Question
Title: Can the DHT11 give reasonable readings?
I bought a batch of ESP8266-01 and DHT11 on ebay.

The sensors give data, but the datasheet say +/- 2 degrees. Who can live with that? Well, they claim the repeatability is 0.2 degrees, so I guess they could be calibrated.

But thet are not stable. They start a few degrees over room temperature, but gradually the reading is up to 33 degrees, more than 10 degrees too high.

Could it be the proximity of the ESP8266 giving off heat? Or are the sensors themselves heating up when reading at one read every two seconds?

# Answer
> 2 votes
It could be the ESP8266, try physically separating the DHT11, but I'm guessing that that will only help slightly.

Do you have some way of reliably calibrating the sensors? If not, then even if you are getting consistent readings, you'll have a hard time knowing how accurate your readings are.

While they're typically more expensive, it might be prudent to buy an infrared temperature sensor. If you have the budget, replacing the DHT11s with IR temperature sensors might just be a better solution, I saw that Sparkfun's MLX90614 was accurate within +/- 0.5 degrees Celsius. If you don't have the budget to replace your DHT11s, or don't want to be wasteful, perhaps you just buy one IR temperature sensor to use as a sanity check. These should be more reliable than DHT11s and you could even write a sketch to calibrate them based on the IR temperature sensor's readings.

---
Tags: esp8266
---


# Question
Title: Circuit works on breadboard but has power problems on protoboard
I'm building a simple circuit that takes data from an IMU (using MPU6050), sends it to a microprocessor (Arduino Pro Mini 5V) to apply data smoothing and averaging, and then this data is sent using an HC-08 BLE module for the data to be further processed on a mobile. The circuit is powered by a 9V battery (6LR61) connected to RAW (Vin on other Arduino boards).

When I build this circuit on a breadboard, it works well, but the Arduino is power hungry as expected. It runs for over an hour in this setting (I haven't tested it for longer), but I've build this circuit twice using protoboards and it can't stay on. One circuit is able to send data for a while, but the LED on my BLE module dims and eventually turns off after ~5m, and requires me to wait 30+m before I try to power the circuit again. The other circuit has all LEDs shine when power is switched on, but the IMU doesn't send any data (an LED on the Pro Mini blinks whenever I2C data is received).

The shitty thing is that, whenever I power these circuits via USB, they work as intended, just like when I power them using 9V to RAW on the breadboard.

I tested the circuit on the breadboard later and after BLE has connected and is sending data, the whole circuit draws 42.9mA, the BLE module draws 1.5mA, and the IMU draws 5.4mA.

**What is the most effective way to fix this problem? Should I focus on finding a different battery, or focus on power-savings within the circuit?**

These are my ideas so far:

* replace all boards with 3.3V versions
* reduce clock speed (might not be viable, I need a lot of IMU data?)
* use external voltage regulator, connect Vout from regulator to 5V of pro mini
* replace 9V battery with Lithium Ion battery
* replace Pro Mini with an ATtiny85

I'd like to take the least time to maximize power savings, so while I could go through all these ideas, I just need the circuit to work at the end of the day.

# Answer
> 2 votes
I have a page about power saving.

To summarize some of the techniques you can use:

* Run the processor at a lower frequency
* Run the processor at a lower voltage
* Turn off unneeded internal modules in software (eg. SPI, I2C, Serial, ADC)
* Turn off brownout detection
* Turn off the Analog-to-Digital converter (ADC)
* Turn off the watchdog timer
* Put the processor to sleep
* Don't use inefficient voltage regulators - if possible run directly from batteries
* Don't use power-hungry displays (eg. indicator LEDs, backlit LCDs)
* Arrange to wake the processor from sleep only when needed
* Turn off (with a MOSFET) external devices (eg. SD cards, temperature sensors) until needed

I've got a temperature and humidity sensor which has been running for **years** on 3 x AA batteries.

---

> The circuit is powered by a 9V battery (6LR61) connected to RAW (Vin on other Arduino boards).

That's not a great choice for a start, as the voltage regulator has to turn the 9V into 5V (in the form of wasted heat). You'd be better off with 3 x AA batteries (around 4.5V) and put them straight into the 5V pin.

Those 9V batteries have notoriously low mAh because they are basically 6 coin cells stacked on top of each other.

---
Tags: power, bluetooth, arduino-pro-mini, current, imu
---


# Question
Title: Can the arduino be recognized if the usb chip is broken?
My question might seem one of the million questions out there "Can't upload to arduino uno and receive error avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x01" but as I probably read all the million questions and didn't find the answer I am looking for I decided to write my own.

So my arduino is properly detected in device manager and in the arduino IDE but cant upload sketches to it. The main chip (atmega328p) seems well (13-pin LED blinks 3 times on reset) but the usb chip (ATmega16u2) is what I suspect as the RX and TX LEDs don't blink while uploading (and don't blink in any other situation) but again the arduino is detected and I am sure I chose the right board and port.

The serial monitor is always empty and I tried the loopback test and didn't get any echo at all or even any error message but I think that what I should have expected as the RX and TX not blinking means that there is no data transmission in the first place. Or am I wrong?

So is the USB chip broken or maybe corrupt? How can I be sure? And if not then what could the problem be?

I saw a tutorial in the answer of this question to test the usb chip using another arduino but I don't have that in hand right now or an ICSP programmer for that matter.

# Answer
> 1 votes
It depends on the exact arduino product. An Arduino Uno has a USB programmer chip, that then programs the AtMega 328 Chip. If the programmer is broken, it will likely not register any device when you plug in an arduino uno to your PC.

if the micro-controller is dead, but the programmer is operational, you will get a device in your device manager, but not be able to reprogram the micro controller.

If both the programmer, and the micro-controller are broken, then figuting that out could be difficult. The AVR microcontrolers support other programing methods, and the AtMega 328 IC, supports DebugWire. you could attempt to reprogram the MCU out side of the programmer, if you thought the programmer, was defective.

Here is a great article on using DeBugWire. https://awtfy.com/2010/02/21/modify-an-arduino-for-debugwire/

another nifty trick I learned, is to take your Digital MultiMeter, set it to diode test, or continuity. then, measure between the ground pin, and the positive voltage pins on the MCU. If you get a shot, the chip is busted. You will expect to get roughly 0.7Volts, although an OL reading might indicate more about your multi-meter, than the MCU.

Other Arduino devices, that have integrated USB programing, may behave differently. Features of the specific MCU dictate how it can be debugged. You might want to read the datasheet for a specific MCU if you're having trouble.

---
Tags: arduino-uno, avrdude, atmega16u2
---


title: memory usage "dos and don'ts"

text:
# Question
Title: memory usage "dos and don'ts"
Though I've written C/C++ code for a long time, the unseen limitations on how memory was consumed on various MCU and SOC programming platforms have often tripped me up. As I'm about to build up code for my first large project for my NANO boards, which will likely use a fair amount of its resources, I'd like to be better prepared for any surprising and unexpected "gotchas" to look out for.

For example, on another SOC I recently worked on extensively (The Pololu.com wixel) I was very surprised to learn that function/method arguments and auto variables, which I'd normally expect to be stack allocated and recovered when a function returns were in fact permanently allocated for the life of the program! Wow! so on that platform, where I'd normally hate to "overwork" variables or reuse variables after their names no longer make sense, I had to adjust my coding to what I'd normally consider BAD for readability. Not to mention realizing that simple loop variables were better off allocated globally. Yecch!

Can those of you who have run into such unexpected coding issues in the Arduino environment share some "special" guidelines about things like this?

# Answer
As you have noticed yourself, this can be somewhat platform-dependent. Since you are working on a Nano, my answer will be for the AVR architecture, when compiled with gcc, the avr-libc, and the Arduino core library.

First, let me reassure you: this weird behavior you saw of the Wixel doesn't happen on this platform. Local variables get allocated mostly in CPU registers, then on the stack.

Now, the first general rule may sound obvious: think twice about what your program *really* needs to remember. Also, use each time the smallest possible data type. The C99 types `int8_t`, `uint16_t` and co. are useful for this.

Another rule you will often hear on this platform: avoid dynamic allocation, i.e. `malloc()` and `new`, as quite often you cannot afford heap fragmentation. Avoid also the `String` class, as it relies on dynamic allocation. Prefer when possible static allocation, or stack allocation for small things.

Don't forget to use `const` for constants: with this qualifier the compiler can often optimize the constants out as immediate operands. For arrays of constants, use `PROGMEM`. Yes, it's not comfortable to use, but it can save you lots of RAM. The `F()` macro for printing constant messages is a special case of `PROGMEM`.

Lastly, be very careful with recursion.
> 11 votes

# Answer
Edgar's got some great tips, and I'll reiterate one before giving a few more:

**avoid dynamic memory allocation**

Don't use malloc. When you're designing a system, budget out your RAM like you do your monthly budget. Make sure you're able to do everything at once.

And a couple other tips:

**global statics**

Make full use of the BSS block; try to block out space for as much as possible in global `static` arrays. You may shudder or scoff at the idea of putting everything at a global level, but embedded is a paradigm shift, with its own set of rules.

Since you'll have so many variables at a global level, `static` helps you to avoid polluting your namespace too much.

**avoid fancy C++ features**

In fact, try to not use C++ at all. C++ takes you "farther from the metal," with its RAII and its constructors and its implicit type conversion... It's much harder to keep a tight inventory of all of your resources when your language does so much behind the scenes. If you really want to use a certain C++ language feature, try to keep the tone of your code more like "C with bits of C++" rather than "C++ shoehorned into an embedded system." That never goes well.

Especially avoid generics/templates, which will eat up lots of your memory. Every time you use a new type with a template in your code, another copy of the template class is compiled into your program, just for that one type. Ever wonder why C++ binaries can balloon to 20, 50, even 100 MB? Templates, man. Templates.

**const**

This keyword should go on as many variables as it can. Keeping this habit will save on both execution time and space consumption. Learn the difference between `const T* foo`, `T* const foo`, and `const T* const foo`.
> 3 votes

---
Tags: memory-usage
---


# Question
Title: Where to connect an external power source for an Arduino motor driver shield to?
I have a BYJ48 stepper motor and an ULN2003A motor driver shield shield.

In many tutorials I read:

> do not to draw current from the 5V on the Arduino rail, but use an external power source, since the motor can draw quite some current

Which of these options to they mean by this?

> Connect an external power adapter to the Arduino and connect the ULN2003A board to the Vin pin and GND on the Arduino

or

> Connect the motor shield itself to an external power adapter and connect it to the + and - pin on the motor shield

or perhaps both are valid solutions?

The board I use is this one.

# Answer
> 0 votes
There are two things you need to do:

1. Prevent the motor drawing its power from the micro-controller board.
2. Make sure that all the grounds are connected but avoiding motor current return through the micro-controller board.

simulate this circuit – Schematic created using CircuitLab

*Figure 1. A good wiring configuration. The heavy wires carry the motor current.*

Note that there is one ground connection between the micro-controller and the motor system. The return current for the 12 V supply does not pass through the micro-controller board.

---
Tags: arduino-motor-shield
---


# Question
Title: analogWrite(DAC0, X), Analog voltage on DAC0 pin is higher for lower X value - is this normal?
I am using an Arduino DUE. Using the `analogWrite(DAC0, X)` command I am writing an analog value to this pin. X = 0 - 255 as I understand it.

I am observing that when X is lower, the voltage on DAC0 is higher nad when X is higher the voltage is lower.

Is that expected?

My code is simple:

```
void setup()
{
  analogWriteResolution(12);
}

void loop()
{
  analogWrite(DAC0, 10 );
}

```

# Answer
> -1 votes
That doesn’t sound right. Try setting **x** to 0 and measure with DC. You should get ~0.56 V. Repeat with 4095, and you should get ~2.76 V.

Also, note that with `analogWriteResolution(12)` your range is not 8-bits (0-255), but 12-bits (0-4095).

The output should follow:

**Vout = Vref * Xin(2N-1) \+ Voffset**

where

* Voffset = 0.56 V
* Vref = 2.2 V
* 0 ≤ Xin ≤ 4095

---
Tags: arduino-due, analogwrite, digital-analog-conversion
---


title: Arduino Rotary Encoder Pulses?

text:
# Question
Title: Arduino Rotary Encoder Pulses?
I made an program so if I turn on my rotary encoder the position and the rotation comes on a LCD screen. But I need to change it a bit up for my teacher, she wants to see the graph of the pulses on the serial monitor. I searched it up and can't find a solution? Any help?

My program:

```
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);
#define outputA 2
#define outputB 4
int counter = 0;
int angle = 0;
int aState;
int aLastState;
int lastAngle = 0;
String rotationDirection;
String savedRotationDirection;

void setup() {
  pinMode (outputA,INPUT);
  pinMode (outputB,INPUT);

  aLastState = digitalRead(outputA);
  lcd.begin();

     }

void loop() {
  aState = digitalRead(outputA);
  if (aState != aLastState){
     if (digitalRead(outputB) != aState) {
       counter ++;
       angle ++;
     }
     else {
       counter--;
       angle --;
     }
     if (counter >=30 ) {
      counter = 0;
     }

     if (angle < lastAngle){
      rotationDirection = "CCW";
     }
     else {
      if (angle > lastAngle){
        rotationDirection = "CW";
      }
      else {
        rotationDirection = savedRotationDirection;
      }
     }
     lcd.clear();
     lcd.setCursor(0,0);
     lcd.print("Position: ");
     lcd.print(int(angle)*(-1));
     lcd.print((char)223);
     lcd.setCursor(0,1);
     lcd.print("Rotation: ");
     lcd.print(rotationDirection);
     savedRotationDirection = rotationDirection;
     lastAngle = angle;
  }
  aLastState = aState;

}

```

# Answer
Add Serial.begin(115200); in setup() and use Serial.println() or Serial.print() to print to Serial.

In Arduino IDE open Serial Monitor and set baud rate to 115200.

EDIT: The question turned out to be about Serial Plotter. Maximilian Gerhardt answered in a comment :

> If you want multiple data streams (graphs) you need to seperate them by a comma: Serial.println( String(digitalRead(outputA)) + "," + String(digitalRead(outputB)));
> 2 votes

---
Tags: rotary-encoder
---


# Question
Title: Why I get error on string concatination?
exit status 1 invalid operands of types 'const char \[5\]' and 'const char \[2\]' to binary 'operator+'

```
  String message = "Page not found\n\n";
  message += "URI: " + HTTP.uri() + "\n";
  message += "Method: " + (HTTP.method() == HTTP_GET)? "GET": "POST" + "\n";
  message += "Arguments: " + HTTP.args() + "\n";

```

# Answer
The operators of the class String apply only for an instance of String. In your expression you concatenate two c-strings "POST" + "\n"
> 2 votes

# Answer
A simple fix is to just move the (const char \*)s around a little:

This should compile

```
  String message = "Page not found\n\n";
  message += "URI: " + HTTP.uri() + "\n";
  message += "Method: " + (HTTP.method() == HTTP_GET)? "GET\n": "POST\n";
  message += "Arguments: " + HTTP.args();
  message += "\n";

```
> 0 votes

---
Tags: string, nodemcu
---


# Question
Title: How to scroll data in LED dot matrix through multiple modules?
I've been struggling in this issue for a long time, I know there are people who have done it.

But, I don't have much experience in C to have the skills to design or develop such complicated functions.

I want to scroll data, e.g. text, chars or numbers just like the nice projects in YouTube about the dot matrix.

Like this one: How to Make a SCROLLING TEXT Display at Home

I know how to display a char, but I don't know how to scroll it. If I try I don't get the results I want.

This is my function for displaying chars:

```
void draw(void)
{
  s=0;
  uint8_t data_shift_buf;
  for (l=0;l<26;l++)            // to print 26 letters
  {
    for (row=1;row<9;row++)     // for 8 matrix rows
    {

        SPI_TX_m16(data = (row<<8) | (Alphabet[s]),4);// trying set data by column
        s++;_delay_ms(300);
    }
  }
}

```

# Answer
> 0 votes
This is the function for my problem.

```
void draw(void)
{
uint32_t map_buffer=0;int8_t i,k;
uint8_t data_reg[4] = {0xaa,0xbb,0xff,0xff};      // random data to write
uint8_t dis_buf[4],no_device,no_col;s=0;l=3;

for (i=0;i<4;i++)
map_buffer |= data_reg[i] << i*8;                 // loading data into map_buffer

for (col=0;col<32;col++)                          // for 8 matrix columns
{
    map_buffer >>= 1;                            // start shifting the data by 1 pixel
    for (i=0;i<4;i++)
    dis_buf[i] = map_buffer >> i*8;              // loading shifted data into display buffers
    for (i=0;i<4;i++)
    {
        for (row=1;row<9;row++)                 // for 8 matrix rows
        {
            SPI_TX_m(data = (row<<8) | (dis_buf[i]),i);
        }
    }_delay_ms(1000);
}

```

}

---
Tags: led, c, avr, data
---


# Question
Title: Extract binary data from text string. Like Perl pack, not just regexp
If I have data coming into an Arduino in an ASCII serial format from some external device (or from a PC, or whatever) and I want to extract binary values from that data and log it or put it on a little display or react to it or whatever there are a few ways I can do it. But it seems like there should be a reversed version of sprintf, mashed up with regexp, mashed up with Perls pack/unpack that would make it easy and configurable.

For example, let's say I'm getting hex numbers from a data logger. something like `c,03,1234,5678,9ABC` where c is just a code telling me this line is channel data, there are 3 channels installed, and then there are the 3 sets of data. I can use split or something like that and then extract the values, convert the hex to binary, apply Y=mX+B and display the channel readings. If a channel goes flat, I can sound an alarm, etc... No worries.

But then I have a different data logger plugged in, and this one uses a different format. Like decimal raw ADC counts. It spits out `2342 1313 234236` Now I gotta recode.

But wait, what if I just had a regexp in eeprom and I used that to extract the data? Something like `/^c,\X+,(\X+),(\X+),(\X+)$/` for the first logger and `/^(\d+) (\d+) (\d+)$/` for the second. That would be really cool because I could pretty much extract data from any serial device for local display. No need to reprogram, just update the regexp. And there is a nice regexp library: https://github.com/nickgammon/Regexp although it uses the LUA regexp syntax.

Oh, but that won't work... because although my program in the Arduino gets back 3 values from the regexp, it doesn't know that the first set are hex strings, and the second set are decimal.

Now, if I was doing this in Perl, I'd just apply a pack string to the binary data. But then pack can't reject a bad match, it always returns a result, even if the input wasn't valid.

Doesn't it seem like the regexp should be able to return /binary/ values instead of just the string? It knows those values are hex. And shouldn't pack be able to do matching against the other characters in the string and reject the value if it's not a match?

Seems to me like there is a hole in our standard libraries. Something that does both simple matches, and converts data to binary return values on the fly.

Or is that too much to ask from an engine? Perhaps few people would use it; better to just hardcode for the rare times you need something like this?

# Answer
> Something that does both simple matches, and converts data to binary return values on the fly.

You are describing `sscanf()`. It is way less powerful than regexps when it comes to pattern matching, but it seems to closely match your requirements.

Dummy example:

```
const int FORMAT_COUNT = 2;
const char * formats[FORMAT_COUNT] = {
    "c,%*x,%lx,%lx,%lx",  // first data logger
    "%lu %lu %lu"         // second data logger
};

// Here goes the data.
unsigned long channels[3];

// Try to parse using all the known formats.
void parse(const char *message)
{
    for (int i = 0; i < FORMAT_COUNT; i++) {
        int ret = sscanf(message, formats[i],
                &channels[0], &channels[1], &channels[2]);
        if (ret == 3) {
            Serial.print("Message \"");
            Serial.print(message);
            Serial.print("\" matched with format \"");
            Serial.print(formats[i]);
            Serial.println("\"");
            return;
        }
    }
    Serial.println("Could not parse message.");
}

```

Sample output:

```
Message "c,03,1234,5678,9ABC" matched with format "c,%*x,%lx,%lx,%lx"
Message "2342 1313 234236" matched with format "%lu %lu %lu"

```
> 1 votes

# Answer
Yes, but it doesn't really *know* something is hex. What about the patterns:

```
[\dA-F]
[0-9A-Fa-f]

```

And so on. The regexp library is simply a way of extracting out substrings of a target string. It doesn't make a heap of sense for it to try to auto-detect the type of the returned string. For example, a GUID might be a lot of hex digits. Do you want something like `182676d07497c511f850` to be somehow converted into binary? And then what? Compressed into an `int`?

In fact it doesn't return (decimal) numbers anyway, it returns a string which may or may not be convertible into a number. Chris Stratton's suggestion of using `atoi`, `sttol` and so on is the logical way to go. Just have a flag in your EEPROM that tells the decoding routine what format the input data is. Also, for simple string sequences, don't forget `strtok`.
> 1 votes

---
Tags: serial
---


# Question
Title: Propane injection software compiles, uploads, doesn't work
Looking for some help here. I have written out some code to add propane injection for my forklift. It is supposed to read three analog inputs, add them together and multiply the sum by three. There is an interrupt which is triggered by a hall effect sensor which is supposed to fire a solenoid valve for a duration of microseconds. I have mocked this up on a breadboard with a attiny85 pulsing the hall effect pin and nothing happens. Would appreciate some one having a look at the code and letting me know where I went wrong. Thanks.

```
const byte interruptPin = 2; //this is the interrupt pin hall sensor//
int mpPin = A3; //manifold pressure sensor//
int tpsPin = A4; //throttle position sensor//
int tunePin = A5; //tune pot 10k//
volatile byte inj; //this will end up being the duration of the injector pulse//
int mpValue = 0; //setting manifold variable to zero//
int tpsValue = 0; //setting throttle positon sensor value to zero//
int tuneValue = 0; //setting tune value sensor variable to zero//
int injValue = 0; //setting injection variable to zero//

void setup() {
    pinMode(12, OUTPUT);  //this is the pin that fires the injector//
    pinMode(interruptPin, INPUT_PULLUP); //set the interrupt pin to high pull up //
    attachInterrupt(digitalPinToInterrupt(interruptPin), shot, LOW);  //set the interrupt to trigger shot isr on low//
}

void loop() {
    tpsValue = analogRead(tpsPin); //read the throttle positon sensor//
    mpValue = analogRead(mpPin);//read the manifold pressure sensor//
    tuneValue = analogRead(tunePin); //read the tune sensor//
    injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//
}

void shot() {
    digitalWrite, 12, HIGH; // initilize injector powerup//
    delayMicroseconds(inj); //delay the calculated value  in microseconds//
    digitalWrite, 12, LOW; //shut down the injector//
}

```

# Answer
I can see two things wrong with your code at first glance. First is the kind of interrupt you're using:

```
attachInterrupt(digitalPinToInterrupt(interruptPin), shot, LOW);

```

A `LOW` interrupt keeps triggering over and over again *all the time the input is low*. It's a special interrupt type that is seldom used for anything except waking up the MCU or handling external peripherals with *persistent* interrupt indication. Instead you should be using `FALLING` which will trigger once and once only when the input transitions from `HIGH` to `LOW`.

```
attachInterrupt(digitalPinToInterrupt(interruptPin), shot, FALLING);

```

Secondly you have two variables that seem to be intended to do the same thing - store the delay time for your output pulse. And that's caused confusion:

```
injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//

```

... and then later ...

```
delayMicroseconds(inj); //delay the calculated value  in microseconds//

```

In your comments you reference the second variable, but the code uses the first one. Change that so it uses just one (volatile) variable:

```
inj = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//

```

Alternatively, and perhaps much safer, is to assign the result of the calculation inside a *critical section*, in which case having two variables is useful:

```
injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//
noInterrupts();
inj = injValue;
interrupts();

```

This will prevent your interrupt triggering whilst the value is being calculated and placed into the `inj` variable which could result in the `inj` variable containing gibberish, which could cause your engine to explode.
> 1 votes

---
Tags: interrupt
---


# Question
Title: Properly using separate tabs with Arduino IDE
I'm trying to split up a large project of mine into separate tabs in the Arduino IDE and I'm having more than a few troubles with it. My main trouble is finding a way to have routines in extra tabs access the Serial object; because it's really hard to debug things with `Serial.println()` otherwise. All I get, though, is "'Serial' was not declared in this scope". There appears to be some kind of trick to this? I've noticed that "byte" or "bool" needs to be declared in .cpp tabs and .h tabs but not on the main one? Is there some kind of easy way to set this up so that I don't need to constantly `#include <stdbool.h>` and `typedef unsigned char byte;`?

Current issue: Main file:

```
void setup() {
  Serial.begin(500000);
  PrintMessage();
}

void loop() {
}

```

driver.ino file:

```
byte PrintMessge () {
  Serial.println("printin");
}

```

and on compiling:

```
error: 'PrintMessage' was not declared in this scope

```

EDIT: Found a silly typo. Problem solved.

# Answer
This question is more about C/C++ header basics rather than Arduino. Anyways, you should have the following file structure: Code in `.cpp`files, Header in `.h` files. Main sketch either `.ino` or `.cpp` (for cpp remember that you must explicitly write out the function prototypes!)

So for your small example that would be:

`main.ino`:

```
#include "driver.h"
void setup() {
  Serial.begin(500000);
  PrintMessage();
}

void loop() {
}

```

`driver.cpp`

```
#include "driver.h"
byte PrintMessage () {
  Serial.println("printin");
  return 0; //previously had no return although returning 'byte'.
}

```

`driver.h`

```
 //Always use include guards
 #ifndef DRIVER_H
 #define DRIVER_H

 #include <Arduino.h>
 //All function prototypes from driver.cpp.
 byte PrintMessage();

 #endif /* DRIVER_H */

```

Also corrected a typo from `PrintMessge` to `PrintMessage`. This is the "professional" way to do it, seperate implementation and header files.
> 5 votes

# Answer
Tabs are actually quite simple:

* If it's named `<something>.ino` it will get merged with the main tab. It's just like working in one big file and you don't need to do anything special.
* If it's named `<something>.cpp` or `<something>.c` it's a completely separate *translation unit* and has to be manually "enroled" into the Arduino system by including the `Arduino.h` header.

So it's simplest to just name them as INO files not CPP files and you don't have to do anything special:
> 1 votes

---
Tags: arduino-ide, c++, c
---


title: Changing Arduino Outputs into Binary

text:
# Question
Title: Changing Arduino Outputs into Binary
I am new to Arduino so please give me some advice on this really simple problem. I am currently using an Arduino Mega in a school project to make 4 capacitive sensors which are supposed to receive an input when you touch the sensors, and I have programmed the arduino such that you will light up an LED upon touching the sensors.

Now the problem is after I light up the LEDs the serial data monitor gives me many different numbers when I am touching the sensors. Is it actually possible for me to tweak my program such that outputs of my sensor will show up as a single line of '0' when the sensor is not being touched and '1' when the sensor is being touched? This would really help me in the quantifying of some of the data I would wish to collect from my experiments with the sensors.

My code is

```
#include <CapacitiveSensor.h>

CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4); // 1M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_5_7 = CapacitiveSensor(5,7);
CapacitiveSensor   cs_8_10 = CapacitiveSensor(8,10);
CapacitiveSensor   cs_11_13 = CapacitiveSensor(11,13);

void setup()
{
   cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);// turn off autocalibrate on channel 1
   cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_8_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_11_13.set_CS_AutocaL_Millis(0xFFFFFFFF);

   Serial.begin(9600);
   pinMode(3,OUTPUT);
   pinMode(6,OUTPUT);
   pinMode(9,OUTPUT);
   pinMode(12,OUTPUT);
}

void loop()
{
 long sensor1 =  cs_2_4.capacitiveSensor(50);
 long sensor2 =  cs_5_7.capacitiveSensor(50);
 long sensor3 =  cs_8_10.capacitiveSensor(50);
 long sensor4 =  cs_11_13.capacitiveSensor(50);
Serial.print("\t");
Serial.println(sensor1, BIN);  // print sensor output
Serial.print("\t");
Serial.print(sensor2, BIN);
Serial.print("\t");
Serial.print(sensor3, BIN);
Serial.print("\t");
Serial.print(sensor4, BIN);

    if(sensor1 >= 1000)
   {
    digitalWrite(3,HIGH);
   }
   else{
    digitalWrite(3,LOW);
   }
     if(sensor2 >= 1000)
   {
    digitalWrite(6,HIGH);
   }
   else{
    digitalWrite(6,LOW);
   }
    if(sensor3 >= 1000)
   {
    digitalWrite(9,HIGH);
   }
   else{
    digitalWrite(9,LOW);
   }
    if(sensor4 >= 1000)
   {
    digitalWrite(12,HIGH);
   }
   else{
    digitalWrite(12,LOW);
   }
   }

```

and the output that I end up receiving is

Hence it would be really great if I could tweak my code such that the output on the serial monitor would be '0' when there is no output(Not touching sensor) and '1' when there is an output (touching sensor)

Thanks a lot for the help once again!

# Answer
It sounds like what you want isn't really "binary", nor the bit-to-characters expansion of the touch readings.

Rather it sounds like what you want to do is to print the character '0' or '1' for the state of each button. You already have the decisioning code for your outputs, so you can simply extend it for the serial prints:

```
if(sensor1 >= 1000) {
   digitalWrite(3,HIGH);
   Serial.print("1");
} else{
   digitalWrite(3,LOW);
   Serial.print("0");
}

```

and so on, with the next set having tabs and the last a newline.

Worth noting, intermixing the printing and digital outputs will put some time delay between the outputs (potentially quite a bit if the evaluation gets ahead of the serial buffers), so another option could to do all the outputs and then all the prints, or store the decisions in a bit mask for later printins, etc.
> 1 votes

# Answer
`capacitiveSensor` returns an analog value so you need to set a threshold for the point where 0 (AKA `false`) becomes 1 (AKA `true`):

```
long touchThreshold = 123;  // Adjust this according to your application

```

...

```
boolean sensor1 = (cs_2_4.capacitiveSensor(50) > touchThreshold) ? true : false;

```

If you don't recognize that syntax, it's the conditional operator but you could just as well use `if`.
> 0 votes

---
Tags: arduino-mega
---


# Question
Title: Getting error 32 in multi-master I2C sketch with library https://github.com/rambo/I2C
I am developing a multi-master scenario sketch with the https://github.com/rambo/I2C library, because this library will handle multi-master data collisions.

I created a setup with two Arduino nano's which act both as master and slave.
My sketch works as long as I use only one master. Sending data from one Arduino to the other works fine. The other receives the data.

But when I sequentially try to send data from the second Arduino to the first, I get an error (32). After that even sending data from the initial Arduino results in error 32.

This is the used sketch for both the Arduino's. The only difference is that I switch the values of rel\_address and own\_address when programming the seconds Arduino.

Sending data is done by pressing a button on pin 2 (switchPin)

```
/**
   atme328 = ATmega328
   SDA --> Pin A4
   SCL --> Pin A5
*/
#include <I2C.h>
#include <Wire.h>

int switchPin = 2;
int relayOnPin = 3;
int relayOffPin = 4;

uint8_t broadcast_address = 0;
uint8_t own_address = 11; // CHANGE FOR EVERY MODULE!!
// rel_address = address of relay to switch; SET to own_address if relay is connected to this chip!
uint8_t rel_address = 10; // CHANGE FOR EVERY MODULE!! SET to own_address if relay is connected to this chip!
uint8_t rpi_address = 1;

unsigned long counter = 0;

void setup() {

   Serial.begin(9600);
   pinMode(switchPin, INPUT_PULLUP);

   pinMode(relayOnPin, OUTPUT);
   pinMode(relayOffPin, OUTPUT);
   // start condition
   digitalWrite(relayOnPin, HIGH);
   digitalWrite(relayOffPin, LOW);

   I2c.begin();
   I2c.timeOut(50);
   // I2c.pullup(true); // done by external 4.7kOhm resistors

   // config Wire library for I2C slave functionality
   Wire.begin( own_address );

   TWAR = (own_address << 1) | 1;  // enable broadcasts to be received!

   // set slave receive callback
   Wire.onReceive( onI2CReceive );

}

void loop() {
   counter = counter + 1;
   if (counter == 20000) {
      digitalWrite(relayOnPin, LOW);
      digitalWrite(relayOffPin, LOW);
   }
   if ( digitalRead(switchPin) == LOW ) {
      sendCmd('d', rel_address); // send command to remote relay
   }
}

void sendCmd(uint8_t cmd, uint8_t address) {
   uint8_t status = I2c.write(address, cmd); //configure device for continuous mode
   if (status > 0) {
      // error codes at https://github.com/rambo/I2C/blob/master/I2C.cpp
      Serial.print(status, DEC);
      Serial.print('!');
      digitalWrite(relayOffPin, HIGH);
      delay(50);
   } else {
      digitalWrite(relayOnPin, HIGH);
      Serial.print('.');
   }
   counter = 0;
}

void onI2CReceive(int howMany) {
   // loops, until all received bytes are read
   while (Wire.available() > 0) {
      digitalWrite(relayOffPin, HIGH);
      Serial.write(Wire.read());
   }
   counter = 0;
}

```

What do I need to do to be able to send from two units using this library? Thanks!

# Answer
You cannot use the I2C library and the Wire library at the same time. From the code I guess you wanted the Wire library to do the slaves job and the I2C library to implement the master. But since both libraries use the same hardware, this cannot be divided between them. Combining two libraries for the same hardware isn't that trivial. The I2C library only provides master functionality. So, to reach your goal, you would have to find a library, that provides both master and slave functionality while doing correct bus arbitration (which is the term for correctly handling master data collisions). Or you have to change one of the two libraries yourself, to provide the missing functionality.

And the error you get is defined in `#define MT_SLA_NACK 0x20` in I2C.h (0x20 is equal to 32). This means, that you haven't got an acknowledgement from the slave you have addressed. This suggests, that in your current code only the master functionality is working. (But it may have another meaning considering the interaction of the two libraries on the same hardware)
> 1 votes

# Answer
I ended up removing the I2C library and using a modified version of Wire. I replaced the twi.h and twi.c libraries in C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility with those from http://liken.otsoa.net/pub/ntwi/. This implementation adds timeouts to the operations, which prevents a hang-up.
> 0 votes

---
Tags: arduino-nano, i2c, atmega328
---