# Question
Title: Using ESP8266 Adapter with Temperature/Humidity Sensor
Good Day. I am currently following a project where I can send data to my firebase database using an ESP8266-ESP01 wifi module and DHT11 temp/hum sensor. I am using this adapter to enter the boot mode already with a program. Everything seems fine.

When I need to upload a program I am just tweaking the adapter using jumper cables to put the GPIO0 to GND and It works fine. My problem now is I have to use the DHT11 Sensor which is supposed to be connected to GPIO2. I tried to go to bootmode so I connected DHT11(data) directly to the ESP8266(GPIO2) leaving the slot in the adapter empty in which I cant enter the boot mode for some reason.

But when I plug ESP8266(GPIO2) to the adapter slot, I can enter bootmode. Currently confused on how to tweak the adapter to be able to use the GPI02 to the DHT11. Any tips would really help. thanks!

# Answer
> 0 votes
Thank you everyone for the tips. I have found a way to use the esp8266 adapter with the DHT11 sensor. First of all it was on boot mode all along, I had some code mistakes where my target url includes an 'https' tag on it thus not functioning as expected.

For those who would like to use this specific adapter with DHT11 attached in boot mode.

-Connect all female jumper wires end to the Esp8266 and the male jumper ends to the adapter except for the GPI02.

-The GPI02 slot on the adapter will be empty but the ESP8266 GPI02 end must be connected to the data pin of the DHT11.

Make sure that the ESP8266 and DHT11 sensor have enough power for both devices.

---
Tags: esp8266, temperature-sensor
---


title: Fading LED Lights

text:
# Question
Title: Fading LED Lights
How do you make a fading led with 8 different colors I already made a blinking led every 1 second. Can you give me an idea how am I going to fade it every time it switch?

```
const int red = 5;
const int green = 6;
const int blue = 9;

void setup() {
    // put your setup code here, to run once:
    pinMode(red, OUTPUT);
    pinMode(green, OUTPUT);
    pinMode(blue, OUTPUT);
}

void loop() {
    lightMe(red);
    lightMe2(red, green);  // yellow
    lightMe(green);
    lightMe2(green, blue);  // cyan
    lightMe(blue);
    lightMe2(blue, red);  // magenta
    lightMe3(red, green, blue); // white
}

void lightMe(int pin){
    digitalWrite(pin, HIGH);
    delay(1000);
    digitalWrite(pin, LOW);
    delay(500);
}

void lightMe2(int pin1, int pin2) {
    digitalWrite(pin1, HIGH);
    digitalWrite(pin2, HIGH);
    delay(1000);
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, LOW);
    delay(500);
}

void lightMe3(int pin1, int pin2, int pin3) {
    digitalWrite(pin1, HIGH);
    digitalWrite(pin2, HIGH);
    digitalWrite(pin3, HIGH);
    delay(1000);
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, LOW);
    digitalWrite(pin3, LOW);
    delay(500);
}

```

# Answer
You could look at this example, which fades an LED using PWM.

https://www.arduino.cc/en/Tutorial/Fading

Basically you use `analogWrite` to control the output of the pins with finer resolution, 0-255 rather than 0-1. Only certain pins support PWM, they should be marked on your board. You just need to extend the example to support your LED. (Put the resistor on the common pin)
> 4 votes

# Answer
```
int color_set = 0;    //set to red first
int wait_fade = 1000 // delay time in ms.  1000ms is equal to 1sec

// set the color for all the LEDs based on the color code
void setcolor(int colorcode) {

  for (int i = 0; i < LED_COUNT; i++) {
    // instead of setting the color all at once we're going to step through each LED to show how to set them individually
    switch(colorcode) {
      // We're going to pass a CRGB here,
  case 0: leds[i] = CRGB(255, 0 , 0); break; // red

  case 1: leds[i] = CRGB(255, 127, 0); break; // orange

  case 2: leds[i] = CRGB(255, 255, 0); break; // yellow

  case 3: leds[i] = CRGB(0, 255, 0); break; // green

  case 4: leds[i] = CRGB(0, 255, 255); break; // cyan

  case 5: leds[i] = CRGB(0, 0, 255); break; // blue

  case 6: leds[i] = CRGB(75, 0, 130); break; // indigo

  case 7: leds[i] = CRGB(148, 0, 211); break; // violet
}
  }
     LEDS.show();
    }
// we'll make the color fade in and out by setting the brightness
void pulse(int wait_fade) {
  // let's fade up by scaling the brightness - in general, brightness shouldn't go above 93, so the strip won't draw too much power.
  // Oh, and 93 is plenty bright!
  for(int scale = 0; scale < 93; scale++) {
    LEDS.setBrightness(scale);
    LEDS.show();
    delay(wait_fade);
  }
  // now let's fade down by scaling the brightness
  for(int scale = 93; scale > 0; scale--) {
    LEDS.setBrightness(scale);
    LEDS.show();
    delay(wait_fade);
  }
}

// this is the main loop where we call the other functions.
void loop() {
  int waiting_time = 10; //time in ms for color scaling
  setcolor(color_set);  //we call our color-set routine
  pulse(waiting_time); //now we make it fade in and out
  color_set++;        //next color
  color_set = color_set % 8; // number of color modulus, remember it's 0 based.
}

```

because there are so many different microcontrollers, i left it basic, and you only need to define `color_set` as a integer and then the `setcolor()` loop, as you can see in the main loop we pass the parameter color\_set from our *integral* 8 colors. here is my complete arduino setup:

```
#include <FastLED.h>

#define LED_COUNT 96 // number of LEDs!
struct CRGB leds[LED_COUNT]; // this struct contains 60 CRGB values.

#define PIN_BUTTON 10
#define PIN_IO_A   7
#define PIN_IO_B   11
#define PIN_SIGNAL 13
#define PIN_INPUT  10

int color_set = 0;   // set to red
int wait_fade = 1000 // delay time in ms.  1000ms is equal to 1sec
// first, let's get ready to blink using some FastLED routines
// take a look at the FastLED example called Fast2Dev for more usage info
void setup()
{
  LEDS.addLeds<WS2812B, PIN_SIGNAL, GRB>(leds, LED_COUNT); // this configures the Board - leave as is.
  LEDS.showColor(CRGB(0, 0, 0)); // set the color for the strip all at once.
  LEDS.setBrightness(0); // start out with LEDs off
  LEDS.show(); // you'll always need to call this function to make your changes happen.
}

// set the color for all the LEDs based on the color code
void setcolor(int colorcode) {

  for (int i = 0; i < LED_COUNT; i++) {
    // instead of setting the color all at once we're going to step through each LED to show how to set them individually
    switch(colorcode) {
      // We're going to pass a CRGB here,
  case 0: leds[i] = CRGB(255, 0 , 0); break; // red

  case 1: leds[i] = CRGB(255, 127, 0); break; // orange

  case 2: leds[i] = CRGB(255, 255, 0); break; // yellow

  case 3: leds[i] = CRGB(0, 255, 0); break; // green

  case 4: leds[i] = CRGB(0, 255, 255); break; // cyan

  case 5: leds[i] = CRGB(0, 0, 255); break; // blue

  case 6: leds[i] = CRGB(75, 0, 130); break; // indigo

  case 7: leds[i] = CRGB(148, 0, 211); break; // violet
}
  }
     LEDS.show();
    }
// we'll make the color fade in and out by setting the brightness
void pulse(int wait_fade) {
  // let's fade up by scaling the brightness - in general, brightness shouldn't go above 93, so the strip won't draw too much power.
  // Oh, and 93 is plenty bright!
  for(int scale = 0; scale < 93; scale++) {
    LEDS.setBrightness(scale);
    LEDS.show();
    delay(wait_fade);
  }
  // now let's fade down by scaling the brightness
  for(int scale = 93; scale > 0; scale--) {
    LEDS.setBrightness(scale);
    LEDS.show();
    delay(wait_fade);
  }
}

// this is the main loop where we call the other functions.
void loop() {
  int waiting_time = 10; //time in ms for color scaling
  setcolor(color_set);  //we call our color-set routine
  pulse(waiting_time); //now we make it fade in and out
  color_set++;        //next color
  color_set = color_set % 8; // number of color modulus, remember it's 0 based.
}

```

A lot of the code is commented. I use FastLED too. If you have any questions please let me know.
> -1 votes

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


# Question
Title: How to use ESP8266 Pin D3 / GPIO 0 and D8 / GPIO 15 properly
I am using WeMos D1 Mini Pro to control multiple relays. I found out that during start up the relay connected to pin D3 and D8 would switch between on and off a couple times in a very short interval. I found out that the two pins are related to boot loader configuration.

Question is: Is there any way to prevent the relay from "blinking"? Is there a way to disable the relay output until boot loader finish it's stuff? Because this behavior only occur once every boot up.

# Answer
> 1 votes
A 74HC244 can be used to buffer up to 8 outputs and isolate them at will from the ESP8266. It can also be used for inputs as well if you connect gates the other way around. One additional IO line is required to control it.

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


title: Powering via an I/O Line

text:
# Question
Title: Powering via an I/O Line
I have an SPI 128x64 OLED display. Is it safe to power this display's VCC from a digital I/O pin? I would like to do this so I can connect it flush to my arduino's header, and so I can control the power going to the display for a "low power" sleep mode.

Thanks for any responses.

# Answer
> 1 votes
Unlikely. An IO pin can only provide 25mA sustained, and 40mA peak. A display is likely to require more than that. However check the datasheet for the display. If by chance it should not need more than 25mA maximum (all pixels white) then yes it may be possible.

# Answer
> 1 votes
Adafruit model. monochrome 1.3" 128x64 OLED display (similar to yours, I assume):

> Display current draw is completely dependent on your usage: each OLED LED draws current when on so the more pixels you have lit, the more current is used. They tend to draw ~25mA or so in practice but for precise numbers you must measure the current in your usage circuit

To be safe, you can use one pin to control a power switch for the display.

---
Tags: arduino-mega, pins, spi, display, digital
---


title: Using a separate power supply?

text:
# Question
Title: Using a separate power supply?
I'm new to the operation and applications of the arduino and have a question. I would like to run 6 x 4 bit seven segment displays from an arduino controller. How do I connect an external supply to the displays to ensure I don't overload the arduino please?

Regards

# Answer
> 1 votes
Here's a tutorial from Sparkfun that shows how to drive an LED using a transistor to switch the LED. Where the transistor is connected to +5v, that should be to your *external* 5v supply. The pin labeled "Control" is connected to one of your Arduino pins. Connect the external supply's ground to the Arduino's ground.

Done this way, the Arduino's pin driver only needs to supply enough current to switch the transistor; the current to power the LED is provided by your external power supply.

---
Tags: power
---


# Question
Title: Problem with uploading my sketch to my Arduino
I chose the correct COM port but it won't upload.

Arduino: 1.8.3 (Windows 10), Board: "Arduino Leonardo"

```
Sketch uses 5252 bytes (18%) of program storage space. Maximum is 28672 bytes.
Global variables use 228 bytes (8%) of dynamic memory, leaving 2332 bytes for local variables. Maximum is 2560 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:713)
    at processing.app.SketchController.exportApplet(SketchController.java:686)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2149)
    at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port 'COM4'.
    at processing.app.Serial.touchForCDCReset(Serial.java:99)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:93)
    ... 6 more
An error occurred while uploading the sketch
Exception in thread "Thread-124" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:123)
    at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:106)
    at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:682)
    at processing.app.Base.onBoardOrPortChange(Base.java:1297)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2179)
    at java.lang.Thread.run(Thread.java:745)

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

```

# Answer
> 2 votes
This is the relevant bit in your error output:

```
Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.

```

Is your Leonardo on COM4, or some other port? Does some other program have that port open?

# Answer
> 0 votes
I don't see any trivial solution from the error log, but you can try one or more of the following items:

* Unplug and replug the USB cable (to check if the connection is ok)
* Change your USB cable in another USB port from your computer
* Restart computer
* Change USB cable
* Try another Arduino (if you have two megas, or change to Uno if possible), just to check for uploading
* Reinstall Arduino

---
Tags: arduino-leonardo, sketch, uploading
---


title: Connecting esp8266 using Arduino

text:
# Question
Title: Connecting esp8266 using Arduino
I am trying to connect to esp8266 using Arduino UNO. There are various things on the internet having mixed information and hence I am seeking some clarity.

I followed these instructions, but could not get to connect to ESP8266 using AT command. http://cordobo.com/2300-flash-esp8266-01-with-arduino-uno/

I have following questions:

* Can I connect ESP8266 directly to Tx/Rx without voltage divider or level shifter? I also suspect that the voltage divider connections are wrong. As per my understanding, the Tx from Arduino should be divided, and the divider output should be connected to ESP8266.
* When I connected the shield as described, the shield gets hot. Is there any way to conclude if the shield is damaged or not?
* When I connect the device using voltage divider the blue LED on the shield also lights up. Without divider, it does not light up. What is the significance of the blue LED?

**Hardware**

ESP8266-01 pinout

Circuit using voltage divider

Circuit without voltage divider

# Answer
> 1 votes
There are a number of issues with the tutorial you've listed there.

Firstly, a voltage divider is very highly recommended as the ESP8266 cannot handle more than 3.3V, however, the connections for the voltage divider in the tutorial you linked to are the wrong way round (as you suspected).

Secondly, you cannot power the ESP8266 directly from the Arduino, as the power requirements are higher than the Arduino's on board 3.3V regulator. A separate power supply or regulator is recommended. This might be cause of it getting hot (the onboard regulator maybe - but I can't be sure as there is not enough information from your initial post as to exactly what is getting hot).

There are 2 LED's on the ESP8266 shield (the one used in the tutorial you've linked to) one is power and the blue one is wifi communication.

The other potential issue with the tutorial you've linked to is that they have used Arduino pins 0 and 1 to connect to the ESP8266 - while this will work, the problem is that the Arduino uses pins 0 and 1 to communicate over USB with a computer, which means that in in that configuration you cannot use Serial monitor to send/receive data.

# Answer
> 0 votes
Some ESP boards are 5v tolerant on the digital pins, some aren't. So it depends on what board you have, I don't think the one in the tutorial is.

If you are using serial to communicate the a resistor divider will not work. You need a proper level shifter, which you should be able to get for less than a $1. Remember you will probably need to down shift the Tx from the Arduino and Up Shift the RX to the Arduino.

# Answer
> 0 votes
I'm working with ESP-12S which use ESP8266 recently.

My main goal is to use UART-WIFI passthrough mode, so I only need **VCC, RX, TX, GND**.

These are the steps I take:

1. Use USB to TTL converter to link WIFI module to PC for WIFI configuration. (two USB converter were used for power issue)

2. On PC I used *minicom* to open the USB serial. Use AT commands(espressif.com/sites/default/files/documentation/4a-esp8266\_at\_instruction\_set\_en.pdf) to config WIFI module:

AT+RESTORE // restores the factory default settings

AT+GMR // checks version information

AT+RST // restarts the module

AT+CWMODE\_DEF=1 // set station mode

AT+CWJAP\_DEF="APname","password" // connect to AP

AT+CWDHCP\_DEF=1,1 // set station mode with DHCP

AT+CWAUTOCONN=1 // auto connect

AT+CIFSR // show local IP

AT+PING="10.0.1.1" // ping network gate

AT+CIPSTART="TCP","10.0.1.116",2048 // setup TCP to server

AT+CIPMODE=1 // set UART-WIFI passthrough mode

AT+CIPSEND // enter UART-WIFI passthrough mode

AT+SAVETRANSLINK=1,"10.0.1.116",2048,"TCP" // save configuration in WIFI module
3. After configuration, hook WIFI module to Arduino (actully I'm using stm32, but it's the same) UART pins. When power on, the WIFI module will automatically connet to AP and setup TCP link to server and enter UART-WIFI passthrough mode.

4. If you want to exit UART-WIFI passthrough mode, send '+++' on UART end, without '\r\n' and '+++' must be sent continuously (type '+++' in minicom won't work).

as for your questions,

1. Voltage divider is used, but pay attention to RXD TXD link problem. (RXD to TXD, TXD to RXD)
2. My WIFI module also gets hot, but working properly.
3. I don't know the blue LED's function, but I did remember reading about it some where, maybe in the documentation.

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


# Question
Title: ESP8266 returns whatever is sent through Arduino serial
I am a newbie and working on a kind of WiFi-controlled vehicle (car or maybe hovercraft later). My ESP8266 repeats the commands I send. For example, AT gives AT, AT+GWR gives AT+GWR, dabdabik gives dabdabik, etc.

I am using an Arduino Uno to send commands, as I don't have FTDI related stuff (USB to Serial Converter). I use AA cells for power supply (1.5v\*2=3v). I don't even have 3.3 volt direct supply. I am using the Arduino IDE Serial Monitor. I connected the Arduino's TX to the ESP8266's RX via a voltage divider (1.66K Ohm(TX) and 1.66K Ohm (GND)-\>3.29 Ohm(RX)).

My connections are:

```
ESP8266----------------Arduino Uno
TX---Voltage divider---RX(d0)
RX---------------------TX(d1)
GND--------------------GND
VCC-------**3V**
CH_PD-----**3V**

```

Sometimes it gives garbage otherwise it just repeats (weird). Garbage ONLY changes if baud rate is changed.

I flashed it (it seems) with the AT 9.5.2 firmware. Flashing works rarely ONLY with TX to TX connected directly without a voltage divider.

I tried as much as I could after searching the web and ESP8266 forum but still couldn't solve problem.

Please help. I am a student in a small town (Manipal) in Southern India so no good stores nearby and I don't want to buy FTDI or anything online. I am a bit new to electronics, but I am a C++ programmer and student.

UPDATE: I noticed after some resets that it gives full garbage to longer commands most of the time, whereas two-letter commands give partial garbage. For example AT gives IT,TT,OT,etc.

There is no coding. I am sending the commands directly via Arduino hardware serial pins (rx,tx) and a bare minimum program.

# Answer
I noticed when testing my ESP8266 using the Arduino IDE serial console that ending with a `CR` repeated what was sent, a `NL` executed the command and combination of the two yielded a combination of the two behaviours. This could have just been the firmware on mine (it seemed to be non-standard), but it is possible that the behaviour is similar on yours. If you are using `CR` & `NL`, it would explain repetition. However, I can't explain commands not executing, or executing abnormally.
> 1 votes

# Answer
When I recieved my first ESP I struggled for weeks trying to get it working. First, the voltage divider is a good thing for its longevity but I got it working without it.

Next about baudrate, mine sent some data at startup on 76800 baud then would work on 9600 baud. You might want to check that out for the garbage you're seeing.

Finally, it might be related to a power draw problem. The ESP has 400mA peaks, this is high for an Arduino and even for a 3.3v USB serial programmer. I had to use a 1A breadboard power supply to actually get it to work. Before buying anything you should try putting a big (220µF or more) capacitor in parallel on the 3.3V power.
> 0 votes

# Answer
1. AT commands must end with '\r\n'.
2. 'ATE'commands can enable/disable echo. (ATE0: disable, ATE1: enable)
3. AT commands documentation: http://espressif.com/sites/default/files/documentation/4a-esp8266\_at\_instruction\_set\_en.pdf
> 0 votes

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


# Question
Title: can we use Lm317 1.25 ref for ext. reference of arduino
I m trying to give ext ref. To Arduino using lm317 1.25 ref. I tried to do it. Iswt this voltage in programme too But when I run it it was just displaying 1.25 And der was no variation as I varie the resistance of potentiometer which is connected to A0 So plz help me..... My Arduino chip is Atmega 8A

# Answer
yes but you have to use the analogReference(EXTERNAL); command otherwise it will short the default VCCref volatage with the external (i assume this will cause damage.. dunno never done that. yet...) also if you use a 1.25v reference just remember that that will be the maximum voltage you can measure up to. theres a couple of things you can do

1 use a voltage devider circuit to drop the max voltage out of your sensor(potentiometer) down to about 1.25v

2 put a series resistor betweent vcc and the positive terminal of your potentiometer (creating a voltage devider between the resistor and the full resistance of the potentiometer)

3 and probably the easiest connect the positive of the potentiometer to the lm317 /reference pin so that its output will be between Aref and GND this is the best option as it will be the most stable as its output will be in propotion to any fluctuation of the lm317

as in 3. the same can be done if using the internal Vref conect the pot to Aref (but remember that it has a limited current output so be carefull not to draw too much by using low resistance pots or many in parallel)
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to use #define in a library I'm trying to write?
I have written simple code to enable toggling of `serial.print` debug data.

```
  #define DEBUG
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

```

Then I can just call `DEBUG3("words",value,"words");` anywhere in the sketch and it will automatically print out the text, int, strings, etc with a single space between and automatically go to next line etc etc.

Just define the correct number of fields to print and separate using commas.

If I want to turn off debug then I just comment out `#define DEBUG` at the top.

Now the issue is I don't want to copy in this code every time I want to use it, so it makes sense to make it a library so that I can just call something like:

```
#include <SERIAL_DEBUG.h>
#define DEBUG     (or //#define DEBUG) //to enable or disable

```

The reason being that sometimes I might want to print up to 10 things on a single line (not very often but it could happen).

This is my first library attempt and I'm having a hard time finding any information on how I would go about setting up the .h and .cpp files for this type of `#define DEBUG(x) Serial.println(x)` and the `#define DEBUG (from sketch)` parts.

# Answer
Anything in a header file that is included with `#include` is literally pasted into the file at the point of the `#include`.

So anything in your sketch you want to place into a header file you can just place it in a header file and include that file *at the same location where the original code was*.

So you can have a header file `debug.h`:

```
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

```

And include that in your sketch at the right location:

```
#define DEBUG
#include "debug.h"

```

Note that the `#define DEBUG` *must* come before the `#include`. Remember: the `#include` is replaced by the content of the included file, so after preprocessing you end up with exactly what you had before in your sketch:

```
  #define DEBUG
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

```

The file can be in the same location as the sketch (in which case you should use `#include "debug.h"` or in a library folder (`Arduino/libraries/debug/debug.h`) in which case you should include it with `#include <debug.h>`. In the Arduino IDE it actually makes little or no difference which type of `#include` you use, but it does serve as a visual reminder that this is either a header included with the sketch (`""`) or an external library or system header (`<>`).
> 1 votes

# Answer
Not a direct answer to your question, but I would suggest a different approach based on streaming output, as described in the Arduino Playground: Adding Streaming (insertion-style) Output. In a nutshell, you define the `<<` operator for `Serial` (and any other object that inherits from `Print`) in a way that allows you to write things like:

```
Serial << "My name is " << name << " and I am " << age << " years old.";

```

Now you can define a `Debug` object which would be, depending on whether you want debugging output or not:

* an alias to Serial
* a dummy object that just discards its input.

Example:

```
#define DEBUG_ON

// From https://playground.arduino.cc/Main/StreamingOutput
template<class T> inline Print& operator<<(Print &obj, T arg)
{ obj.print(arg); return obj; }

#ifdef DEBUG_ON
# define Debug Serial
#else
class DummyStream {
public:
    template<class T> DummyStream& operator<<(T arg)
    { (void) arg; return *this; }
} Debug;
#endif

void setup()
{
    const unsigned long BAUDRATE = 9600;
    Serial.begin(BAUDRATE);
    Debug << "Serial port open at " << BAUDRATE << " bps\r\n";
}

```
> 1 votes

---
Tags: serial, library, debugging, debug
---


title: Stopping motor DC with 2 limit switches

text:
# Question
Title: Stopping motor DC with 2 limit switches
I try to build an automatic roof with rain sensor input, when it's rain the roof then closed pulled by DC motor on the tracks and activate a buzzer. When it reach the end (limit switch pressed) then the motor stopped and buzzer off. And when the rain stopped, motor will turning again to open the roof until the second limit switch pressed to stop the DC motor.

I have try to make my own program but it have an error, when it's has no rain detected the motor spin to close the roof and stop when limit switch pressed (LOW logic), but when rain detected the buzzer turned on but the motor doesn't spin at all. Here is my code, I'm using L293D for motor driver and using its enable pin.

```
void setup() {
  digitalWrite(enable_motor, HIGH);
  digitalWrite(motor_open, LOW);
  digitalWrite(motor_close, LOW);
  digitalWrite(alarm, LOW);
}

void loop() {
  if (analogRead(rainSensor) < 650){
    digitalWrite(alarm, HIGH);
    digitalWrite(motor_close, HIGH);
    digitalWrite(motor_open, LOW);
  }
  else if (digitalRead(stop_close) == LOW){
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
  }
  else if (analogRead(rainSensor) > 850){
    digitalWrite(alarm, LOW);
    digitalWrite(motor_close, LOW);
    digitalWrite(motor_open, HIGH);
  }
  else if (digitalRead(stop_open) == LOW){
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
  }
  else {
    digitalWrite(enable_motor, HIGH);
    digitalWrite(alarm, LOW);
  }
}

```

Can I use If-Else logic? Or I make a mistake?

# Answer
> 1 votes
Your logic is a bit off. For example, when it is raining and `rainSensor < 650`, only that part of the `if` gets executed and the `else if` parts never happen.

You could just wait for the roof to open/close in a loop. Also, you will find it helpful to break your code into smaller functions. (I'm not sure what the `enable_motor` pin is for, so that part may need fixing).

```
// This function determines the current status of the roof
enum {OPEN, CLOSED, OPENING, CLOSING, UNKNOWN};
byte get_roof_status()
{
    if (digitalRead(stop_close) == LOW) return CLOSED;
    else if (digitalRead(stop_open) == LOW) return OPEN; // Fixed typo
    else if (digitalRead(motor_open) == HIGH) return OPENING;
    else if (digitalRead(motor_close) == HIGH) return CLOSING;
    return UNKNOWN;
}

// Helper functions
void open_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_close, LOW);
    digitalWrite(motor_open, HIGH);
    // Loop until roof is open
    while (OPEN != get_roof_status()) /* NULL */;
    stop();
}
void close_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, HIGH);
    // Loop until roof is closed
    while (CLOSED != get_roof_status()) /* NULL */;
    stop();
}
void stop() {
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, LOW);
}

void setup() {
  // Set the pinmodes
  pinMode(enable_motor, OUTPUT);
  pinMode(motor_open, OUTPUT);
  pinMode(motor_close, OUTPUT);
  pinMode(stop_close, INPUT_PULLUP);
  pinMode(stop_open, INPUT_PULLUP);
  pinMode(alarm, OUTPUT);

  digitalWrite(enable_motor, HIGH);
  digitalWrite(motor_open, LOW);
  digitalWrite(motor_close, LOW);
  digitalWrite(alarm, LOW);
}

void loop() {
  // This function is much simpler now
  if (analogRead(rainSensor) < 650) {
    close_roof();
  }
  else if (analogRead(rainSensor) > 850){
    open_roof();
  }
}

```

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


# Question
Title: usart sketch uploaded using makefile gives unusual behaviour
This is a simple usart program in avr c which just transmits a character.

```
#include <avr/io.h>
#include <util/delay.h>
#define F_CPU 16000000UL
#define BAUD 9600
#define BAUD_PRESCALLER ((F_CPU / (BAUD * 16UL)) - 1)
void send_val(unsigned char);
int main() {

UBRR0H = (uint8_t)(BAUD_PRESCALLER>>8);
UBRR0L = (uint8_t)(BAUD_PRESCALLER);
UCSR0B = (1<<TXEN0);
unsigned char x = 'B';
while(1) {

    send_val(x);
    _delay_ms(1000);
}

return 0;
}

void send_val(unsigned char v) {
while(!(UCSR0A & (1<<UDRE0)));
UDR0 = v;

}

```

when I upload this code via the Arduino IDE, everything is fine and the code works as expected.The LED labeled "L" on the PCB is still.

but, when I upload the code using the following Makefile, the code uploads successfully but the outcome is unexpected. I see a weird character(see EDIT) and the LED "L" blinks a couple of times in that 1 sec delay.

```
CC=avr-gcc
OBJCOPY=avr-objcopy

CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

led.hex: led.elf
    ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

led.elf: led.o
    ${CC} -o led.elf led.o

install: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

```

I referred the Schematics and the led is connected to SCK but I don't understand why the makefile is causing it to trigger. that blinking of LED is what I think is causing the issue. Does the IDE have some other specific flags while uploading the code or am I committing some silly mistake?

EDIT: I wrote a small program to see the values in the device node /dev/ttyACM0. the ASCII value of the weired character(looks like a question mark) is actually 255.

another issue I noticed is that when I touch the solder beneath the pin 13 (only pin 13) the led L goes off!

As led L is connected to pin 13 I thought this is some hardware issue with my board but then I uploaded the blink led example code, touched the solder and everything is fine.

what could be the actual issue? this is getting mysterious.

# Answer
> 1 votes
The `-mmcu=atmega328p` compiler flag is needed not only for the compile phase, but also for the link phase. Otherwise the linker will not know which CRT (C run time) to link with your program, and it will link none. The CRT is responsible for things like initializing the stack pointer, clearing `r1` (as required by the AVR calling convention) and calling your `main()`.

**Edit**: the following simplified Makefile should work if you have a modern version of avrdude that understands ELF files:

```
CC     = avr-gcc
MCU    = atmega328p
CFLAGS = -Os -DF_CPU=16000000UL -mmcu=${MCU}
PORT   = /dev/ttyACM0

led.elf: led.c
    ${CC} ${CFLAGS} $< -o $@

install: led.elf
    avrdude -c arduino -p ${MCU} -P ${PORT} -b 115200 -U $<

```

Otherwise you can keep your rules for led.elf → led.hex → install.

---
Tags: arduino-uno, serial, uploading, arduino-makefile
---


# Question
Title: Charlieplexing 30 LED sections with a max of 27 LEDs at the same time?
So basically, I'm trying to make a digital wall clock and using digital numbers, I have 7 sections of LED's per number, 4 numbers and one section for the colon in between them. A total of 30 sections. The colon will toggle every second so the the most possible simultaneously glowing sections is 27. That's because of the time 08:08. Is there any way to make this work with an arduino? Possibly by Charlieplexing the arduino into 30 sections, using 6 pins. Or is there something out there that has 30 pins!?

The problem of course with charlieplexing, is that you need it to become rapid pulses. I'm sure I'm going to need some help with this, and also with laying out a schematic.

To be clear, this is how the led sections are going to be laid out. I also know I'm going to need an npn transistor for every single one of them. the biggest section uses 20 LEDs.

Thanks!

# Answer
I would consider 74HC595N's. These are shift registers, which can control 8 'outputs' using less pins on your Arduino.

These are very cheap (buy them per 10) and you can daisy chain 4 of them, having 32 outputs, using only 5 pins of your Arduino. This would fit perfectly with your 30 sections.

Each of the 30 outputs can be used to control a transistors to control one LED sections.

See for an example for using shift registers with the Arduino: ShiftOut

Also you might need this: ULN2803 darlington drivers for each output (4 total).
> 1 votes

---
Tags: led
---


title: changing device signature in avrdude

text:
# Question
Title: changing device signature in avrdude
I am trying to burn bootloaders to Atmega2560V and when I hit burn bootloaders it shows me this error

> avrdude: Device signature = 0x1e9803 avrdude: Expected signature for ATmega2560 is 1E 98 01

I know this device should have 0x1e9801, But I don't know why it's showing me this error.

I tried my luck by starting threads at AVRFREAKS but no joy.

One of my friend told to try changing the device signature in the avrdude from 0x1e9801 to 0x1e9803 for a temporary try.

How can I do that.? please please please anyone help.

Thanks

# Answer
You should have, somewhere in your hard drive, a file named avrdude.conf. My copy of the file has the following lines:

```
#------------------------------------------------------------
# ATmega2560
#------------------------------------------------------------

part
    id               = "m2560";
    desc             = "ATmega2560";
    signature        = 0x1e 0x98 0x01;
    ...

```

Try changing the line with `signature`. Alternatively, you could make a new entry for your MCU like this:

```
#------------------------------------------------------------
# ATmega2560V
#------------------------------------------------------------
# Identical to  ATmega2560 but for the signature

part parent "m2560"
    id        = "m2560v";
    desc      = "ATmega2560V";
    signature = 0x1e 0x98 0x03;

```
> 2 votes

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


title: Multimaster I2C with same address

text:
# Question
Title: Multimaster I2C with same address
I use the Wire Library and need to have multi-master setting. I see multi-master examples, where the masters have their own ID's -- which make sense.

Now I have just connected three devices on the bus with the same ID (for example `0x05`) and they can communicate! Every node can listen to all traffic, which is not common but this was exactly what I want.

The question is: Will I have trouble in the future? Is my setup something like "multi-slave"?

# Answer
```
const byte MY_ADDRESS = x;  // where x is whatever unique address you like

byte RxByte[32]  //32 byte buffer

void setup() {
  //insert unique ddress
  Wire.begin(MY_ADDRESS);

// this line allows the arduino to listen for i2c broadcast at address 0

TWAR = (MY_ADDRESS << 1) | 1;
//set up a receive handler
 Wire.onReceive(receive_data);

then call
Wire.beginTransmission (0)  //transmit broadcast so all devices will receive

Wire.write( address of destination) // make the first byte the destination

Wire.endTransmission ();

then you need a receive handler

void receive_data() {
//use a buffer to temporarily store the data

for ( int d = 0; Wire.available() > 0 ;d++){

RxByte[d] = Wire.read();} // READ WIRE BUFFER UPTO 32BYTES, INTO AN ARRAY
datareceived = 1;

//then test if it was for this device
if (RxByte[0] == MYADDRESS){ do somthing with RxBytes[1-31];}
else {}

```

I use this extensively its very handy and works well I have a complex transmission table which has a 4 byte header and the rest of the bytes can be used as data send

destination, myaddress, a command, and how many data bytes to follow

---

Addendum to Original answer. below is a complete working example.

//so the basics of the tranmission table are the first 4 bytes (ie Rx or Tx byte 0-3 depending on if we are talking about the sender or recipient) //are used as a header 0= recipient (0 for broadcast. or address) 1= senders address 2= is the command (ie tells the recipient what to do) //and 4= the number of data bytes which follow in the packet //not all of these need to be specified at any time but its usefull to have a structure to follow at each end which never changes //copy and past this upload to 2 arduinos connected by i2c change the 2 addresses and it should work. its a n example of how data can be moved around in a multi master situation that should hopefully give you some ideas. it looks complicated but half of it is just generating some example data and triggering method and the transmit part is repeated 3 times to send out different data.. you should be able to create a more general purpose transmit block for your application

to send data just attach a button or wire to pin 2 directly to ground

watch the 2 serial windows

```
#include <Wire.h>
//device address  MAKE DIFFERENT FOR EACH

const byte MY_ADDRESS = 20;
const byte PARTNER_DEVICE = 25;

// transmission table stuff
byte RxByte[32]; //setup a receive buffer to hold data
byte TxByte[32]; //setup a transmit buffer to hold data
byte datareceived;

// stuff to generate some data
const int Sensor1 = A0;
byte SensorVal1 = 0;

//stuff to debounce pin 2
const byte digitalpin = 2;
byte pinstate = 0;
byte lastpinstate = 0;
unsigned long checktime = 0;
const byte debouncetime = 50;

// timer
unsigned long timing_loop = 5000;

void setup() {
  Wire.begin (MY_ADDRESS);
  TWAR = (MY_ADDRESS << 1) | 1;                                                      // ENABLE BROADCASTS TO BE RECEIVED
  Wire.onReceive(ReceiveData);     // INTERUPT ON I2C DATA RECEIVE
  Serial.begin(9600);
  pinMode (  digitalpin  , INPUT_PULLUP );// set the pin to input pullup so we can trigger the code by connecting directly to ground
  Serial.println( "READY" );
}

void loop() {
  // generate some random data

  GenRandData();
  //Serial.print(  pinstate);Serial.print( " " );Serial.println( lastpinstate );
  // debounces pin 2 so we can trigger a data broadcast
  pinstate = digitalRead (digitalpin);
  if ( pinstate != lastpinstate && millis() >= checktime) {
    if ( pinstate == 0 && lastpinstate == 1 ) {
      checktime = millis() + debouncetime;
      Serial.println( " button working" );
      REQUEST();
    }
    lastpinstate = pinstate ;
  }

  // this triggers the process data method after receive of data
  if (datareceived == 1  ) {
    datareceived = 0 ;
    ProcessData();
  }

  // 10 second timer triggers transmission of some data
  if ( millis() >= timing_loop ) {
    BROADCAST();
  }
}
void GenRandData() {
  // this just reads analog0 and maps it to a byte then sequentially shifts the transmit buffer
  SensorVal1 = random(255);
  TxByte[7] = TxByte[6];
  TxByte[6] = TxByte[5];
  TxByte[5] = TxByte[4];
  TxByte[4] = SensorVal1;
}

void ReceiveData() {
  // READ AVAILABLE BYTES INTO 32BYTE BUFFER (while data is available)
  for ( byte d = 0; Wire.available() > 0 ; d++) {
    RxByte[d] = Wire.read();
  }
  //set a trigger event
  datareceived = 1;
  Serial.println( "receive" );
}

void ProcessData() {
  Serial.println( "process" );
  // check what the data is an who its for then do something with it (RECEIVE TABLE)
  if (RxByte[0] == MY_ADDRESS) { // for this device
    switch (RxByte[2]) {
      case 1:       Serial.print("RECEIVED DATA FOR THIS DEVICE, = "); Serial.println( RxByte[4] ); break;
      case 255:       Serial.println("RECEIVED A REQUEST FOR DATA, SENDING READ FROM  > Sensor1"  ); ActAsMaster();              break;
      default:      Serial.print("D-Type byte = error"); Serial.println(RxByte[2]);                   break;
    }
  }

  else if (RxByte[0] == 0) {       //handle broardcast
    Serial.print( "RECEIVED BROADCAST FROM DEVICE = " ); Serial.println( RxByte[1] );
    Serial.print( "DATASIZE = " ); Serial.print( RxByte[3] ); Serial.println( " Bytes" );
    Serial.print( "DATABYTE 1 = " ); Serial.println( RxByte[4] );
    Serial.print( "DATABYTE 2 = " ); Serial.println( RxByte[5] );
    Serial.print( "DATABYTE 3 = " ); Serial.println( RxByte[6] );
    Serial.print( "DATABYTE 4 = " ); Serial.println( RxByte[7] );
    Serial.println( "DONE" );
  }
  Serial.println(  );
}

void BROADCAST() {
  // this is transmission table to send data to everyone
  Serial.println("Sending broadcast");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (0);                       // broadcast
  Wire.write(0);                                    // ADDRESS =0 BROARDCAST
  Wire.write(MY_ADDRESS);                           // SEND my address
  Wire.write(0);                                    // DATA TYPE CODE
  Wire.write(4);                                    //number of bytes being sent
  Wire.write(TxByte[4]);                            //data
  Wire.write(TxByte[5]);                            //data
  Wire.write(TxByte[6]);                            //data
  Wire.write(TxByte[7]);                            //data
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;
    Serial.println( "fail" );
    goto Tx;
  }
  //reset timer to run this again
  timing_loop = millis() + 10000 ;
  Serial.println(  );
}

void ActAsMaster() {
  //this is transmission table to send data to specific device OR return a result of a task
  Serial.println("Sending data");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (RxByte[1]);               //the return address
  Wire.write(RxByte[1]);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(1);                                  // DATA TYPE CODE
  Wire.write(1);
  Wire.write(SensorVal1);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );

}
void REQUEST() {
  //this is transmission table to send data request of partner device
  Serial.println("Sending request");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (PARTNER_DEVICE);               //the return address
  Wire.write(PARTNER_DEVICE);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(255);                                  // DATA TYPE CODE (MASTER ADDRESS)
  Wire.write(0);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );
}

```
> 1 votes

---
Tags: i2c
---


# Question
Title: AT+CENG=2,0 What type is the returning LAC?
The `AT+CENG=2,0` command is giving me this result:

> +CENG: 0,"0794,48,00,510,10,53,7944,10,00,36e3,255"

My LAC is `36e3` but what is the type? (Int, Double, byte, string)?

I get this code to translate cell ID and LAC into lat long:

```
class GMM {
  public static byte[] PostData(int MCC, int MNC, int LAC, int CID) {
    /* The shortCID parameter follows heuristic experiences:
     * Sometimes UMTS CIDs are build up from the original GSM CID (lower 4 hex digits)
     * and the RNC-ID left shifted into the upper 4 digits.
    */
    byte[] pd = new byte[] {
      0x00, 0x0e,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00,
      0x00, 0x00,
      0x00, 0x00,
      0x1b,
      0x00, 0x00, 0x00, 0x00, // Offset 0x11
      0x00, 0x00, 0x00, 0x00, // Offset 0x15
      0x00, 0x00, 0x00, 0x00, // Offset 0x19
      0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, // Offset 0x1f
      0x00, 0x00, 0x00, 0x00, // Offset 0x23
      0x00, 0x00, 0x00, 0x00, // Offset 0x27
      0x00, 0x00, 0x00, 0x00, // Offset 0x2b
      0xff, 0xff, 0xff, 0xff,
      0x00, 0x00, 0x00, 0x00
    };
    Console.WriteLine(pd.Length);
    bool isUMTSCell = ((Int64)CID > 65535);
    if ((Int64)CID > 65536) /* GSM: 4 hex digits, UTMS: 6 hex digits */
      pd[0x1c] = 5;
    else
      pd[0x1c] = 3;
    pd[0x11] = (byte)((MNC >> 24) & 0xFF);
    pd[0x12] = (byte)((MNC >> 16) & 0xFF);
    pd[0x13] = (byte)((MNC >> 8) & 0xFF);
    pd[0x14] = (byte)((MNC >> 0) & 0xFF);
    pd[0x15] = (byte)((MCC >> 24) & 0xFF);
    pd[0x16] = (byte)((MCC >> 16) & 0xFF);
    pd[0x17] = (byte)((MCC >> 8) & 0xFF);
    pd[0x18] = (byte)((MCC >> 0) & 0xFF);
    pd[0x27] = (byte)((MNC >> 24) & 0xFF);
    pd[0x28] = (byte)((MNC >> 16) & 0xFF);
    pd[0x29] = (byte)((MNC >> 8) & 0xFF);
    pd[0x2a] = (byte)((MNC >> 0) & 0xFF);
    pd[0x2b] = (byte)((MCC >> 24) & 0xFF);
    pd[0x2c] = (byte)((MCC >> 16) & 0xFF);
    pd[0x2d] = (byte)((MCC >> 8) & 0xFF);
    pd[0x2e] = (byte)((MCC >> 0) & 0xFF);
    pd[0x1f] = (byte)((CID >> 24) & 0xFF);
    pd[0x20] = (byte)((CID >> 16) & 0xFF);
    pd[0x21] = (byte)((CID >> 8) & 0xFF);
    pd[0x22] = (byte)((CID >> 0) & 0xFF);
    pd[0x23] = (byte)((LAC >> 24) & 0xFF);
    pd[0x24] = (byte)((LAC >> 16) & 0xFF);
    pd[0x25] = (byte)((LAC >> 8) & 0xFF);
    pd[0x26] = (byte)((LAC >> 0) & 0xFF);
    return pd;
  }

  public static string[] GetLatLng() {
    string[] result = new string[2];
    try {
      String url = "http://www.google.com/glm/mmap";
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(url));
      req.Method = "POST";
      int MCC = Convert.ToInt32(510); //actual data
      int MNC = Convert.ToInt32(10); //actual data
      int LAC = Convert.ToInt32(36e3); //actual data - gives error here
      int CID = Convert.ToInt32(7945); //actual data
      byte[] pd = PostData(MCC, MNC, LAC, CID);
      req.ContentLength = pd.Length;
      req.ContentType = "application/binary";
      Stream outputStream = req.GetRequestStream();
      outputStream.Write(pd, 0, pd.Length);
      outputStream.Close();
      HttpWebResponse res = (HttpWebResponse)req.GetResponse();
      byte[] ps = new byte[res.ContentLength];
      int totalBytesRead = 0;
      while (totalBytesRead < ps.Length) {
        totalBytesRead += res.GetResponseStream().Read(
        ps, totalBytesRead, ps.Length - totalBytesRead);
      }
      string r = System.Text.Encoding.UTF8.GetString(ps);
      Console.WriteLine(r);
      if (res.StatusCode == HttpStatusCode.OK) {
        short opcode1 = (short)(ps[0] << 8 | ps[1]);
        byte opcode2 = ps[2];
        int ret_code = (int)((ps[3] << 24) | (ps[4] << 16) | (ps[5] << 8) | (ps[6]));
        if (ret_code == 0) {
          double lat = ((double)((ps[7] << 24) | (ps[8] << 16) | (ps[9] << 8) | (ps[10]))) / 1000000;
          double lon = ((double)((ps[11] << 24) | (ps[12] << 16) | (ps[13] << 8) | (ps[14]))) / 1000000;
          result[0] = lat.ToString();
          result[1] = lon.ToString();
          return result;
        } else {
          return result;
        }
      } else return result;
    }
    catch (Exception ex) {
      result[0] = ex.Message;
      return result;
    }
  }
}

```

# Answer
> 2 votes
LAC is "Location Area Code" - the code assigned by the operator to a group of cells that operate as one single broadcast unit.

It is returned to you as a hexadecimal representation of an unsigned 16 bit integer.

To know where the LAC is physically located on the planet you need to look it up in a table. I believe only the operator can give you that information. OS providers like Apple and Google most likely also have access to that data through agreements with operators.

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


title: Pin 9 and 10 with different duty cycles

text:
# Question
Title: Pin 9 and 10 with different duty cycles
I want to control the contrast and backlight of an HD44780 LCD display with two PWM signals. I would like to use `PB1` and `PB2` (`Pin 9` and `Pin 10`) for this. As far as my research goes, `timer1` is responsible for the two pins. `OCR1A` and `OCR1B` are responsible for the pulse length.

With the code below I get a frequency of 7.823 kHz and a duty cycle of 88%. But it works only on `PB1`. `PB2` is still constant `0V`. I am using the AtmelStudio, therefore I don't have access to functions like `pinMode(10, Output)`

How can I have different duty cycles on pin 9 and 10?

```
#define F_CPU 16000000UL
#include <avr/io.h>

int main(void)
{
    DDRB |= (1 << DDB1) | (1 << DDB2);
    OCR1A = 900;
    OCR1B = 400;
    TCCR1A |= (1 << COM1A1);
    TCCR1A |= (1 << WGM11) | (1 << WGM10);
    TCCR1B = (TCCR1B & 0b11111000) | (1 << CS10);

}

```

# Answer
After trying a lot of things i got it working. And even the contrast is working directly on the pwm signal.

```
#define F_CPU 16000000UL
#include <avr/io.h>
void main(void){
    DDRB = 0x06;
    OCR1A = 200; //Duty cycle for PB1 ~80%
    OCR1B = 100; //Duty cycle for PB2 ~40%
    TCCR1A = 0; //Set TCCR1A to zero. We will configure it manually
    TCCR1A |= (1 << COM1A1) | (0 << COM1A0) | ( 0 << COM1B0) | (1 << COM1B1);
    TCCR1A |= (0 << WGM12) | (0 << WGM11) | (1 << WGM10);
    TCCR1B = 0; //Set TCCR1B to zero. We will configure it manually
    TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
    while(1){

    }
}

```
> 2 votes

---
Tags: arduino-uno, c++, pwm, atmega328
---


title: Is the A6 module broken?

text:
# Question
Title: Is the A6 module broken?
Hi recently I've could send some messages with the A6 GSM module, which uses **AT commands**. To switch on the board, you need to press the power button about 4 seconds or connecting the VCC pin to the PWR pin to avoid manual switching on. In this Andreas Spiess' video (minute 2:21), he recommends reset the device to give to the board a defined state. I had not done this until the device didn't work properly with some scripts. To reset it, he advises to reset the modoule. Its RST pin needs 0.70 mA and works at low level. In addition, the Arduino can not provide that current with a single pin so he uses a N-channel MOSFET (3055) to reset the board.

In my case I used a transistor (I don't know if it's NPN or PNP) and I connected the circuit like in his video. It worked! But it given **strange results** to the serial monitor (yes, I set the baud rate correctly). After reset the board it switched on automatically because it was connected the PWR pin and VCC pin. The mistery occured when I unplugged the board (even its current) and then I reconnected it again. Since that moment it doesn't work, it doesn't switch on its LED to show you that the board is working. So, can anyone explain me **why** the 3055 it's neccesary to reset the board? Can it be done using **Ohm's Law**, a digital pin and a big resistance to give to the board the 70 mA?

Thanks!

# Answer
I come across this problem too..based on what you said, i think it works like this:

The parameter you are looking for is power rating.. Arduino digital pin can only tolerate some amount of current, and im guessing it is less than 70mA..if you still do that, it is possible to damage that pin..since you want a LOW level for trigger, you can connect that RST manually to GND.. GND is also 0V just like the DIGITAL LOW, but it has no internal circuitry as of digital pin - meaning that you can sink a lot more current to GND.. If you want to be on the safe side, connect a limiting resistor(use ohm law for value), and also take note on the resistor power rating..
> 0 votes

---
Tags: gsm, arduino-pro-mini
---


# Question
Title: Esp8266-01 AT commands returns random chars and/or "ERROR"
I'm trying to make my esp8266 work with my arduino.

But when I send AT commands I get some weird symbols and some functions return "ERROR"

Here's the code I'm using.

```
#include "SoftwareSerial.h"

SoftwareSerial esp8266(6, 7); // RX, TX

void setup()
{
  Serial.begin(9600); // serial port used for debugging
  esp8266.begin(115200);  // your ESP's baud rate might be different
}

void loop()
{
  if(esp8266.available())  // check if the ESP is sending a message
  {
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      Serial.write(c);  // writes data to the serial monitor
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer

    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd);
  }
}

```

Here's the Serial Monitor:

```
AT

OK
AT+RST

OK

 ets Jan  8 2013,rst catse:2, boot lode:(3,7)

loab 0x40100000& len 1396, qoom 16
tail 4C�,kk�������e
load 0x3fge8000, len 776, room 4 tak0  t0�v�
�!jH+��
����(j5�!
,�2%1�

j
�sl��o�
Ai,Thinker Technology Co. Ltd.

invalid
AT+CWMODE?

+CWMODE:1

OK

AT+GMR

AT version;0.25.0.0(Juo  5 2015 17:27:16)
SDK version:1.0
ryJ 0

AT+CWLAP

+CWLAP:(4,"�P��R�*bj��b���*��2��*����Ҋ�b�Jj
��*A�B�br������Յź�aj��b����2j
":6�*AՉ����J
"�́������

```

The commands where, `AT`, `AT+RST`, `AT+CWMODE?`, `AT+GMR`, `AT+CWLAP`

Why am I getting this weird symbols and etc? I haven't upgraded the firmware, should I? There other commands I tried return "ERROR" or even "ERROQ"

I don't have a USB to TTL or any other board. I connected my board in the arduino with this schematic:

Cap = 10uF VolReg = LM1117 3.3v

# Answer
> 1 votes
The problem is mainly in using Serial and SoftwareSerial together. Or it can be due the esp getting less current than it requires from the Arduino(you are also damaging your Arduino!), use an external 5V source (I use my computer USB)

Why dont you directly use Serial for communication with pins 0 and 1. Just upload a blank sketch, connect Arduino Tx, Rx to esp's Tx, Rx(reverse Tx, Rx if not working). What you type into Serial will then be sent to the esp. Later if you wish to communicate to esp in sketches, use only SoftwareSerial.

Also, the esp is not 5V tolerant so you need to use a level shifter(like the cd4050 ic) or a voltage divider(less efficient) for signals from the Arduino to the esp. 3.3V is considered as a logical HIGH so you dont need to do any changes for signals from esp to the Arduino.

I highly recommend getting a USB TTL converter, this will save you a lot of headaches and debugging will be easy. I did things without it for 1-2months and now I can totally feel the difference.

# Answer
> 1 votes
SoftwareSerial is reliable only up to 9600 baud or so. You can either swap ports and use Software serial as your debug output (but requires disconnecting/reconnecting the ESP8266 chip each time you upload to the UNO); or write a short sketch to set the device's baud rate to 9600 baud (and convince yourself that at least that much ran OK!) and set your SoftwareSerial to that rate.

# Answer
> 0 votes
* The Arduino pin 7 (TX) signal must be level-shifted from 5V to 3.3V using a voltage divider, because the ESP cant handle 5V signals.
* The Serial baud is a lot lower than that of SoftwareSerial plus you are spending a lot of time waiting for the whole command to come in. SoftwareSerial is also unreliable at 115200 baud. Use 57600 baud for both serial ports.

Use this code:

```
SoftwareSerial esp8266(6, 7); // RX, TX

void setup()
{
  Serial.begin(57600);
  esp8266.begin(57600);
}

void loop()
{
  while (Serial.available())
    esp8266.write(Serial.read());
  while (esp8266.available())
    Serial.write(esp8266.read());
}

```

It will do the exact same thing you want to do. Good luck.

# Answer
> 0 votes
I had the same issue before and it is a little bug in your code - while reading all the data from the serial port, you also read the CR & NL and then you send that as a line (with probably another NL). I solved it as such:

```
  if(Serial.available())
  {
    String command="";
    uint8_t c=0;
    while(c!=10) // read the command character by character
    {
      if (Serial.available()) {
        c=Serial.read();
        command+=(char)c;
      }
    }
    //Serial.print("Sending: ");
    //Serial.println(command);
    esp8266.print(command); // send the read character to the esp8266
  }

```

As you can tell, I was suspicious of the code and echoed back to make sure the reading from the `Serial` function. Also I went back to straight USB-\>Uno-\>ESP mode to confirm all was working, even the firmware with the 9600 Baud uploaded and then it clicked.

# Answer
> 0 votes
These values mostly come when you are unable to communicate with any UART device on proper baud rate. Best is to change the baud rate of ESP8266 from dafault 115200 to 9600 using

```
AT+UART_DEF=9600,8,1,0,3

```

And then use the regular program. And you will get what you want.

```
#include <SoftwareSerial.h>
#include<stdio.h>
SoftwareSerial mySerial(2,3);
void get_wifi_list();
uint8_t flag = 0;

void setup() {

    Serial.begin(9600);
    Serial.println("Starting the code, initial set-up");
    mySerial.begin(9600);
    delay(1000);
    Serial.println("Inside the main loop, going to start communicating with ESP8266");
    delay(1000);

}

void loop(){

  char data[1024];
  uint8_t ch = -1;
  uint8_t index = 0;
  memset(&data,0,sizeof(data));
  char data1[200];
  uint8_t index1 = 0;
  memset(&data1,0,sizeof(data1));

  if(mySerial.available())  // check if the ESP is sending a message
    {
    while(mySerial.available())
        {
            char c = mySerial.read();  // read the next character.
            data[index] = c;
            index++;
            if(index >= 2000){
                Serial.print("Data received exceed allowed length \n");
                return;
                }
                if (c == '+' ){
                    Serial.print("got start char");
                    //data1[index1] = c;
                    //index1++;
                    //if ( c== '\n');{
                    //    Serial.print("First data1 is :  ");
                    //    Serial.println(data1);
                    //    return;
                    //    }

      if( strstr(data,"OK")!=NULL || strstr(data,"CWLAP") !=NULL){
      Serial.print ("Get reply as OK \n");
      Serial.print (data);

        }
      }
    }
  }
  if (flag == 0){
      get_wifi_list();
      Serial.println("Getting the wifi list");
      flag = 1;
      return;
  }

  if(Serial.available()){
    delay(10);
    String cmd = "";
    while(Serial.available()){
        cmd += (char)Serial.read();
        }
    mySerial.println(cmd);
      }

}

void get_wifi_list(){
  String cmd = "AT+CWLAP";
  mySerial.println(cmd);
}

```

---
Tags: serial, esp8266
---


title: 'tmElements_t' does not name a type

text:
# Question
Title: 'tmElements_t' does not name a type
I've connected a real time clock ZS-042 to my Arduino Uno. I tried to set the time, using an example from DS1307RTC library. Here is my code:

```
#include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>

*const* char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

  tmElements_t tm;//it says that problem is in here

void setup() {

  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}

```

and this is my output:

```
Arduino: 1.6.12 (Windows 10), Плата:"Arduino/Genuino Uno"

In file included from C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino:1:0:

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:19:22: error: 'tmElements_t' has not been declared

     static bool read(tmElements_t &tm);

                      ^

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:20:23: error: 'tmElements_t' has not been declared

     static bool write(tmElements_t &tm);

                       ^

SetTime:10: error: 'tmElements_t' does not name a type

   tmElements_t tm;

   ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'void setup()':

SetTime:21: error: expected primary-expression before ')' token

     if (RTC.write(tm)) {

                     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getTime(const char*)':

SetTime:54: error: expected unqualified-id before '.' token

   tm.Hour = Hour;

     ^

SetTime:55: error: expected unqualified-id before '.' token

   tm.Minute = Min;

     ^

SetTime:56: error: expected unqualified-id before '.' token

   tm.Second = Sec;

     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getDate(const char*)':

SetTime:71: error: expected unqualified-id before '.' token

   tm.Day = Day;

     ^

SetTime:72: error: expected unqualified-id before '.' token

   tm.Month = monthIndex + 1;

     ^

SetTime:73: error: expected unqualified-id before '.' token

   tm.Year = CalendarYrToTm(Year);

     ^

exit status 1
'tmElements_t' does not name a type

```

# Answer
Clearly the compiler does not know what tmElements\_t means.

It is defined in TimeLib.h

In your program you reference Time.h instead, where it is not defined.

So: Change

```
include <Time.h>

```

to

```
include <TimeLib.h>

```

and it should clear that error.
> 2 votes

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


# Question
Title: How to listen for an incoming serial string inside loop with long delay?
I'm trying to build a datalogger using Arduino UNO, I'll use RS232 for the communication between PC and Arduino, the problem I'm facing now is that I'm using delay(10000) : 10 seconds as a timestep for data acquisition. however, I can't find any solution to receive a string from the serial input to Arduino while delay is executing. Here is the code :

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

void loop() {
  serialRoutine();
  dataLoggingEvery10Second(); // That's a function to receive data from the sensor and store it in SD card.
  delay(10000);
}

  // A function to handle all the serial in out
  void serialRoutine(){
  // print the string when a newline arrives:
  while(Serial.readString() == ""){
    String serstr = Serial.readString();
      /*
      *  Getters
      */
      if(serstr == "GETDATA"){
        Serial.println("Here is my data");
      }
      serstr = "";
  }
}

```

Any help would be highly appreciated !

# Answer
> 1 votes
```
void loop() {
  static unsigned long prev = 0;
  unsigned long now = millis();

  if (now - prev >= 10000L) {
    serialRoutine();
    dataLoggingEvery10Second();
    prev = now;
  }
}

```

This will executed at time 10s, 20s, etc. I

# Answer
> 0 votes
If your PC is sending GETDATA, then it can send it every 10 seconds (or every 15 or 30 minutes) so you don't need any delays at the Arduino end at all.

I have a page about getting serial data without blocking which illustrates how you can be doing other things (like reading sensors) without blocking.

An example sketch is:

```
/*
Example of processing incoming serial data without blocking.

Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

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

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

```

---
Tags: arduino-uno, serial, interrupt, rs232
---


# Question
Title: 2 Channel Relay normal open is not working with NodeMCU but led on board light up
I am pretty new to NodeMCU (ESP8266) and Arduino IDE in general. I followed various documentation / blogs to set up 2 Channel Relay with NodeMCU chip.

Below is sketch code for it.

```
#include<CayenneMQTTESP8266.h>
#define CAYENNE_DEBUG
#define CAYENNE_PRINT Serial

#define LEFT_GARAGE 4
#define RIGHT_GARAGE 5

char ssid[] = "XXXXXXXXXXXXXXXXXXXXXXXX";
char password[] = "XXXXXXXXXXXXXXXXXXXXXX";

char username[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
char mqtt_password[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
char client_id[] = ""XXXXXXXXXXXXXXXXXXXXXX";";

void setup() {
  Cayenne.begin(username, mqtt_password, client_id, ssid, password);
  pinMode(LEFT_GARAGE, OUTPUT);
  digitalWrite(LEFT_GARAGE, HIGH);
  pinMode(RIGHT_GARAGE, OUTPUT);
  digitalWrite(RIGHT_GARAGE, HIGH);
}

void loop() {
  Cayenne.loop();
}

// Left Garage Door
CAYENNE_IN(0){
  int currentValue = getValue.asInt();
  digitalWrite(LEFT_GARAGE,!currentValue);
}

//Right Garage Door
CAYENNE_IN(1){
  digitalWrite(RIGHT_GARAGE,!getValue.asInt());
}

```

On relay board I tried to connect wire in 2 different configuration.

1st Config:

```
vcc -> 3.3v from NodeMCU
in1 -> D1/GPIO 04 from NodeMCU
in2 -> D2/GPIO 5 from NodeMCU
GND -> GRD from NodeMCU

```

2nd Config:

```
vcc -> 5v USB from NodeMCU
in1 -> D1/GPIO 04 from NodeMCU
in2 -> D2/GPIO 5 from NodeMCU
GND -> GRD from NodeMCU

```

In 1st config, On relay board respective LED's are turning on when Cayenne buttons are pressed but when I check for continuity on multi meter I don't get anything.

In 2nd config, no LED and no continuity.

am I missing something here? Any feedback/comments are highly appreciated.

# Answer
> 1 votes
Your second configuration is right because from picture of relay module it clear that it requires 5V supply.

relay working principal is:

* when the signal port(in1/in2) is at low level, the signal light will light up and the optocoupler (it transforms electrical signals by light and can isolate input and output electrical signals) will conduct, and then the transistor will conduct, the relay coil will be electrified, and the normally open contact of the relay will be closed.
* When the signal port(in1/in2) is at high level, the normally closed contact of the relay will be closed. So you can connect and disconnect the load by controlling the level of the control signal port.

As you mentioned that in second configuration there is no LED glow. For find out solution of your problem, you have do one test. Test voltage level of D1/D2. Just make connection on breadboard as mentioned in image.

If voltage level is correct that it might be problem with your relay module.

Also I have attached here relay connection reference for your directness.

---
Tags: arduino-ide, esp8266, relay, nodemcu
---


# Question
Title: Android, Raspberry, Atmega, SQL communication
Hej there,

I have a small project at home and I'm curious if people have some advice/idea for me. Because I'm not sure if the communication between the different devices is the way to go.

This is my current setup:

I have a Android application running on an Android device (tablet). This Android device can communicate with a MySQL server with a json/PHP. The Android device is receiving data from the database but also writing data to it. The MyQL/web server is running on a Raspberry.

The second device is an atmega328p microcontroller(http://www.ebay.com/itm/2-x-ATMEGA328P-PU-ATMEGA328-MICROCONTROLLER-IC-Free-Shipping-/280994585126) that is sending temperature/humidity to the MySQL server on the Raspberry. The ATmega is communicating through a 433 MHz chipRF(MX-05V). The Raspberry also has a 433 MHz chip RF(MX-05V) that is receiving this data and writing it to the MySQL server.

So actually the ATmega is communicating with the Raspberry and the Raspberry is communicating with the MySQL server.

It is working properly but I'm not sure if this is the way to go. So my question, what are you thoughts of this setup, what would you do different and why?

Thanks, Matthijs

# Answer
If I understand correctly:

* You have a Pi hosting MySQL and a web server.
* A Mega writes temp/humidity data to the server.
* An android device reads data from the web server.
* The Pi and the Mega talk over a 433(MHz) radio?

Is it the write way to go? What you have is a tried an tested design, a central server responsible for collating at serving the data. My one concern is the 433 radios, I think you might be limiting the scalability of your design by using that. What happens if you want to add a second Mega to report a different sensor? You PI needs a second receiver and a second app to read, although the PI will handle 2, easily, there will be a point where it can't handle any more. I'd suggest that you look at technology that allows multiple nodes on the same network, WiFi.

You could use WIFI by either getting adding a WiFi device to you Mega or ditching the expensive Mega and buying a $2 Wemos D1.

But that's just my opinion, and unfortunately that's the reason this question will get closed, because asking for people's opinions is taboo.
> 1 votes

---
Tags: communication, atmega328, raspberrypi
---


# Question
Title: Can we use yx5300 to play audio from a file in Arduino?
I want to play a file that I have in my USB device through a yx5300 mp3 module.

I have a file in my USB device at path `Music/hello.mp3`. I want to play this file using the yx5300 module or some other module, if available.

I have already read this file using a shield. I want to pass the data to the yx5300.

# Answer
No. That chip can only play files on an SD card that is directly attached to it.
> 2 votes

---
Tags: sound
---


# Question
Title: I2C communication between Arduino Due and Nano
I'm trying to communicate between two Arduino Due and Nano. Nano as Master and Due as a slave. As given in the library description Wire Lib

When the master request for data from the slave, first it goes to Request ISR. `Wire.onRequest(requestEvent)` But when compile the program for Arduino Due I get following errors.

```
In file included from C:\Users\\Slave_Test3.ino:14:0:

C:\Users\..\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\libraries\Wire\src/Wire.h:59:7: error:   initializing argument 1 of 'void TwoWire::onRequest(void (*)())' [-fpermissive]

 void onRequest(void(*)(void));

       ^

```

But If I change from Arduino Due to any other board this error does not come.

Thank you

# Answer
> 1 votes
Dead easy !! (Well only because I had a `-fpermissive` yesterday :) )

You are trying to implicitly cast, and you can't do that with modern GCC versions (quite rightly).

So you need to explicitly cast the first parameter to void\*.

Because this is in a "core" library for the Due I would get the latest version of the board package and see if it goes away. You can turn the check off, but you will need to google on how to do that.

---
Tags: arduino-nano, i2c, arduino-due, wire-library
---


title: RFM95 LoRa module frequency options

text:
# Question
Title: RFM95 LoRa module frequency options
I live in India, and unfortunately here the unlicensed band ranges only from 865MHz to 867M Hz. The IBM LoRa code for Arduino (as node) for RFM95 module allow you to choose between 915 Mhz and 868 Mhz only. I initially created a gateway using a Pi3 listening at 865.7 (to conform with Indian rules), but it couldn't receive any payloads from my node running at 868 Mhz. Then, eventually, I tried again with my gateway listening at 868 Mhz, and it worked like a charm. No hiccups.

But, obviously, it seems to be against the rules, and I don't fancy prison. So I want to know if I can get the RFM95 module working somewhere in the range of 865 Mhz to 867 Mhz? And if yes, how can I do it? There certainly doesn't seem to be an option to choose a frequency other than 868 Mhz or 915 Mhz in the IBM Lora code. Here is the link to the code library. https://github.com/matthijskooijman/arduino-lmic

# Answer
The RF networks of the RFM95 board are ideally configured for the general range of frequencies, but the difference between your 865.7 MHz and the 868 MHz tuning of a **European** (vs US) version of the board is likely smaller than the error with which the RF networks can be tuned to begin with, so that is unlikely to be a problem unless there is some hard lockout of your desired frequency in the SX1272 chip. I've even heard claims that some people have managed to at least somehwat use US vs European tuned versions on the opposite bands, which is far more drastic than what you are trying to accomplish.

So assuming there is no hard lockout of your desired frequencies in the hardware, basically what you will need to do is to change the frequency list in the source of the software you are using to operate the module.

Basically you would edit `src/lmic/lorabase.h` and make a modified version of the EU configuration. Ideally you'd add that as an additional option and select it, but for an initial test you could just edit the European version to fit your needs.

Do keep in mind the code will probably want to use multiple frequencies - if you have a gateway that receives only on a single frequency, you'll need to modify the code to always use that, after determining if doing so fits with usage-rate rules in your jurisdiction.

It's probably worth doing some online research to see if anyone has already put thoughts into operating LoRa in India - if so, there may already be a modified branch of the LMiC code you can use.
> 1 votes

---
Tags: wireless
---


# Question
Title: ESP8266MOD programing using Arduino uno?
I want to make a very simple webserver who sends welcome message to anyone who joins it using WiFi.

I have a ESP8266MOD module, I want to program it using arduino ide and arduino uno board. How I can use arduino uno to program this WiFi module without using urat USB serial board?

SoftwareSerial.h is not working with esp.write() command, I believe it is because of low power, can anyone suggest me on power supply too?

Thanks in advance,

Mohan

# Answer
When you use the Uno for its UART only, i.e. grounding RST pin, its Rx pin 0 becomes Tx, and Tx pin 1 becomes Rx -- because that's what pins on the UART you are connecting to. AppMonk didn't say what specific breakout/ chip mount he's using, there are many, or say how he's managing level-shifting from the Uno to the ESP if needed. The Tx pin on Uno (0, labeled Rx) is putting out 5v and the ESP would prefer 3.3, so level shifting w/ simple voltage divider is recommended. You don't need to level shift the Tx signal from ESP to Arduino's Rx (pin 1).
> 1 votes

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


title: Arduino ESC controlled motor has issues

text:
# Question
Title: Arduino ESC controlled motor has issues
I have a brushless motor what is hooked up to a external power supply and I'm using an arduino with a potentiometer to control it. I know that the motor has power but whenever I turn the potentiometer nothing happens. I'm wondering if my wiring is wrong. Here's the wires is connected:

First pin of the potentometer to arduino GND Second pin of the potentometer to arduino A0 Third pin of the potentiometer to arduino 5V

Black wire of the ESC to arduino GND Red wire of the ESC to VIN White wire of the ESC to D8

I'm also using a switch to give both the arduino and motor power and they both seem to turn on fine.

Motor has external power and does twitch very slightly when powered on with this circuit but I can't get is to actually move substantially using the potentiometer.

Here's my code:

```
#include <Servo.h>//Using servo library to control ESC
Servo esc; //Creating a servo class with name as esc
void setup()
{
esc.attach(8); //Specify the esc signal pin,Here as D8
esc.writeMicroseconds(1000); //initialize the signal to 1000
Serial.begin(9600);
}
void loop()
{
int val; //Creating a variable val
val= analogRead(A0); //Read input from analog pin a0 and store in val
val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(Change if needed)
esc.writeMicroseconds(val); //using val as the signal to esc
}

```

# Answer
> 1 votes
It would seem you are attempting to power the motor's coils from VIN of the Arduino. If you are powering the whole system from USB or from the barrel connector on the Arduino, then it's likely that the small voltage regulator on the Arduino cannot supply sufficient current to the motor.

You should connect the black and red wires of the ESC directly to a high-current power supply, and ensure the black (GND) wires of the ESC, power supply, and Arduino are tied together.

---
Tags: arduino-nano, servo, potentiometer
---


title: L298 works only when touched

text:
# Question
Title: L298 works only when touched
The following image is my connection of l298 with Arduino.

This is the program.

```
int ENA = 10; // MCU PWM Pin 10 to ENA on L298n Board
int IN1 = 9;  // MCU Digital Pin 9 to IN1 on L298n Board
int IN2 = 8;  // MCU Digital Pin 8 to IN2 on L298n Board

int ENB = 5;  // MCU PWM Pin 5 to ENB on L298n Board
int IN3 = 7;  // MCU Digital pin 7 to IN3 on L298n Board
int IN4 = 6;  // MCU Digital pin 6 to IN4 on L298n Board

void setup()
{

pinMode(ENA, OUTPUT); //Set all the L298n Pin to output
pinMode(ENB, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
}
void DRIVEONE()
{
// Run the motors on both direction at fixed speed
digitalWrite(IN1, HIGH); // Turn HIGH motor A
digitalWrite(IN2, LOW);
analogWrite(ENA, 200); // TO set the turning speed to 200 out of possible
range 0 to 255

digitalWrite(IN3, HIGH); // turn HIGH motor B
digitalWrite(IN4, LOW);  // To set the turning speed to 200 out of possible
range 0 to 255
analogWrite(ENB, 200);
delay(2000);  // Delay to 2 seconds
void loop()
{
DRIVEONE();
delay(100);
}

```

The program seems to work fine but the motors run only when I touch all the 15 pins in L298 as shown in the second image. I don't understand why the motors aren't running without touching those 15 pins.

I have connected the L298 to a 12V rechargeable battery and Arduino to a 9V battery. Please help me understand what is wrong here. Thank you.

# Answer
Your schematic does not show a connection from the ground line of the 12V battery to the GND connection on the Arduino. This is required.
> 10 votes

---
Tags: l298n
---


title: Unknown type name 'IRsend'

text:
# Question
Title: Unknown type name 'IRsend'
In the C file in simplesample\_mqtt.c, which connects Arduino to the Azure IoT hub, I need to use the IRsend and IrRemoteESP8266 libraries to send an infrared signal with Azure IoT hub.

```
 #include <IRremoteESP8266.h>
 #include <IRsend.h>
 IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

```

I don't have any problem when I use this code in my main Arduino file. But when I use these includes in a C file (simplesample\_mqtt.c), I get this error from line 3: "unknown type name 'IRsend'".

error full info :

```
Arduino: 1.8.2 (Windows 10), Board: "NodeMCU 0.9 (ESP-12 Module), 80 MHz, 115200, 4M (3M SPIFFS)"

In file included from sketch\simplesample_mqtt.c:29:0:

C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:1: error: unknown type name 'class'

class IRsend {

C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:14: error: expected '=', ',', ';', 'asm' or 'attribute' before '{' token

class IRsend {

simplesample_mqtt.c:31: error: unknown type name 'IRsend'

IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

simplesample_mqtt.c:31: error: expected declaration specifiers or '...' before numeric constant

IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

exit status 1
unknown type name 'IRsend'

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

```

# Answer
> 1 votes
I solved this problem. The reason for this is because main Arduino is c++ and simplesample\_mqtt.c is c code and we have to use c++ code in c code:

In main Arduino file you have to declare function like this :

```
extern "C" void TurnOn();
void TurnOn()
{
    digitalWrite(RELAY_SONOFF, HIGH);
    digitalWrite(LED_SONOFF, HIGH);
}

```

and use this function in c code:

```
void TurnOn();
EXECUTE_COMMAND_RESULT TurnOn(ContosoAnemometer* device)
{
    (void)device;
    TurnOn();
    (void)printf("Turning fan on.\r\n");
    return EXECUTE_COMMAND_SUCCESS;
}

```

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


title: Usage of Crypto Library (Speck)

text:
# Question
Title: Usage of Crypto Library (Speck)
I really want to understand how can I use this library for my purposes.

I'm trying to encrypt a message that comes through the serial port of the Arduino, and send it through another serial port. But I'm having issues understanding how to use the library. I have read the documentation of the library, but I still get errors, I need a little help with this.

This is the code I have (without involving the serial ports), initially I wanted to check if I could define my strings and use them in another way instead of using the TestVector Function:

```
 #include <Crypto.h>
 #include <Speck.h>
 #include <SpeckSmall.h>
 #include <SpeckTiny.h>
 #include <string.h>

 struct EncryptText
 {
     const char *name;
     byte key[32];
     byte plaintext[16];
     byte ciphertext[16];
 };

 EncryptText test ;

   static TestCipher {

   test.name = "Speck-128-ECB";
   test.key = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                     0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
   test.plaintext = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                     0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
  test.ciphertext = {0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                     0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};
   }

Speck speck;
SpeckSmall speckSmall;
SpeckTiny speckTiny;

byte buffer[16];

//void testCipher(BlockCipher *cipher, const struct TestVector *test, size_t keySize, bool decryption = true)
void testCipher(BlockCipher *cipher, size_t keySize, bool decryption = true)

{

    Serial.print(" Encryption ... ");
    cipher->setKey(key, keySize);
    cipher->encryptBlock(buffer, plaintext);

    for(byte b=0; b<16; b++)
   {
      Serial.print(buffer[b], HEX);
   }

    if (memcmp(buffer, ciphertext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");

    if (!decryption)
        return;

    Serial.print(" Decryption ... ");
    cipher->decryptBlock(buffer, ciphertext);

    for(byte b=0; b<16; b++)
   {
      Serial.print(buffer[b], HEX);
   }
    if (memcmp(buffer, plaintext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");
}

```

I'm getting the error: "exit status 1 'TestCipher' does not name a type"

EDIT: The full error that I get is:

```
 Speck_4-08-2017:27: error: 'TestCipher' does not name a type    static
 TestCipher {
           ^ Speck_4-08-2017.ino: In function 'void testCipher(BlockCipher*, size_t, bool)': Speck_4-08-2017:62: error:
 'key' was not declared in this scope
      cipher->setKey(key, keySize);
                     ^ Speck_4-08-2017:63: error: 'plaintext' was not declared in this scope
      cipher->encryptBlock(buffer, plaintext);
                                   ^ Speck_4-08-2017:70: error: 'ciphertext' was not declared in this scope
      if (memcmp(buffer, ciphertext, 16) == 0)
                         ^ Speck_4-08-2017:80: error: 'ciphertext' was not declared in this scope
      cipher->decryptBlock(buffer, ciphertext);
                                   ^ Speck_4-08-2017.ino: In function 'void perfCipher(BlockCipher*, const TestVector*, size_t, bool)':
 Speck_4-08-2017:104: error: 'key2' was not declared in this scope
          cipher->setKey(key2, keySize);
                         ^ Speck_4-08-2017.ino: In function 'void setup()': Speck_4-08-2017:158: error: 'testVectorSpeck128' was not
 declared in this scope
      testCipher(&speck, &testVectorSpeck128, 16);
                          ^ exit status 1 'TestCipher' does not name a type

```

Any guidance would be very helpful.

# Answer
The first error looks like this

```
 Speck_4-08-2017:27: error: 'TestCipher' does not name a type    static
 TestCipher {

```

Further errors are basically all caused by that one wrongly written declaration. It could be fixed by declaring the first struct properly.
Compare this example code you have

```
struct TestVector
{
    const char *name;
    byte key[32];
    byte plaintext[16];
    byte ciphertext[16];
};

static TestVector const testVectorSpeck256 = {
    .name        = "Speck-256-ECB",
    .key         = {0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18,
                    0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
                    0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    .plaintext   = {0x65, 0x73, 0x6f, 0x68, 0x74, 0x20, 0x6e, 0x49,
                    0x20, 0x2e, 0x72, 0x65, 0x6e, 0x6f, 0x6f, 0x70},
    .ciphertext  = {0x41, 0x09, 0x01, 0x04, 0x05, 0xc0, 0xf5, 0x3e,
                    0x4e, 0xee, 0xb4, 0x8d, 0x9c, 0x18, 0x8f, 0x43}
};

```

and your code

```
struct EncryptText
 {
     const char *name;
     byte key[32];
     byte plaintext[16];
     byte ciphertext[16];
 };

 EncryptText test ;
   static TestCipher {

   test.name = "Speck-128-ECB";
   test.key = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                     0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
   test.plaintext = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                     0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
  test.ciphertext = {0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                     0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};
   }

```

You wrote `EncryptText test;` by specifying the type `EncryptText` you defined before and a name `test`, but now, you can assign to test by just using `test.` \+ variable name and nothing else (no `static TestCipher{}`). Or you could use what the example does, it basically just skips the `EncryptText test;` part and puts it on one line, like `static TestVector const testVectorSpeck128 = {` and assigns inside the curly brackets just using `.` \+ variable name (without `test` or `testVectorSpeck128`).

Now, the second error

```
 'key' was not declared in this scope
      cipher->setKey(key, keySize);

```

is that the variable `key` is not defined in the function `testCipher` just like the error says, you have to define that variable or use the right one, in the example it was done using a function parameter (you commented out) `TestVector *test`, it was dereferenced and accessed with `test->key`. I assume you've properly defined that struct now, there's no need to deal with pointers and with direct reference to the data you can use it elsewhere by just using something like this

```
cipher->setKey(test.key, keySize);

```

rest of the errors are of similar fashion and can be fixed by just adding `test.` like I showed. If you fix those errors rest should be simple already.

As you are just learning, take small steps modifying the examples and use the `Verify` button as often as possible, Arduino IDE also has a button to autoformat code, use it, makes your code more readable for you and everyone else.
> 1 votes

# Answer
It looks like you want to create a struct and initialize it. Like this:

```
struct EncryptText
{
    const char *name;
    byte key[32];
    byte plaintext[16];
    byte ciphertext[16];
};

EncryptText test = {
    "Speck-128-ECB",
    {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                     0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                     0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
    {0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                     0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18}
};

```

Then it appears you want to use that object. Note that to access each member of the struct you have to use dot notation (ex: `test.key`):

```
void testCipher(BlockCipher *cipher, size_t keySize, bool decryption = true)
{
    Serial.print(" Encryption ... ");
    cipher->setKey(test.key, keySize);
    cipher->encryptBlock(buffer, test.plaintext);

    for(byte b=0; b<16; b++)
    {
        Serial.print(buffer[b], HEX);
    }

    if (memcmp(buffer, test.ciphertext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");

    if (!decryption)
        return;

    Serial.print(" Decryption ... ");
    cipher->decryptBlock(buffer, test.ciphertext);

    for(byte b=0; b<16; b++)
    {
        Serial.print(buffer[b], HEX);
    }
    if (memcmp(buffer, test.plaintext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");
}

```
> 2 votes

---
Tags: arduino-uno, library
---


# Question
Title: Wemos D1 mini freezing after a few minutes
I´m using a Wemos D1 mini board to control a RGB LED Strip and programmed a simple code with the Arduino IDE. The Wemos conects to my Internet just fine and with the IP adress I can change the RGB values of the Strip. Everything works but after a few minutes the board freezes and nothing works. After a reset it works again.

I also conected a simple circuit to the board just to controle a RGB-LED Strip with a few transistors nothing that should cause an issue and also if i conect nothing to the board the problem occurs.

I also tested a example from the Wemos Library but there is the same problem. Here is my code I used (And sorry if the code isn´t that well programmed I´m a beginner ;)):

```
#include <ESP8266WiFi.h>

const char* ssid = "my SSID";
const char* pass = "my password";

void setup() {
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D5, OUTPUT);

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) delay(500);

  Serial.begin(9600);
  //Serial.println(WiFi.localIP());
  server.begin();
}
void setColor(String rgb)
{
  String rgb_val = rgb.substring(4, rgb.lastIndexOf('H'));
  String red_val = rgb_val.substring(1,rgb_val.indexOf(':'));
  String green_val = rgb_val.substring(rgb_val.indexOf(':') + 1,rgb_val.indexOf(':',rgb_val.indexOf(':') + 1));
  String blue_val = rgb_val.substring(rgb_val.lastIndexOf(':') + 1);
  int redval = red_val.toInt();
  int greenval = green_val.toInt();
  int blueval = blue_val.toInt();
  analogWrite(D5, redval);
  analogWrite(D2, greenval);
  analogWrite(D1, blueval);

  redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
  if (redval == 0)
    analogWrite(D5, 0);

  greenval = greenval >= 1023 ? 1023 : greenval <= 0 ? 0 : greenval;
  if (greenval == 0)
    analogWrite(D1, 0);

  blueval = blueval >= 1023 ? 1023 : blueval <= 0 ? 0 : blueval;
  if (blueval == 0)
    analogWrite(D2, 0);

  return;
}

void loop() {
  //delay(50) //just a test if there are not so many updates
  WiFiClient client = server.available();
  if (!client) return;

  while (!client.available()) delay(1);

  String request = client.readStringUntil('\r');
  client.flush();

  //Serial.print(request);
  setColor(request);
  client.stop();

  client.print("HTTP/1.1 200 OK\r\n");
  client.flush();
  return;
}

```

Is there someone who know what I have done wrong?

# Answer
I doubt this is the problem, but this code looks wrong.

```
  int redval = red_val.toInt();
  analogWrite(D5, redval);
  redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
  if (redval == 0)
    analogWrite(D5, 0);

```

I think it should be more like this:

```
  int redval = red_val.toInt();
  if (redval > 1023)  // If its =1023 you do need to set it to 1023.
    redval= 1023;
  else if (redval < 0)
    redval = 0;
  analogWrite(D5, redval);

```

The inline if statement is too ugly and doesn't really add anything.

To be honest I would look at pulling this code into functions to make it easier to read and I suspect you will find the problem.

When these microprocessors stop after a while its usually memory, heat or electrical. If you have checked the electrics and its stopping quite quickly its probably a memory leak. So refactoring your code might help people spot the problem easier.

You might want to replace you call to `setColour()` with a call to `Serial.println()` and see if that cure the problem. If it doesn't then your problem is with the way you are calling client.
> 0 votes

---
Tags: esp8266, wifi, web-server, code-review
---


title: TEENSY 3.2 RS-232 throughput

text:
# Question
Title: TEENSY 3.2 RS-232 throughput
I have an application where I need 4 serial ports - 3 will be sending and receiving. The packet size will be up to 255 bytes on these 3 "main" ports. The 4th port will be receive only, and its packet size will be 6 bytes. There is no flow control. The data rate on all ports is 115,200 baud. The 3 main ports will send or receive data packets approximately once per second. Most data will be half-duplex, although occasionally it will be necessary to send and receive simultaneously from a port . The 4th port (the one that handles 6 bytes), will get packets at an approx 50 packets/second rate.

The TEENSY will have to calculate CRCs on all ports, and will have to do a small amount of data manipulation as well.

I was planning to use the hardware serial ports for the 3 main ports, and software serial for the port that has to deal with only 6 bytes. It is important that the 3 main ports be able to not miss any incoming data. The 4th port is less important and can "miss" a packet now and then with no ill effects.

Will a TEENSY 3.2 running 90MHz be able to keep up?

# Answer
Once per second? I don't see any problem, I will try to calculate:

3 ports: send + receive 255 bytes, let's say 270 bytes (with start/stop bits, probably way too much) per message:

3 * 2 (send + receive) * 270 = 1620 bytes 4th port: 50 * 6 bytes = 300 bytes

Total: 1920 bps

The serials can easily keep up with this, so that is not a problem.

90 MHz is 90 million instructions per second. As you can see, handling 1620 bytes is nothing ... it could do many more, a factor of multiple thousands more.

Unless of course you want to do heavily calculations for the received/sent data.
> 1 votes

---
Tags: serial, teensy
---