# Question
Title: Esp8266-01 AT Commands returns partially
Im trying to get html response from server via esp01 module

when using the serial monitor in arduino studio everything works fine

here is the serial monitor output

```
AT+CIPSTART="TCP","aaaa.aaaa",80

CONNECT

OK
AT+CIPSEND=43

OK
>
Recv 43 bytes

SEND OK

+IPD,227:HTTP/1.1 200 OK
Date: Sat, 19 Jan 2019 18:42:58 GMT
Server: Apache
X-Powered-By: PHP/7.2.11
Vary: Accept-Encoding,User-Agent
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

10
Hello from server

0

CLOSED

```

but when im trying to do the same from the sketch my response is returned partially

```
AT+CIPSTART="TCP","aaaa.aaaa",80

CONNECT

OK
AT+CIPSEND=43

OK
>
Recv 43 bytes

SEND OK

+IPD,227:HTTP/1.1 200 OK
Date: S

```

it ends on the first letter of date for some reason

here is my sketch

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX //serial for comunication with esp
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.setTimeout(5000);//dont know if i need this

  delay(10000);

  //check wifi module
  mySerial.println("AT");
  delay(1000);
  if(mySerial.find("OK"))
  {
    Serial.println("Initializing");
  }else{
    Serial.println("Error initializing");
  }
}

void loop() { // run over and over

  Serial.println("go");
mySerial.println("AT+CIPSTART=\"TCP\",\"aaaa.aaaa\",80");
delay(1000);
    while(mySerial.available()){
    Serial.write(mySerial.read());
     delay(1);
  }
mySerial.println("AT+CIPSEND=43");
delay(1000);
    while(mySerial.available()){
    Serial.write(mySerial.read());
     delay(1);
  }
mySerial.println("GET /load.php HTTP/1.1");
delay(100);
    while(mySerial.available()){
    Serial.write(mySerial.read());
     delay(1);
  }
mySerial.println("Host: aaaa.aaaa");
delay(100);
    while(mySerial.available()){
    Serial.write(mySerial.read());
     delay(1);
  }
mySerial.println("");
delay(2000);

    while(mySerial.available()){
    Serial.write(mySerial.read());
     //delay(100);
  }

delay(5000);

}

```

what is the reason for this behavior? how can i fix this?

# Answer
> 0 votes
found the solution i had t wait for serial input without delay function

```
String sendCommand(String command, const int timeout)
{
  String res = "";
  mySerial.println(command); // send the read character to the wifi
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(mySerial.available())
    {
      // The esp has data so display its output to the serial window
      char c = mySerial.read(); // read the next character.
      res+=c;
    }
  }
  //Serial.print(response);
  return res;
}

```

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


# Question
Title: How to send chars and values at the same time from processing to Arduino
i have been trying to set Builtin LED frequency from arduino and turn it on and off .

I have created an interface with knobs and buttons in processing . I want to set delay between ON and OFF with 1 knob and OFF and ON delay with another knob . And button blinks the led at given frequency

In arduino i have tried something like this :

```
if(Serial.available() >0){
char val=Serial.read();
switch(val)
{
  case 'c':
  theValue=Serial.read();
  break;
  case 'd':
  theValue1=Serial.read();
  break;

case 'r':
digitalWrite(13,HIGH);
delay(theValue);
digitalWrite(13,LOW);
delay(theValue1);

break;
}

}

```

In the processing :

```
  public void Blink(){
   myPort.write('r');
 }

 public void knobON(int theValue){
   myPort.write('c');
   myPort.write(theValue);
 }

 public void knobOFF(int theValue1){
   myPort.write('d');
   myPort.write(theValue1);
 }

```

Can you help me on what should i do ?

# Answer
> 0 votes
The Arduino code sample you've provided is incomplete, and does not compile. On the Processing side, I would combine the LED On time with the Off time, using a separator, then ending with a `\n`. Something like this: `myPort.write("1000:2000\n");`.

There are many ways to parse the serial data into `unsigned long` to be used in the `delay()` function. Here is a sketch illustrating one way to parse it. I am using the serial monitor to send the following test data **1000:2000** (LED on for 1 second, off for 2 seconds). The serial monitor is sending the `\n` character.

```
char buffer[16];
unsigned long onTime;
unsigned long offTime;

void setup(){
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop(){

  if(Serial.available() > 0){

    Serial.readBytesUntil('\n', buffer, 13);

    char * pch;
    pch = strtok(buffer, ":");
    onTime = strtol(pch, &pch, 10);
    pch = strtok(NULL, ":");
    offTime = strtol(pch, NULL, 10);

    digitalWrite(13, HIGH);
    delay(onTime);
    digitalWrite(13, LOW);
    delay(offTime);
    memset(buffer, 0, sizeof(buffer));
  }
}

```

---
Tags: arduino-uno, processing-lang
---


# Question
Title: Can Serial be safely used in an SPI interrupt routine
I have anecdotal experience that using Serial.print inside a slave's SPI interrupt routine (ISR) causes issues with transmission. It also seems that interrupts may be called more than once before the main loop can react, so it is difficult to print info from all interrupts. Is this because Serial is inherently unsafe, or too slow? Can Serial be used safely inside the ISR routine?

# Answer
> 4 votes
Serial should be avoided in ISRs because interrupts are disabled inside ISRs, and Serial transmission uses interrupts to operate. Better to have the ISR set a flag that is read in the next iteration of `loop()` to print the desired info.

# Answer
> 2 votes
Hardware Serial write(byte) function in Arduino AVR core will work in interrupt. It checks if interrupts are disabled and if yes and the buffer is full, it executes directly the interrupt function, which pushes bytes from buffer to output.

(All write and print functions of hardware Serial use the write(byte) function to send data.)

It depends on other factors if a long time spent in interrupt handler will disturb things.

# Answer
> 1 votes
In general, interrupts should run as fast as possible. This is especially true when using SPI, since in the slave's ISR, the slave needs to put a byte in the SPI Data Register (SPDR) *before* the next transfer occurs. Thus it is good practice to avoid Serial transmission entirely in an interrupt, since in simple interrupts it can be by far the slowest portion of the interrupt.

---
Tags: serial, interrupt, spi
---


# Question
Title: Is not it possible to use more than 3 output pins in ESP8266 at the same time?
I'm trying to make a WiFi controlled Car from my old toy car which will be running on ESP8266. I'm using the L298N motor driver and have *one motor for left-right control* & *other for forward-backward direction control*.

Now the problem is I'm unable to use more than 3 pins at once. If I even try, likely my code **stops** working.

Below is my code :

```
static const uint8_t enFront   = D0;
static const uint8_t front_in1 = D1;
static const uint8_t front_in2 = D2;
static const uint8_t enBack    = D5;
static const uint8_t back_in1  = D3;
static const uint8_t back_in2  = D4;

#include <ESP8266WebServer.h>

const char* ssid = "espCar <^_^>";
const char* password = "hacksAllowed";

  ESP8266WebServer server(80);

void setup() {
  pinMode(enFront,OUTPUT);
  pinMode(front_in1,OUTPUT);
  pinMode(front_in2,OUTPUT);
 /* pinMode(enBack,OUTPUT);   <--Problem here
  pinMode(back_in1,OUTPUT);   <--Problem here
  pinMode(back_in2,OUTPUT);*/ <--Problem here

   Serial.begin(115200);
  WiFi.softAP(ssid, password);
  WiFi.mode(WIFI_AP);
  delay(500);
  server.on("/REQ",processRequest);
  server.begin();
  Serial.println("Server is UP!");
}

void loop() {
 // server.handleClient();
  analogWrite(enFront,1023);
  digitalWrite(front_in1,HIGH);
  digitalWrite(front_in2,LOW);
  delay(2000);
  digitalWrite(front_in2,HIGH);
  digitalWrite(front_in1,LOW);
  delay(2000);
}

void processRequest() {
 /* if (server.arg("move")!=""){
    if (server.arg("right")!=""){
      analogWrite(enFront,server.arg("right").toInt());
      digitalWrite(front_in1,HIGH);
      digitalWrite(front_in2,LOW);
      /*Debug*/
    /*  server.send(200, "200", server.arg("right"));
    }else if(server.arg("left")!=""){
      analogWrite(enFront,server.arg("left").toInt());
      digitalWrite(front_in1,LOW);
      digitalWrite(front_in2,HIGH);
      /*Debug*/
     /* server.send(200, "200", server.arg("left"));
    }
  }*/
}

```

---

***All code working fine until I declare `pinMode(pin,OUTPUT)` for any 4th pin.*** (Everything is ok for every pin till 3rd one is declared)

I'm not so old with ESP or Arduino. So, please help by giving some clarification on this.

---

**Schematic**:

simulate this circuit – Schematic created using CircuitLab

**Sorry for the mistake of making both motors tagged 2, → one is M1 & other is M2**

# Answer
> 0 votes
I found out the problem & it has nothing to deal with ESP8266. It was something like voltage conflict (I don't know the deeper science, I agree).

*Actually, I was testing by plugging in the USB to ESP & at the same time I had a 11V lipo connected to L298N.*

I tested by using one single voltage source & everything worked fine.

It looked something like this (It → the wrong one here):

simulate this circuit – Schematic created using CircuitLab

---
Tags: esp8266, l298n
---


# Question
Title: Arduino scrolling text program freeze after some time
I use a 16x2 character lcd to display some text. What I want is first line will stay, but the second line should scroll text.

I wrote a program which works fine but the problem is after some time arduino does not respond. I suspect there might be a bug or memory leak in the code.

The relevant code is like this.

```
void scrollTextFromRight(int line, char text[])
{
    const char space[16] = "                ";
    char screen[16];
    char * longText;

    longText = malloc(sizeof(char) * (sizeof(text) + 17));

    memset(longText, '\0', sizeof(char) * (sizeof(text) + 17));
    memset(screen, '\0', sizeof(screen));

    for (int i = 0; i < 16; ++i)
    {
        longText[i] = space[i];
    }

    for (int j = 0; j < sizeof(text) + 17; ++j)
    {
        longText[16+j] = text[j];
    }

    for (int i = 0; i < sizeof(text) + 17; ++i)
    {

        lcd.setCursor(0, line);
        strncpy(screen, longText + i, 17 );
        lcd.print(screen);
        delay(350);
    }
}

```

I call this function from main program like this:

```
scrollTextFromRight(1, "Scrolling text");

```

# Answer
> 1 votes
You malloc but don't free. Of course it's going to leak. Also `sizeof(text)` doesn't work like that. Instead you can do strlen to get the number of characters in a null-terminated char array.

You can do this without the `longText` buffer by doing partial copies into `screen`.

```
const char space[16] = "                ";
char screen[16];

for (int i = 0; i < sizeof(text) + 17; ++i)
{
    lcd.setCursor(0, line);
    strncpy(screen, space, i); // copy i spaces
    strncpy(screen+i, text, min(17-i, strlen(text))); // copy the rest of the string up to the end whichever is shorter.
    screen[17] = '\0'; // force null termination
    lcd.print(screen);
    delay(350);
}

```

---
Tags: arduino-uno, lcd, strlen
---


# Question
Title: AccelStepper Library: How do I go to a position without decelerating?
When I make the motor move at a certain distance with setMaxSpeed(), setAcceleration(), and moveTo(), it always accelerates and decelerates. Is there a way to disable the deceleration?

# Answer
AccelStepper, as hinted by the name, uses acceleration always. By setting the acceleration high, you reduce the amount of time spent accelerating to the set speed.

`setAcceleration()` sets the rate in steps per second per second. If your MaxSpeed is 200 steps per second, then setting the acceleration to 200\*10 means all acceleration is over in 1/10 second. You can go higher, etc.
> 1 votes

---
Tags: motor, stepper
---


title: Wrong conversion of time_t to char

text:
# Question
Title: Wrong conversion of time_t to char
I have a simple sample of code that i want to convent a time\_t to char array in order to concatenate it after, in an other array. Code:

```
time_t unixt;
char exm [40];

unixt = RTC.get();
Serial.println(unixt);
dtostrf(unixt, 10, 0, exm);
Serial.println(exm);

```

The problem that i face is that, the console is printing different the second one every time like this:

```
1548258220
1548258200

```

I tried also with unsigned long with no result either. Can someone point me what's wrong or an other way of doing this?

# Answer
> 5 votes
Use `ultoa()` instead of `dtostrf()`. The former is meant to serialize unsigned long integers, while the later is for floating point numbers. By using `dtostrf()`, you are implicitly converting `unixt` to a floating point number. The Arduino Mega only supports single precision floating point, so this conversion incurs some loss of precision, hence the result you see.

---
Tags: arduino-mega
---


# Question
Title: ESP8266 EEPROM seems not working, saved data are different when I try to read them
I'm working on project which require to save some data into the EEPROM. As I read online the ESP8266 has no real EEPROM, it use a section of FLASH just after the SPIFFS. Due to this read/write is quite different from standard Arduino, you need to call `EEPROM.commit()`. You also have to call `EEPROM.begin(size)` (I used size = 512) before start to use it.

I follow different tutorials online and I made some tests but it seems not working at all. When I try to save a value and then read it, values are different. I tried with

```
EEPROM.write(..)
...
EEPROM.read(..)

```

and with

```
EEPROM.put(..)
...
EEPROM.get(..)

```

but nothing change.

Is there any configuration on the board I need to set into Arduino IDE/Board Configuration?

EDIT: here's the code

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

    EEPROM.begin(512);
    EEPROM.write(0, 62);
    EEPROM.write(10, 103);
    //EEPROM.commit();
    EEPROM.end();
    Serial.print("Read at 0:"); Serial.println(EEPROM.read(0), DEC);
    Serial.print("Read at 10:"); Serial.println(EEPROM.read(10), DEC);
}

```

I always read 0 in the output.

# Answer
You can read the emulated EEPROM only between `begin` and `end`. It works with memory image.

* `begin` allocates the in-memory image.
* `commit` writes it to flash.
* `end` commits and deletes the memory image.
> 2 votes

# Answer
Here is some ESP8266 example code to store and read strings from EEPROM data:

```
#include <EEPROM.h>

void writeString(char add,String data);
String read_String(char add);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  EEPROM.begin(512);  // Note::

  String data = "Hello World";

  Serial.print("Writing Data:");
  Serial.println(data);

  writeString(10, data);  //Address 10 and String type data
  delay(10);
}

void loop() {
  // put your main code here, to run repeatedly:
  String recivedData;
  recivedData = read_String(10);
  Serial.print("Read Data:");
  Serial.println(recivedData);
  delay(1000);
}

void writeString(char add,String data)
{
  int _size = data.length();
  int i;
  for(i=0;i<_size;i++)
  {
    EEPROM.write(add+i,data[i]);
  }
  EEPROM.write(add+_size,'\0');   //Add termination null character for String Data
}

String read_String(char add)
{
  int i;
  char data[100]; //Max 100 Bytes
  int len=0;
  unsigned char k;
  k=EEPROM.read(add);
  while(k != '\0' && len<500)   //Read until null character
  {
    k=EEPROM.read(add+len);
    data[len]=k;
    len++;
  }
  data[len]='\0';
  return String(data);
}

```
> -1 votes

---
Tags: esp8266, eeprom
---


# Question
Title: Is there a more elegant way to check highest / lowest sample data?
N00b question,

Is there a better way for readability / elegance / DRY etc to check various sensor values for high/low record value? This code works, but looks like the long way round.

```
  void checkRecord() {

if ( temp.current > temp.high) {
  temp.high = temp.current;
}

if ( temp.current < temp.low) {
  temp.low = temp.current;
}

if ( pressure.current > pressure.high) {
  pressure.high = pressure.current;
}

if ( pressure.current < pressure.low) {
  pressure.low = pressure.current;
}
if ( humidity.current > humidity.high) {
  humidity.high = humidity.current;
}

if ( humidity.current < humidity.low) {
  humidity.low = humidity.current;
}

if ( rainfall.current > rainfall.high) {
  rainfall.high = rainfall.current;
}

if ( rainfall.current < rainfall.low) {
  rainfall.low = rainfall.current;
}
if ( altitude.current > altitude.high) {
  altitude.high = altitude.current;
}

if ( altitude.current < altitude.low) {
  altitude.low = altitude.current;
}
}

```

Thanks!

# Answer
This is a variation on the `struct` idea with an object-oriented flavor.

If you put the current, low and high values of any sensor inside a `struct`, you could also morph this `struct` into a `class` and give it an `update()` method that, in addition to updating the current value, keeps the low and high updated:

```
class LowHigh
{
public:
    LowHigh() : current(0), low(INFINITY), high(-INFINITY) {}
    void update(float value) {
        current = value;
        if (current < low)
            low = current;
        if (current > high)
            high = current;
    }
    float get_low() { return low; }
    float get_high() { return high; }
private:
    float current, low, high;
};

```

I am assuming `float` data here, you may have to adapt to whatever type is appropriate for your sensors.

You would use the class as this:

```
LowHigh temp, pressure, humidity, rainfall, altitude;

void loop()
{
    temp.update(temp_sensor.get_reading());
    pressure.update(pressure_sensor.get_reading());
    humidity.update(humidity_sensor.get_reading());
    // ...
}

```
> 4 votes

# Answer
You could write something like:

```
temp.high = (temp.current > temp.high) ? temp.current : temp.high;
temp.low  = (temp.current < temp.low) ? temp.current : temp.low;
...

```

Most of the time there are min/max macros defined already like:

```
#define MAX(a, b)   ((a > b) ? a : b)
#define MIN(a, b)   ((a < b) ? a : b)

```

So you can then simply write:

```
temp.high = MAX(temp.current, temp.high);
temp.low  = MIN(temp.current, temp.low);
...

```

Which expands to the exact code as given above.
> 2 votes

# Answer
If the temperature, pressure, humidity, rainfall, and altitude structs were elements of an array of structs, you could iterate over those elements setting each one's high and low values with only two handwritten 'if-then' statements. If you also used an enum to name the indices of the structs, then in other parts of your code you could address each of them by a descriptive name:

```
// Declare a data struct and define an array of them.
struct {
   int16_t current;
   int16_t high;
   int16_t low;
} data[5] = {0, 0, 0, 0, 0};

// Name the structs by index
enum kind {
   temperature = 0,
   pressure,
   humidity,
   rainfall,
   altitude
};

// Assign one kind of data:
data[temperature].current = getTermperature();

// Set maxes & mins for all of the kinds of data:
for( i = 0; i < sizeof(data)/sizeof(data[0])); ++i ){
   if ( data[i].current > data.high) {
      data[i].high = data[i].current;
   }

   if ( data[i].current < data[i].low) {
      data[i].low = data[i].current;
   }
}

```

Update:

> I'm strugling with the data\[5\] {0,0...} part in struct.

I can't see your whole sketch but you probably have allocated 5 separate structs named "temp", "pressure", ... , etc. I'm suggesting you allocate an array of 5 structs (which I collectively called "data"), one for each of your individual ones. I included an initializer ( '= {0,0,0,0,0}') to set everything to zero before the start of the run.

> all of enum kind{} and how it becomes data\[pressure\] etc.,

The enum is a quick way to make 5 symbols that stand for consecutive integers, in this case, the index into the array of each struct, using a descriptive name for that struct's data. So 'data\[pressure\]' is the same as data\[1\] (in this case) but is more understandable.

> the sizeof(data)/sizeof(data\[0\]) in the loop

That expression gives the number of structs in the array (the total byte-size of the array divided by the byte-size of one struct). We could write '5' instead, but when you someday add another member or two (wind\_direction, wind\_speed, perhaps?), you'd have to remember to also fix your for() loop. By using this calculation, the compiler will do it for you, leaving you one less opportunity to make a mistake you'd then need to debug.

> and finally I think altitude.high in the if statement is a paste typo? should be data\[i\].high?

Absolutely right! Fixed now.

Update:

> For defining initial values can you just assign an initial value in the struct such as int16\_t low = INFINITY; and so on instead of {0,0,0,0,0}?

Yes - Without knowing your data and application, I chose the simplest initializer. The full syntax to do what you want would look like this:

```
// Declare a data struct and define an array of them.
struct {
   int16_t current;
   int16_t high;
   int16_t low;
} data[5] = {
  {0, 0, INFINITY},
  {0, 0, INFINITY},
  {0, 0, INFINITY},
  {0, 0, INFINITY},
  {0, 0, INFINITY}
};

```

You don't need (and may not) specify each data type and name; the struct declaration already provides that information. The initializers are positional and each one must be compatible with the data-type it matches up to.
> 0 votes

---
Tags: code-optimization
---


# Question
Title: What am I missing? Send data from Matlab to Arduino to Micro SD
First off. This is not in any way a class assignment. This is my own personal work and research. I just want to get that out of the way.

I am learning how to use Matlab with various Arduino projects. I am a seasoned Matlab user but I am fairly new to the entire Arduino space.

I am trying to send some numerical data from Matlab (via a GUI) to my Arduino Uno and have the Arduino write it to my micro SC card. This is a temporary step to my larger project. However, there is no need to go into those specifics as they are outside of the scope of my issues.

I am fairly confident that the Matlab code works and the Arduino code is slightly modified from another project I did where I wrote and read random numbers from my micro SD card.

However, as I run the Matlab code, the Arduino blinks as if it is receiving the data but after I check the micro SD card it remains blank.

I am confident that my Arduino is wired correctly to my micro SD card adapter since this remains the same from my prior project.

Therefore, I am sure I am missing something trivial to get it to work.

I have researched several websites on the subject and their method and mine seem to align very well.

I am fairly certain the problem is in the conditional statement:

```
if (Serial.available() > 0) {

```

As you will see.

The Matlab code is below:

```
arduinoCom = serial('COM3', 'BaudRate', 115200);
sendData = 5;
fopen(arduinoCom);
fprintf(arduinoCom,'%i',sendData); %this will send 5 to the arduino
fclose(arduinoCom);
delete(arduinoCom);

```

The Arduino code is as follows:

```
#include <SD.h> // load SD library

int chipSelect = 4;  // Chip select pin for the MicroSD Card Adapter
int incomingByte = 0; // for incoming serial data.
File SDF; // Serial data received is saved here.

void setup() {
     Serial.begin(115200); // start serial connection to print out debug messages and data
     pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode
     if (!SD.begin(chipSelect)) { // Initialize SD card
        Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
     }
     while (!Serial) {
     }
}

void loop() {
        // Open file, Write data, Close file only when you receive data
        if (Serial.available() > 0) {
           incomingByte = Serial.read();
           SDF = SD.open("SerialDataFile.txt", FILE_WRITE); // open "SerialDataFile.txt" to write data
           SDF.println(incomingByte, DEC); // write ASCII-encoded decimal number to file
           SDF.close(); // close file
           }
}

```

The expected result would be a file "SerialDataFile.txt" stored on my micro SD card with the value 5.

Thank you for your help!

# Answer
The board resets on new USB connection with fopen. Wait 2 secs between fopen and fprintf in Mathlab code.
> 0 votes

---
Tags: arduino-uno, matlab
---


title: Arduino Driving Pump via MOSFET

text:
# Question
Title: Arduino Driving Pump via MOSFET
I want to turn on a pump that is running 12V and draws a current of max 1.7A with my Arduino Uno.

To do this, I bought the RFP30N06LE MOSFET and followed these instructions to wire it all up.

I connected the red wire from the pump to VIN of the Arduino and plugged a 12V 2A power brick into the Arduino. However, when I put the output pin to HIGH, the pump only pumps weakly and the MOSFET gets very hot.

When I connect the pump straight to VIN and GND, it works as expected, so the Arduino is able to provide the required current. I'm thinking that there is something to the MOSFET that I am not understanding correctly. I measured VGS at 4.5V, so the MOSFET should be able to handle the current. Is there anything I am missing?

This is the wiring:

This is the (very simple) sketch I'm using to test it all:

```
#define PIN_PUMP_ON 7

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

void loop() {
  digitalWrite(PIN_PUMP_ON, HIGH);
  delay(1000);
}

```

# Answer
> 4 votes
Vin is only rated to supply at most 1A due to the reverse polarity protection diode in series from the barrel jack to the Vin pin. You try and draw 1.7A thru that and you may smoke it. The Vin header is also only rated for 1A.

Connect the motor to the supply directly. The Arduino Gnd must also connect to the supply. R2 limits Arduino IO pin current to a safe level. R1 keeps the MOSFET off while the Arduino boots up. Diode dissipates motor generated current when the MOSFET goes from On to Off. The RFP30N06LE looks to be rated for full turn on with Vgs of 5V, and Rds of 47milliohm, that part should be ok to use.

Powering the Arduino from the same source as the motor may cause issues. If you can power the Arduino from USB or a seperate battery pack and not the same 12V that powers the motor, that will probably yield better results, especially if the 12V droops at all under heavy loads from the motor. That could cause Arduino resets.

simulate this circuit – Schematic created using CircuitLab

# Answer
> 1 votes
Rewire the motor power so that it is not using any Arduino Power or GND pins. Only connect the MOSFET gate to an Arduino pin using a suitable resistor. The MOSFET drain needs to go directly to your power supply ground. This way you're not cooking your Arduino. A relay instead of the MOSFET would prevent the MOSFET resistance from reducing the power of your motor.

The 3 big pins under the Arduino's power connector (2 GND and 1 +V) can be used to power your motor, just solder directly to them for Motor +V and GND for MOSFET drain. This bypasses the Arduino's diode.

# Answer
> 0 votes
Under no circumstances should you connect the motor to VIN on the Arduino. A motor draws far too much current.

You want to have the ground on the arduino connected to the ground for the motor, but you want different positive supplies for the 2 different devices. You also need to make sure you have a properly sized protection diode wired in parallel with the motor, but pointing against the flow of current.

---
Tags: arduino-uno, mosfet
---


title: Forbidden characters in TCP/IP

text:
# Question
Title: Forbidden characters in TCP/IP
I'm trying to send data from my ESP8266 to a NodeJS TCP server, the connection and basic charakters (48-90) are working fine, but if I use others like ASCII-Code (0,1,2,3...) I don't get any usefull data out of it. So what I was thinking about that there are some character which aren't allowed to send over TCP/IP.

By the way, I'm using this to write to the server, and I work with the standard WiFi Client library

```
char arr[255]
for(int i = 0; i < 255; i++){
   arr[i] = (char)i;
}
client.print(arr);

```

Nodejs File:

```
// Load the TCP Library
net = require('net');

var mysql = require('mysql');

// Keep track of the chat clients
var clients = [];
var uploadCounter = 0;

initMySQLConnection();

// Start a TCP Server
net.createServer(function (socket) {

    // Identify this client
    socket.name = socket.remoteAddress + ":" + socket.remotePort

    // Put this new client in the list
    clients.push(socket);

    // Send a nice welcome message and announce
    socket.write("Welcome " + socket.name + "\n");
    broadcast(socket.name + " connected\n", socket);

    // Handle incoming messages from clients.
    socket.on('data', function (data) {
        broadcast(">> " + data, socket);

        uploadData(data);
    });

    // Remove the client from the list when it leaves
    socket.on('end', function () {
        clients.splice(clients.indexOf(socket), 1);
        broadcast(socket.name + " disconnected.\n\n");
    });

    // Send a message to all clients
    function broadcast(message, sender) {
        clients.forEach(function (client) {
            // Don't want to send it to sender
            if (client === sender) return;
            //client.write(message);
        });
        // Log it to the server output too
        process.stdout.write(message)
    }

}).listen(10101);

// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 10101\n");

var connection;
function initMySQLConnection() {
    connection = mysql.createConnection({
        host: "host",
        user: "user",
        password: "pass",
        database: "database"
    });

    connection.connect(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
        }
    });

    connection.on('error', function (err) {
        console.log('db error', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
                                    // lost due to either server restart, or a
        } else {                                      // connnection idle timeout (the wait_timeout
            throw err;                                  // server variable configures this)
        }
    });

    setInterval(function () {
        connection.query('SELECT 1');
    }, 60000);
}

function uploadData(data) {
    data = String(data);

    console.log("Package Length: " + data.length);
    console.log("GOT ASCII CODE: ");
    for (var i = 0; i < 255; i++) {
        console.log(data.charCodeAt(i));
    }

    //upload Code
}

```

# Answer
> 0 votes
The `print` function takes an array of characters as zero terminated c-string. It prints until a byte with value 0. You have zero at `arr[0]` so it is an empty string.

To send bytes, `write` function is used. The `print` functions convert parameters to text or expect text as zero terminated char array.

In your case it should be `client.write(arr, length);` where `length` is the number of bytes you want to send from the buffer `arr`.

---
Tags: esp8266, tcpip
---


title: DHT11 Reading Too High Values

text:
# Question
Title: DHT11 Reading Too High Values
When I run the program, there are no syntax errors or anything. All it does is give me values for the temperature in the hundreds. I don't know if there is a way to turn these abstract and unexpected values into the actual temperature.

I originally expected that it would print out the temperature around 20 Celsius, but instead, it prints around 600. This is my code:

```
#include <Adafruit_Sensor.h>
#include "DHT.h"

int sensor_pin = A0; // Analog Pin sensor is connected to
int output_value ;

void setup(){

  Serial.begin(9600);
  delay(5000);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(5000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    output_value= analogRead(sensor_pin);

    Serial.println("temperature = ");
    Serial.println(output_value);
    Serial.println("*C");
    if (output_value < 60) {
    Serial.println("Increase temperature by ");
    Serial.println(output_value);
    Serial.println("*C");
} else {
    Serial.println("Temperature does not need to be increased.");
}

    delay(5000);

}// end loop()

```

# Answer
> 3 votes
The DHT11 is a **digital** device. You cannot read from it with `analogRead()`.

While temperature is an *analog* value, that's not how the DHT11 communicates with an Arduino. There is a specific digital protocol.

In your code, it appears you have added the headers for the Adafruit Sensor library and DHT library, but you never actually call the functions provided therein.

The Adafruit repository for the DHT sensor library has an example: https://github.com/adafruit/DHT-sensor-library/blob/master/examples/DHTtester/DHTtester.ino

You can see how to create an object from the `DHT` class, and how to call it's member functions, such as `readTemperature()` and so on.

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


title: How to initialize and run PCA9685?

text:
# Question
Title: How to initialize and run PCA9685?
I'm trying to write a simple code for initializing and running the PCA9685. I tested the board with Adafruit library and it's working.

But I just want to develop a simple code to include it in my various modules library for future projects.

I wrote a code, but I think I'm not understanding the work of the internal registers.

But according to the datasheet I configured only the auto increment and left the rest to default settings. Then I headed up to the last registers which are the `all_led_on` and `all_led_off`as wanting to run the outputs on/off to blink the LEDs. But I think these two registers are for enabling/disabling the pins. Is that right?

This is my code:

```
void pca9685_init(void){
    uint8_t i,val[]={0x20,0x04};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_MODE1);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

void pca9685_all_on(void){
    uint8_t i,val[]={0x00,0x10};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_ALL_LED_ON_L);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

void pca9685_all_off(void){
    uint8_t i,val[]={0x00,0x10};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_ALL_LED_OFF_L);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

```

# Answer
The registers aren't for just turning the LEDs on or off. They are for setting the ON and OFF times of the PWM. Bit 12 of each combined value is used as a "full" setting, so:

To set the LEDs on to full brightness you need to set:

* `PCA9685_ALL_LED_OFF_L` to 0x00
* `PCA9685_ALL_LED_OFF_H` to 0x00
* `PCA9685_ALL_LED_ON_L` to 0x00
* `PCA9685_ALL_LED_ON_H` to 0x10

This sets the off time to 0 counts and the on to be "full on".

It doesn't really matter what value you set the OFF to as long as you set ON to "full on" and off *isn't* set to "full off".

For off you should set the ON to 0 and the OFF to "full off" (reverse the above settings).

Section 7.3.3 of the datasheet says:

> The turn-on time of each LED driver output and the duty cycle of PWM can be controlled independently using the LEDn\_ON and LEDn\_OFF registers.
>
> There will be two 12-bit registers per LED output. These registers will be programmed by the user. Both registers will hold a value from 0 to 4095. One 12-bit register will hold a value for the ON time and the other 12-bit register will hold the value for the OFF time. The ON and OFF times are compared with the value of a 12-bit counter that will be running continuously from 0000h to 0FFFh (0 to 4095 decimal).
>
> **Update on ACK requires all 4 PWM channel registers to be loaded before outputs will change on the last ACK.**
>
> The ON time, which is programmable, will be the time the LED output will be asserted and the OFF time, which is also programmable, will be the time when the LED output will be negated. In this way, the phase shift becomes completely programmable. The resolution for the phase shift is 1⁄ 4096 of the target frequency.

So you *have* to set all 4 registers together for anything to happen.

There are also some examples shown in the datasheet as well which explain it better.

In simple terms:

* There is a free-running counter that counts from 0 to 4095
* When the ON time matches the counter the LED turns on.
* When the OFF time matches the counter the LED turns off.
* If a channel is "FULL OFF" it will be off regardless.
* If a channel is "FULL ON" and *not* "FULL OFF" it will be on regardless.
* **"FULL OFF" always takes priority over everything else - even "FULL ON".**

Some simple examples:

* All off: ON=0x0000 OFF=0x1000
* All on full: ON=0x1000 OFF=0x0000
* 50% duty: ON=0x0000 OFF=0x0800
* 25% duty: ON=0x0000 OFF=0x0400
* 25% duty with phase shift: ON=0x0100 OFF=0x0500
> 3 votes

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


# Question
Title: Having really weird experience with string concat
Having really bad day with concat. I'm not quite sure where i did wrong.. Have a look at my function below.

```
void sim900aSendHttp(String bid, String lati, String longi) {
  Serial.println("BUSID:"+bid+",LAT:"+lati+"LONG:"+longi);
  String httpget = "http://uumresearch.com/bustracking/update_location.php?busid="+bid+"&latitude="+lati+"&longitude="+longi+"";
  //String httpget = "http://uumresearch.com/bustracking/update_location.php?busid=KDF8860&latitude=6.533415&longitude=106.33345";
  Serial.println(httpget);
  serialSIM800.println("AT+HTTPPARA=\"URL\",\"" + httpget + "\"");
  delay(3000);
  serialSIM800.println("AT+HTTPACTION=0");
  delay(8000);
}

```

The problem is with:

```
String httpget = "http://uumresearch.com/bustracking/update_location.php?busid="+bid+"&latitude="+lati+"&longitude="+longi+"";

```

where serial monitor only shows

```
http://uumresearch.com/bustracking/update_location.php?busid=KDF8860

```

missing "lat" and "longi" variables in the string concat.

Both variable confirmed available to the function as printed by

```
Serial.println("BUSID:"+bid+",LAT:"+lati+"LONG:"+longi);

```

# Answer
> 1 votes
`+` on `const char *` increments the pointer. only String has `+` overloaded as concatenation of the right operand (not left). so `"abc" + str + "efg"` will not work even if `str` is String. What will work is `String("abc") + str + "efg"`, but small Strings will fragment the heap memory of the MCU very fast and the sketch will crash.

Print the parts directly to `serialSIM800` or use `snprintf` to build the strings or try CStringBuilder from my StreamLib

---
Tags: arduino-ide
---


# Question
Title: How to calculate battery usage of my arduino project?
I want to measure power consumption and calculate the mAH value to know how much time would my battery can run the circuit. I only got a multimeter and DC power supply.(Im not sure if this is enough to measure)

My project has a temp sensor and measures it every 15 mins. It's going to deep sleep mode and wakes up again to measure.

So how to measure the mAH for this circiut?

# Answer
> 3 votes
I suggest using a second Arduino to make yourself an "Energy Meter".

Get a very small power resistor (0.1 Ohm) and power your project through it.

Second Arduino will measure voltage drop on it and that way you can get the current that goes through it using Ohms law. You can also measure the battery/power supply voltage. Knowing those two values and `micros` each `loop` you can calculate actual hourly power consumption of the device.

# Answer
> 0 votes
Use the multimeter to measure the current. Put it in mA current mode, and wire it in series from the DC power supply + to the Arduino positive connection. With an Uno, readings will likly be in the 10s of mA all the time, and maybe a little higher when not in deep sleep mode. This assumes you are not powering the Uno from the USB port.

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


title: Arduino I2C Register Read

text:
# Question
Title: Arduino I2C Register Read
I am trying to read a specific register from a device. In this case I am trying to read the value stored in register 0X1F from slave device 0x08. On the scope I see writes for

```
ADDRESS_SLAVE(Wire.beginTransmission), ADDRESS_TESTCOMP0 (Wire.write)

```

and

```
ADDRESS_TESTCOMP0 (Wire.requestFrom(ADDRESS_TESTCOMP0,8))

```

but I don't see the register values reading out. Here is my code:

```
#include <Wire.h>

int ADDRESS_SLAVE = 0X08;
int ADDRESS_TESTCOMP0 = 0X1F;

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

void loop()
{
   Wire.beginTransmission(byte(ADDRESS_SLAVE));
   Wire.write(byte(ADDRESS_TESTCOMP0));
   Wire.endTransmission(byte(ADDRESS_TESTCOMP0));

   Wire.requestFrom(ADDRESS_TESTCOMP0,8);
   char read = Wire.read();
   Serial.println(read);

   delay(1000);
}

```

# Answer
> 2 votes
errors corrected

```
#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

void setup()
{
 Wire.begin();
 Wire.setClock(400000); // set I2C 'full-speed'
 Serial.begin(9600);
}

void loop()
{
   Wire.beginTransmission(ADDRESS_SLAVE);
   Wire.write(REGISTER_XY);  // set register for read
   Wire.endTransmission(false); // false to not release the line

   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH); // request bytes from register XY
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}

```

if you read only one register of the device, you can setup the device in `setup()` and in `loop()` only read the data from the register:

```
#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

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

  Wire.begin();
  Wire.setClock(400000); // set I2C 'full-speed'

  Wire.beginTransmission(ADDRESS_SLAVE);
  Wire.write(REGISTER_XY);  // set register for read
  Wire.endTransmission();
}

void loop() {
   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH);
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}

```

---
Tags: arduino-mega
---


# Question
Title: Read Serial data from an arduino with c code
I am trying to receive data through the serial port from my SBC (a TS-7200), i am working with linux and handle serial communication using C/C++.To send data to the SBC i'am using an arduino uno.

So basically the arduino is printing ASCII text data through Pin1 (Hardware Serial) in a loop with a 3ms delay.

From the SBC i read raw data in no canonical mode, ( in the code below are the parameters and configurations for the serial port) i'am trying to read one characters at a time, following the example from this page : https:/ from this page/chrisheydrick.com/2012/06/17/how-to-read-serial-data-from-an-arduino-in-linux-with-c-part-3/.

but when i run the code it print the number 2 as 3, and the number 3 as f, I am not able to read ASCII characters.

I have tried several things but I have not been able to find the problem, Hope someone can help me.

Here is the Arduino code:

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

 void setup() {

    Serial.begin(9600);
    mySerial.begin(9600);

  }

 void loop() {

   Serial.print(2);

   delay(3000);

   Serial.print(3);

   delay(3000);

}

```

The c code from the linux side:

```
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>

char *portname = "/dev/ttyAM1";
char buf[256];

int main(int argc, char *argv[])
{
  int fd,stop = 0;

/* Open the file descriptor in non-blocking mode */
fd = open(portname, O_RDWR | O_NOCTTY);

/* Set up the control structure */
struct termios toptions;

/* Get currently set options for the tty */
tcgetattr(fd, &toptions);

/* Set custom options */

/* 9600 baud */
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/* 8 bits, no parity, no stop bits */
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/* no hardware flow control */
toptions.c_cflag &= ~CRTSCTS;
/* enable receiver, ignore status lines */
toptions.c_cflag |= CREAD | CLOCAL;
/* disable input/output flow control, disable restart chars */
toptions.c_iflag &= ~(IXON | IXOFF | IXANY);
/* disable canonical input, disable echo,
   disable visually erase chars,
   disable terminal-generated signals */
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
/* disable output processing */
toptions.c_oflag &= ~OPOST;

/* wait for 1 character to come in before read returns */
/* WARNING! THIS CAUSES THE read() TO BLOCK UNTIL ALL */
/* CHARACTERS HAVE COME IN! */
toptions.c_cc[VMIN] = 1;
/* no minimum time to wait before read returns */
toptions.c_cc[VTIME] = 0;

/* commit the options */
tcsetattr(fd, TCSANOW, &toptions);

/* Wait for the Arduino to reset */
usleep(1000*1000);
/* Flush anything already in the serial buffer */
tcflush(fd, TCIFLUSH);

while(stop == 0){

  /* read up to 128 bytes from the fd */
  int n = read(fd, &buf, 128);
  usleep(3000*1000);
  /* print how many bytes read */
  printf("%i bytes got read...\n", n);
  /* print what's in the buffer */
  printf("Buffer contains...\n%s\n", buf);
 }
 return 0;
}

```

This is what i see:

```
2 bytes got read...
Buffer contains...
f
2 bytes got read...
Buffer contains...
3
2 bytes got read...
Buffer contains...
f
2 bytes got read...
Buffer contains...
3

```

# Answer
> 1 votes
RS232 uses +/- 12V (or sometimes +/- 5V), and is not compatible with TTL Serial, which uses 0V/5V. Also +12V in RS232 represents `0` and -12V represents `1`; inverted from normal TTL.

---
Tags: arduino-uno, serial, c, linux
---


title: Myoware reading multiple fingers?

text:
# Question
Title: Myoware reading multiple fingers?
So I have recently been trying to use the Myoware Muscle sensor to control an 3d printed arm, but it is only able to read the muscle of the entire arm. Is there anyway i could make the Myoware sensor read different fingers at the same time?

# Answer
> 1 votes
Our MyoWare sensor is a single channel EMG sensor and should only be used to detect a single muscle at a time. BUT, if you have 5 sensors, then you can indeed use them to measure each finger's flexion or extension individually. It would take 10 sensors to do both flexion and extension of all your fingers.

However, keep in mind that there are many muscle groups on top of each other in the forearm (e.g. finger muscles, wrist muscles, forearm rotation muscles) and the MyoWare uses surface electrodes. The sensor will detect the activity of any muscle(s) that get activated under the area of the electrodes and you could get a lot of cross-talk between these muscles. For example, the muscles that control your wrist are under the muscles that control your fingers. Any activation of your wrist muscles when trying to measure the finger muscles would cause the sensor to falsely register activity for your finger muscles.

If you are thinking of using it to detect finger position, I would advise using a flex sensor or something similar than a muscle sensor. Muscle sensor sensors are usually used to detect force or as an on/off switch given a threshold value to activate the switch.

---
Tags: sensors
---


# Question
Title: Powering LED strips with two power banks and they randomly change different colors when i use the second power bank
So for one of my projects i want to power LED strips with power banks but once i try use the second power bank the LEDs half way through patterns jump to random different colors and then go back to the code im using to make sure they work, I dont think its a code issue as when i plug the power into my MEGA it works fine. I would use the MEGA to power the strips but i need 3 power sources to keep my strips at maximum brightness. would this be a voltage drop issue?

When I connected it to my 3 usb port power bank it works perfectly fine so it might be different currents causing it to jump im not to sure if im correct but its definitely something to do with using another power supply is causing my LEDs to randomly change multiple different colors randomly i just cant see if its a current or voltage issue. Any help would be greatly appreciated.

block diagram link

# Answer
> 1 votes
These are USB power-banks? You need a way to tie the grounds together somehow. Try tying all the ground lines from your LED strips together and also connecting a wire from one of the LED strips to a ground line on your Arduino.

The USB connections should connect ground between the power bank and the device it's connected to, so by tying the grounds on the LED strips together, that should connect the grounds on the power banks as well.

---
Tags: arduino-mega
---


# Question
Title: Arduino Mega PWM - 100ms Period - SSR and Heater
I'm not very advanced in Arduino "core" functions, so I need your help.

I'm using a Solid State Relay in order to control a heating element, with a PID Library (PID\_v1.h) to obtain the OUTPUT of the PWM.

The code itself is not a problem, so that I'll not post it here.

Summarizing, this is the code where I send the PWM to the Relay: analogWrite(RELAY\_OUT, outputValue);

I've found in this article that: "The analogWrite function is used to set the duty cycle of a PWM pulse train that operates at approximately 500 Hz. Thus, with a frequency = 500 Hz, the period is = 2 ms."

My concern is that the response time of the relay (FOTEK SSR-60 DA) is 10ms (to turn on or to turn off), but I DO NOT KNOW how to configure Arduino PWM to work accordingly to this Relay, in a period greater than 10ms.

I've found in some pages some people changing the clock frequency in order to have a "fast pwm", but I need to know what values I have to use to get a "slow pwm", for a period greater then 10ms.

Can you help me with that? I've been searching a lot for this answer, but I could not find any "definitive"answer.

Thank you in advance!

Everton

# Answer
I'd suggest using the TimerOne library.

Call `Timer1.initialize(10000)` in `setup`. Then call `Timer1.pwm(pin, duty);` in your loop. Where `pin` is 11, 12, or 13 for the MEGA, and `duty` is between 0 and 1023.
> 1 votes

# Answer
Use ATmega PWM registers directly, in order to achieve about 100Hz PWM (10ms period).

This is an example of 10ms PWM period with 50% duty cycle on Arduino Mega (Pin D11):

```
/* Setup PWM pin D11 as Output */
   pinMode(11, OUTPUT); //D11/PB5/OC1A

   /* Timer/Counter Control Registers: TCCRxx */
   TCCR1A = 0;            //Clear register
   TCCR1B = 0;            //Timer/Counter stopped (CS12=0,CS11=0,CS10=0)

   TCCR1A = (1<<WGM11)  | //Fast PWM mode 16-bit (WGM13=1,WGM12=1,WGM11=1,WGM10=0)
            (1<<COM1A1);  //Set output HIGH during Duty Cycle peiod of OC1A

   TCCR1B = 2                     |   //Prescaler: divide by 8
            (1<<WGM12)            |
            (1<<WGM13);

   /* Set PWM frequency */
   ICR1   = 20000; // Period expressed in tick (10ms)

   /* Clear PWM counter */
   TCNT1  = 0;

   /* Set duty cycle to 50% */
   OCR1A  = 10000;

```

I didn't test it, but I think that it's correct.

Read this and this for details.
> 0 votes

---
Tags: pwm
---


title: How to publish on Pubnub with node mcu?

text:
# Question
Title: How to publish on Pubnub with node mcu?
I have node mcu and i am trying to use the example code on github and pubnub blog to send a msg as an experiment but can't figure how to do it.

I used 2 example as the reference - https://github.com/pubnub/arduino , https://www.pubnub.com/docs/arduino/data-streams-publish-and-subscribe

Here is the code which i have. I modified it to include some libraries and my API keys. Let me know what changes i have to make:-

```
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP

#include <PubNub.h>

String pubkey = "pub-c-4a9cdbca-5688-4939-a852-f63cf6743980";
String subkey = "sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094";
String pubchannel = "sec-c-NmFiYjliODYtMTc3Mi00YTMzLTg0OWMtMDgzYjE2ZGUwNzg5";

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

Error:-
node_mcu_test_code:44:46: error: 'subchannel' was not declared in this scope

     PubSubClient *sclient = PubNub.subscribe(subchannel);

                                              ^

node_mcu_test_code:54:14: error: 'class PubSubClient' has no member named 'stop'

     sclient->stop();

              ^

exit status 1
no matching function for call to 'PubNub::begin(String&, String&)'

```

# Answer
The pubchannel and subchannel can be defined as any values in char variable.

Here is the right code:-

```
const char * pubkey = "publisher key from your account";
const char * subkey = "subscriber key from your account";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";

```

Then the error disappeared
> 1 votes

---
Tags: esp8266, wifi, nodemcu
---


# Question
Title: Replace mechanical switch with electrical switch or relay
I have a remote controller for a portable heater, and working on a small project to be able to control the fan on/off from an arduino with Bluetooh HM-10 module. I thought a solenoid might work by mounting on top of the remote but it doesnt have enough force, I want to remove/desolder the mechanical button and figure out a way to control it without the switch but kind dont really know what circuit I should use, kind of just learning how to use arduino.

Images of remote and button traces below.

Any idea how I could wire this up to arduino via some switch/relay circuit? Any circuit design / schematic would be helpful

# Answer
I would unsolder the switch then solder in a FET in the configuration shown below. The FET will act as a switch and may be controlled with any digital output from your Arduino board. When selecting a FET makes sure you find something that will fit the foot print you have to work with on your board, and the gate-source threshold voltage is rated to handled 5V.
> 2 votes

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


# Question
Title: I need help makeing a light flash while a stepper is constantly moving
The starter code.

```
#include <Stepper.h>

const int stepsPerRevolution = 120;  // change this to fit the number
// for your motor of steps per revolution

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;         // number of steps the motor has taken
int LEDPin = 13;
void setup() {
  // initialize the serial port:
  Serial.begin(9600);
  pinMode(LEDPin,OUTPUT);
}

void loop() {
  // step one step:
  myStepper.step(1);
  Serial.print("steps:");
  Serial.println(stepCount=456);
  stepCount++;
  delay(35);
}

```

I want a light to flash in 15 sec increments while my stepper keeps moving. I basically want to combine that code with this one:

```
int LEDPin = 13;
void setup()
  pinMode(LEDPin,OUTPUT);
void loop()
{
  digitalWrite(LEDPin,HIGH);
  delay(6000);
  digitalWrite(LEDPin,LOW);
  delay(6000);
}

```

# Answer
In your loop() function, call two new functions. Let's call those maybeStep() and maybeBlink(). Each one of those reads the time, millis(), and subtracts the saved time when it last performed its action (stepping or toggling the LED). If that difference is \>= the interval for that action, do the action and update the saved time to the current time.

Remember to make the saved times 'static' (or global) so they won't get over-written when these function return.

The BlinkWithoutDelay example program gives the general idea of how to read the clock instead of calling delay(), to decide when to perform each action.

Update:

> new at Arduino and don't quite know what you mean?

Your loop function would something like this:

```
void loop(){
   maybeStep();
   maybeBlink();
}

```

Notice that loop now does nothing but call your action functions. Here's an outline of one of the action functions:

```
void maybeStep(){
   if the time_now > than the time_we_last_stepped by 35 millisec, then
      step again and store the new time_we_last_stepped;

   return;
}

```

Notice that this function may or may not take a step! It decides whether to step by reading the time and comparing it to the time of the previous step. But either way - step, or no step - it returns quickly. The maybeBlink() function will work exactly the same way: compare the time it last toggled the LED on or off to the amount of time it should wait between toggles. Then either toggle it (and save the time and on/off state) or not, and in any case, return to the loop.

Done this way, your loop() function will call those action function very frequently - way more often than the actions need to take place. Most of those times, nothing will happen. But every once in a while (a "tiny while" in human terms), one of those functions will take a step or switch the LED. If you write your code this way, loop() could call dozens or hundreds of such functions and all of those actions could still take place on time.

The key to this programming technique - called non-blocking programming - is that the action functions be *very brief* . They must decide quickly whether something needs to be done, and either do it or not, then return immediately.
> 0 votes

# Answer
The `delay()` function causes the Arduino program to stop in it's tracks and "count to 100". While it's doing that, it's not doing **anything else**.

Therefore delay is not an option when you're trying to do more than one thing at a time.

you need to rewrite your code to use the `millis()` function to tell if your desired amount of time has passed. something like this:

```
unsigned long nextLEDTime = 0;
bool ledState = false;
#define delay 6000

int LEDPin = 13;
void setup()
  pinMode(LEDPin,OUTPUT);
void loop()
{
  if (millis() >= nextLEDTime) //if it's time to toggle the LED
   {
     ledState = ! ledState;  //Invert the LED state
     digitalWrite(LEDPin, ledState);
     nextLEDTime = millis() + delay;  //Set nextLEDTime to the next time we need to do something
   }
}

```

Then you need to do the same thing with your stepper motor code, creating a separate variable to track the next time you want to do something with the stepper motor.

Put all your code in a single loop function that checks bot the nextLEDTime and the nextStepperMotorTime and takes appropriate action at the correct time for each thing you want to handle.
> 0 votes

---
Tags: arduino-uno, led, stepper, loop
---


# Question
Title: MKR WIFI 1010 Providing 3.3V to breadboard
The Arduino MKR WIFI 1010 product page says "The microcontroller on the MKR WIFI 1010 runs at 3.3V, which means that you must never apply more than 3.3V to its Digital and Analog pins. Care must be taken when connecting sensors and actuators to assure that this limit of 3.3V is never exceeded. Connecting higher voltage signals, like the 5V commonly used with the other Arduino boards, will damage the MKR WIFI 1010."

and yet it only has a 5V pin. I have a sensor that requires a 3.3V pin so I'm guessing my only option is to use a Logic Level Converter.

My question is if the MKR Digital and Analog pins can only take 3.3V, why is there only a 5V pin instead of a 3.3V pin to connect to a breadboard?

# Answer
In short: VCC = 3.3V

The Arduino MKR WiFi 1010 board documentation is not complete. Well, at least they have the warning that the processor is running at 3.3V and the voltage levels of the pins should never be above 3.3V.

The page of the Arduino MKR ZERO has more information in the "documentation" tab. The **VIN** pin is the 5V power input, the **5V** pin is unregulated 5V output (when the board is powered by USB or the VIN pin) and **VCC** is the regulated 3.3V output.

The term "VCC" means that it is the voltage at which the processor is running. Since it is a 3.3V Arduino board, it is the 3.3V voltage pin. That 3.3V should be used to power sensors. The "Tech Specs" tab at the MKR ZERO tells that it can supply up to 600 mA. That is the same for the MKR WiFi 1010, because the same AP2112K-3.3 voltage regulator is used.
> 2 votes

---
Tags: voltage-level
---


# Question
Title: How can I update a sketch to a NodeMCU “over the air” with the Arduino IDE?
I’m trying to use a sketch from this repository which uses MQTT to send a notification to Home-Assistant that acts a “presence sensor”. When the NodeMCU comes into range of the specified SSID, the controller connects to WiFi and sends a MQTT message to home-assistant which can then perform some home automation commands. This code does exactly that. The MQTT messages are sent and received.

What is not working is that I can’t update the sketch over the air (OTA) via the included ArduinoOTA library. After uploading this sketch to the NodeMCU, it connects to WiFi and I am getting a message from the console output that the device is ready for OTA updates. From everything that I’ve read I beleive there is supposed to be an option in the Arduino menus where I can specify that I want to update OTA instead of a com port. How can I enable this in the IDE? Also, is there a way to “connect” to the serial monitor so that I can also see the output OTA?

I’m attaching the sketch for your convenience:

```
////////////////////////////////////////////////////////////////////////////////////////////////////
// Modify these values for your environment
const char* wifiSSID = "wifissid";  // Your WiFi network name
const char* wifiPassword = "wifipassword";  // Your WiFi network password
const char* otaPassword = "myotapassword";  // OTA update password
const char* mqttServer = "192.168.1.2";  // Your MQTT server IP address
const char* mqttUser = ""; // mqtt username, set to "" for no user
const char* mqttPassword = ""; // mqtt password, set to "" for no password
const String mqttNode = "CarPresence"; // Your unique hostname for this device
const String mqttDiscoveryPrefix = "homeassistant"; // Home Assistant MQTT Discovery, see https://home-assistant.io/docs/mqtt/discovery/
////////////////////////////////////////////////////////////////////////////////////////////////////

// Home Assistant MQTT Discovery, see https://home-assistant.io/docs/mqtt/discovery/
// We'll create one binary_sensor device to track MQTT connectivity
const String mqttDiscoBinaryStateTopic = mqttDiscoveryPrefix + "/binary_sensor/" + mqttNode + "/state";
const String mqttDiscoBinaryConfigTopic = mqttDiscoveryPrefix + "/binary_sensor/" + mqttNode + "/config";
// And a sensor for WiFi signal strength
const String mqttDiscoSignalStateTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-signal/state";
const String mqttDiscoSignalConfigTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-signal/config";
// And a sensor for device uptime
const String mqttDiscoUptimeStateTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-uptime/state";
const String mqttDiscoUptimeConfigTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-uptime/config";

// The strings below will spill over the PubSubClient_MAX_PACKET_SIZE 128
// You'll need to manually set MQTT_MAX_PACKET_SIZE in PubSubClient.h to 512
const String mqttDiscoBinaryConfigPayload = "{\"name\": \"" + mqttNode + "\", \"device_class\": \"connectivity\", \"state_topic\": \"" + mqttDiscoBinaryStateTopic + "\"}";
const String mqttDiscoSignalConfigPayload = "{\"name\": \"" + mqttNode + "-signal\", \"state_topic\": \"" + mqttDiscoSignalStateTopic + "\", \"unit_of_measurement\": \"dBm\", \"value_template\": \"{{ value }}\"}";
const String mqttDiscoUptimeConfigPayload = "{\"name\": \"" + mqttNode + "-uptime\", \"state_topic\": \"" + mqttDiscoUptimeStateTopic + "\", \"unit_of_measurement\": \"msec\", \"value_template\": \"{{ value }}\"}";

// Set the signal strength and uptime reporting interval in milliseconds
const unsigned long reportInterval = 5000;
unsigned long reportTimer = millis();

// Set LED "twinkle" time for maximum daylight visibility
const unsigned long twinkleInterval = 50;
unsigned long twinkleTimer = millis();

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <PubSubClient.h>

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);

////////////////////////////////////////////////////////////////////////////////////////////////////
// System setup
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.begin(115200);

  Serial.println("\nHardware initialized, starting program load");

  // Start up networking
  setupWifi();

  // Create server and assign callbacks for MQTT
  mqttClient.setServer(mqttServer, 1883);
  mqttClient.setCallback(mqtt_callback);

  // Start up OTA
  if (otaPassword[0]) {
    setupOTA();
  }

  Serial.println("Initialization complete\n");
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Main execution loop
void loop() {
  // check WiFi connection
  if (WiFi.status() != WL_CONNECTED) {
    setupWifi();
  }

  // check MQTT connection
  if (!mqttClient.connected()) {
    mqttConnect();
  }

  // MQTT client loop
  if (mqttClient.connected()) {
    mqttClient.loop();
  }

  // LED twinkle
  if (mqttClient.connected() && ((millis() - twinkleTimer) >= twinkleInterval)) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    twinkleTimer = millis();
  }

  // Report signal strength and uptime
  if (mqttClient.connected() && ((millis() - reportTimer) >= reportInterval)) {
    String signalStrength = String(WiFi.RSSI());
    String uptimeTimer = String(millis());
    mqttClient.publish(mqttDiscoSignalStateTopic.c_str(), signalStrength.c_str());
    mqttClient.publish(mqttDiscoUptimeStateTopic.c_str(), uptimeTimer.c_str());
    reportTimer = millis();
  }

  // OTA loop
  if (otaPassword[0]) {
    ArduinoOTA.handle();
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions

////////////////////////////////////////////////////////////////////////////////////////////////////
// Handle incoming commands from MQTT
void mqtt_callback(char* topic, byte* payload, unsigned int payloadLength) {
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Connect to WiFi
void setupWifi() {
  Serial.print("Connecting to WiFi network: " + String(wifiSSID));
  WiFi.hostname(mqttNode.c_str());
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifiSSID, wifiPassword);

  while (WiFi.status() != WL_CONNECTED) {
    // Wait 500msec seconds before retrying
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected successfully and assigned IP: " + WiFi.localIP().toString());
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// MQTT connection and subscriptions
void mqttConnect() {
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.println("Attempting MQTT connection to broker: " + String(mqttServer));
  // Attempt to connect to broker, setting last will and testament
  if (mqttClient.connect(mqttNode.c_str(), mqttUser, mqttPassword, mqttDiscoBinaryStateTopic.c_str(), 1, 1, "OFF")) {
    // when connected, record signal strength and reset reporting timer
    String signalStrength = String(WiFi.RSSI());
    reportTimer = millis();
    String uptimeTimer = String(millis());
    // publish MQTT discovery topics and device state
    Serial.println("MQTT discovery connectivity config: [" + mqttDiscoBinaryConfigTopic + "] : [" + mqttDiscoBinaryConfigPayload + "]");
    Serial.println("MQTT discovery connectivity state: [" + mqttDiscoBinaryStateTopic + "] : [ON]");
    Serial.println("MQTT discovery signal config: [" + mqttDiscoSignalConfigTopic + "] : [" + mqttDiscoSignalConfigPayload + "]");
    Serial.println("MQTT discovery signal state: [" + mqttDiscoSignalStateTopic + "] : " + WiFi.RSSI());
    Serial.println("MQTT discovery uptime config: [" + mqttDiscoUptimeConfigTopic + "] : [" + mqttDiscoUptimeConfigPayload + "]");
    Serial.println("MQTT discovery uptime state: [" + mqttDiscoUptimeStateTopic + "] : " + uptimeTimer);
    mqttClient.publish(mqttDiscoUptimeConfigTopic.c_str(), mqttDiscoUptimeConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoUptimeStateTopic.c_str(), uptimeTimer.c_str());
    mqttClient.publish(mqttDiscoBinaryConfigTopic.c_str(), mqttDiscoBinaryConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoBinaryStateTopic.c_str(), "ON");
    mqttClient.publish(mqttDiscoSignalConfigTopic.c_str(), mqttDiscoSignalConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoSignalStateTopic.c_str(), signalStrength.c_str());
    Serial.println("MQTT connected");
    digitalWrite(LED_BUILTIN, LOW);
  }
  else {
    Serial.println("MQTT connection failed, rc=" + String(mqttClient.state()));
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// (mostly) boilerplate OTA setup from library examples
void setupOTA() {
  // Start up OTA
  // ArduinoOTA.setPort(8266); // Port defaults to 8266
  ArduinoOTA.setHostname(mqttNode.c_str());
  ArduinoOTA.setPassword(otaPassword);

  ArduinoOTA.onStart([]() {
    Serial.println("ESP OTA:  update start");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("ESP OTA:  update complete");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    //Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.println("ESP OTA:  ERROR code " + String(error));
    if (error == OTA_AUTH_ERROR) Serial.println("ESP OTA:  ERROR - Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("ESP OTA:  ERROR - Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("ESP OTA:  ERROR - Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("ESP OTA:  ERROR - Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("ESP OTA:  ERROR - End Failed");
  });
  ArduinoOTA.begin();
  Serial.println("ESP OTA:  Over the Air firmware update ready");
}

```

# Answer
> 2 votes
Follow the instruction here https://arduino-esp8266.readthedocs.io/en/latest/ota\_updates/readme.html#application-example

First load the OTA example specified. Do not waste your time implementing it in your code until you have the supplied example working.

If you are running Windows then it helps to have an application called Bonjour Browser. The OTA method makes use of mDNS. I use Bonjour Browser to confirm that the ESP is being seen. Then I go to ports in the IDE and there is an entry for the newly added OTA device.

Select the entry instead of the com ports. Then compile and upload.

If you get an error then do a power cycle on the ESP board. You should only need to do this once after the serial upload.

I use this method but sometimes the device does not appear below the com listed. I have had to close and restart the IDE to refresh the device listing. (I think this is a Windows issue) Because of this I prefer the webupdater method. https://arduino-esp8266.readthedocs.io/en/latest/ota\_updates/readme.html#web-browser

# Answer
> 0 votes
Done this form a Linux laptop's command line.

For uploading to Arduino boards, I have been using (via the usual USB port connection) the command line methods as detailed at: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc For the OTA method of uploading to the ESP, I just chanced to discover the following method.

As the argument to "--port", I just used the ip of the wifi connected ESP board.

Let us say I want to upload a sketch "myexample1.ino" to my ESP8266 board "ESP-01 (1MB)" having OTA firmware on it. Am using Arduino 1.8.8 and ESP8266 community version 2.4.2. As already stated, the ESP-01 has the example sketch "BasicOTA.ino" uploaded to it via the usual USB port. Now, the ESP-01 is *not* connected via USB. It is connected to my wifi router at an ip (say, 192.168.22.221). The following command successfully uploaded the code:

~/Arduino/myexample1 $ arduino --upload myexample1.ino --port 192.168.22.221

Just felt like sharing a nice experience not found reported elsewhere on the internet.

---
Tags: arduino-ide, nodemcu
---


# Question
Title: SOLVED: Strange phenomenon with avrdude: stk500v2_ReceiveMessage(): timeout only with ATmega250 on windows 7x64
I know this problem has been reported multiple times but in my case I think there is a different light on it.
My desktop is a w7x64 box and I also have a notebook with w10.
Both system have the arduino IDE 1.8.5 with the latest updates.
The desktop though has more boards and drivers as it is my main development system.
I have at ATmega2560 clone with CH340 which used to work on my desktop about half a year ago when I tried to get an LCD touch shield to work.
Yesterday I tried to resume on it and I got the ubiquitous timeout error.

So I removed the shield and tried the basic blink sketch but no change.
I tried an arduino nano and there was no problem to upload the blink sketch.
Then I tried different USB cables and ports but the timeout problem with the ATmega persisted.

So I went to the notebook and the ATmega worked like a charm.
Now I know that the board is ok as well as the cable.
The port is also ok as the nano worked on it smoothly.
I also tried the upload from an elevated command prompt with the verbose option but it gave me no further clue.

The output is below:

```
C:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/bin/avrdude -vvvv -CC:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf -v -patmega2560 -cstk500v2 -PCOM34 -b57600 -D -Uflash:w:T:\TMP\arduino_build_330193/Blink.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0 -arduino14/etc/avrdude.conf"

         Using Port                    : COM34
         Using Programmer              : stk500v2
         Overriding Baud Rate          : 57600
STK500V2: stk500v2_open()
STK500V2: stk500v2_getsync()
STK500V2: stk500v2_send(0x1b 0x01 0x00 0x01 0x0e 0x01 0x14 , 7)
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
STK500V2: stk500v2_recv(): avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout

```

Does anybody have an idea how to further tackle the problem?

# Answer
I found the problem coming from a mismatch of the port speed setting and the baudrate in the avrdude command. It seems that the ATmega is very sensitive to timing issues. After I did set everything to 115200 it works on my w7 box like on the notebook.
> 1 votes

---
Tags: avrdude, atmega2560, ch340
---


title: Help with placing a function please

text:
# Question
Title: Help with placing a function please
I am trying to call a function that will turn a stepper motor a number of steps depending on the value submitted through the serial console. For an example, if I submit 50, the motor should turn 50 steps clockwise (and counter clockwise for a negative value).

```
#include <Stepper.h>
#define STEPS 200
Stepper stepper(STEPS, 8, 9, 10, 11);

int serial_input = Serial.read();

void setup() {
Serial.begin(9600) ;
stepper.setSpeed(30);
}

void loop() {
}

void turnMotor(serial_input){
  stepper.step ( serial_input ) ;
}

```

And here are the errors I get:

```
Motor4.ino:12:28: error: variable or field ‘turnMotor’ declared void
Motor4.ino:12:16: error: ‘serial_input’ was not declared in this scope
Motor4.ino:117:28: error: variable or field ‘turnMotor’ declared void

```

Thank you

# Answer
> 0 votes
As Juraj already explained, you cannot use Serial.read() outside a function.

What you probably want is to call it within the loop, or a function called from loop (via other functions). Than you can call also turnMotor from Loop or a function called from loop. The value (int serial\_input) probably doesn't have to be global anymore, but that depends on the time where you assign the value and where you call turnMotor.

---
Tags: stepper-motor
---


title: What's going wrong with my EEPROM?

text:
# Question
Title: What's going wrong with my EEPROM?
I've been chipping away at a project for a long time now and I've found a serious bug.

Basically the user has an 8x8 grid, and each cell in this grid has a number of properties. I want to be able to save all of these properties as a 'profile' within the EEPROM, and previously this worked OK but now seems to have a few bugs.

The most prominent of which is that when I save a grid to a profile (Say profile 3), and then load the next profile (profile 4, in this case) the far right column of profile 3 appears in the far left column of profile 4. LikeWise, saving a filled in grid to profile 1, and then saving an empty grid to profile 2 causes the RIGHT hand column of profile 1 to be cleared.

It used to work great in a previous version but there was completely different hardware in place supporting the GUI making it impossible to load older versions of the code and test how it was working then.

Here is the code where I save / load profiles

```

#include <EEPROM.h>
#include"EEPROMAnything.h"
const int profileSize = 224; // Actually everything is only half the size you thought (WTF but ok)

void saveProfile(int profileNum)                               // saves the complete current configuration of the system to memory under a profile for later restoration
{
  tft.fillScreen(BGCOL);// Clear the screen.
  tft.setTextSize(2);
  setLine0();
  tft.print("Saving...");
  setLine1();
  tft.print(sizeof(saveConfiguration)/8); // Original
  tft.print(" Bytes");
  setLine2();
  tft.print("please wait");
//  tft.sendBuffer();

  for (int ROMRow = 0; ROMRow< 8; ROMRow++)    // Populate the ROM Structure
  {
    for (int ROMCol = 0; ROMCol < 8; ROMCol++)
    {
      saveConfiguration.ROMcellType[ROMRow][ROMCol]      = cellType[ROMRow][ROMCol];
      saveConfiguration.ROMindexVal[ROMRow][ROMCol]      = indexVal[ROMRow][ROMCol];
      saveConfiguration.ROMMIDIVariable[ROMRow][ROMCol]  = MIDIVariable[ROMRow][ROMCol];
      saveConfiguration.ROMcellChannel[ROMRow][ROMCol]   = cellChannel[ROMRow][ROMCol];
      saveConfiguration.ROMorientation[ROMRow][ROMCol]   = orientation[ROMRow][ROMCol];
      saveConfiguration.ROMfaderGroundX[ROMRow][ROMCol]  = faderGroundX[ROMRow][ROMCol];
      saveConfiguration.ROMfaderGroundY[ROMRow][ROMCol]  = faderGroundY[ROMRow][ROMCol];
    }
  }

  EEPROM_writeAnything((profileNum*profileSize), saveConfiguration);

  delay(500);
  menuState = 1; // Go back to main menu
  menuLocatorY = 0; // Otherwise text will not show on next screen;
  updateScreen();
}
//{EEPROM_writeAnything(profileNum*profileSize, configuration);}

void loadProfile(int profileNum)                              // saves the complete current configuration of the system to memory under a profile for later restoration
{
  tft.fillScreen(BGCOL);// Clear the screen.
  tft.setTextSize(2);
  setLine0();
  tft.print("Loading...");
  setLine1();
  tft.print(sizeof(saveConfiguration)/8);
  tft.print(" Bytes.");
  setLine2();
  tft.print("please wait");

  initGrid(); // Clear any information regarding the current grid. Shouldn't really be neccesary but makes code safer.

  EEPROM_readAnything(profileNum*profileSize,saveConfiguration);
  for (int ROMRow = 0; ROMRow< 8; ROMRow++)    // Populate the ROM Structure
  {
    for (int ROMCol = 0; ROMCol < 8; ROMCol++)
    {
      cellType[ROMRow][ROMCol]      = saveConfiguration.ROMcellType[ROMRow][ROMCol];
      indexVal[ROMRow][ROMCol]      = saveConfiguration.ROMindexVal[ROMRow][ROMCol];
      MIDIVariable[ROMRow][ROMCol]  = saveConfiguration.ROMMIDIVariable[ROMRow][ROMCol];
      cellChannel[ROMRow][ROMCol]   = saveConfiguration.ROMcellChannel[ROMRow][ROMCol];
      orientation[ROMRow][ROMCol]   = saveConfiguration.ROMorientation[ROMRow][ROMCol];
      faderGroundX[ROMRow][ROMCol]  = saveConfiguration.ROMfaderGroundX[ROMRow][ROMCol];
      faderGroundY[ROMRow][ROMCol]  = saveConfiguration.ROMfaderGroundY[ROMRow][ROMCol];

      /*
      if (cellType[ROMRow][ROMCol] == 3)
      {
        customValue = orientation[ROMRow][ROMCol];
        customMessage =   indexVal[ROMRow][ROMCol];
        MIDIVariable[ROMRow][ROMCol] = 0;   // Sets read fader value to 0 initially,   the customvalue variable is used to control physical orientation in this function
        customChannel = cellChannel[ROMRow][ROMCol];    // The MIDI channel the given cell is assigned to
        initType3(ROMRow,ROMCol);
      }
      */

    }
  }

    // Here we go back to the grid view
    delay(500); // Just so user can see message
    menuState = 2; // Go back to Grid View
    menuLocatorX = 0;
    menuLocatorY = 0; // Otherwise text will not show on next screen;
    updateScreen();
}
//{EEPROM_readAnything((profileNum*profileSize), configuration);}

```

Here is the declaration of the struct I am using

```
//-------------------------------EEPROM STRUCTURE -------------------------------------------
struct config_t   // I think this will allow EEPROM saving made easy
{
  int ROMcellType[8][8];  // [Row][Column] States the type of input assigned to the cell.  Top left = 0,0 Row, Column    // Celltype 9 will be a reservation cell for the faders.
  int ROMindexVal[8][8];       // States the note value / Command  assigned to the cell
  int ROMMIDIVariable[8][8];   // Used to retain desired velocity / Current value of continuous input.
  int ROMcellChannel[8][8];    // The MIDI channel the given cell is assigned to
  int ROMorientation[8][8]; // Keeps track of the direction of orientation of large modules
  int ROMfaderGroundX[8][8]; // Keeps track of where the 'root' of the fader is
  int ROMfaderGroundY[8][8]; // Keeps track of where the 'root' of the fader is
} saveConfiguration;
//--------------------------------------------------------------------------------------------

```

IndexVal, cellType, etc are all global variables (I know, I know, global variable bad)

And last of all, the header file with my base level EEPROM functions

```
#include <EEPROM.h>
#include <Arduino.h>  // for type definitions

template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
    const byte* p = (const byte*)(const void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          EEPROM.write(ee++, *p++);
    return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value)
{
    byte* p = (byte*)(void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          *p++ = EEPROM.read(ee++);
    return i;
}

```

It's been a while since I wrote this code so I'm a little lost in it myself. I should probably add that if I save to profile 1, mess around testing the other profiles, then load profile 1 again it's always correct.

Also, the part where it prints sizeof(saveConfiguration) does return 224, and I've also removed the "/8" just to check that there was no rounding error. If I double the value of profileSize it simple halves the number of profiles I have available by spacing them out by the size of the struct in memory.

Please ignore the (if cellType == 3) section, this is used for a type of object that uses 3 consecutive cells and is a whole can of worms in itself. For the sake of this test I'm just using celltypes that are modules that use a single cell.

I feel like I really need to make some progress with this soon for the sake of my own mental wellbeing.

Anyone able to help?

Further info for the commenters: The board I am using is a PJRC teensy 3.5.

The /8 was to display the number of Integers being saved. I think when I originally wrote this code I mistakenly thought that the device was 8 bit, and estimated the profile size to be 448. I believe the EEPROM is 16 bits wide?

# Answer
> 1 votes
Depending if you are on an 8 bit or 32 bit Arduino your profile is either 896 or 1792 bytes in size. *Not* 224. (Why do you think /8 is an option?)

I am guessing that you are on a 32-bit Arduino since 1792/8 = 224.

1792 is more EEPROM than any normal Arduino has, anyway. Even if you were on an 8-bit Arduino and the profile size was 896 there would only be room for one in the EEPROM.

I think you need to re-think your strategy somewhat to either massively reduce the amount of data you are saving, or change where you are storing the data to.

---
Tags: c++, c, eeprom, teensy
---


# Question
Title: Arduino Analog pins go all to high problem
I was taking measures from the outputs of an OpAmp when all the sudden measure 5 volts from all pins of the Arduino Mega for no reason. I disconnected the Arduino and loaded the Firmata and test. All the pins are reading high to 1023.. 5 volts are been output for no reason even when I have the Analog Ping to input.

Sketches code are loading and the lights look normal. I did noticed the processor chip getting hot and the voltage in the breadboard line to the Arduino Analog pins reading 7 volts.

Is this a sign of a serious damaged to my device?

# Answer
> 2 votes
A high voltage at a pin can damage the microcontroller partially.

The ATtiny microcontrollers can sometimes survive a voltage of 7 V.
The ATmega microcontrollers are damaged by that voltage.
The ATmega2560 is older and even more critical with voltages, it can not work at 16 MHz below 4.5 V and gets easily damaged with voltages above 6 V.

When the microcontroller runs at 5.0 V, a input pin can have -0.5 V to +5.5 V.

When the microcontroller gets damaged, it can be damaged partially. It is impossible to determine which parts of the chip are still okay. Therefor a partially damaged microcontroller should not be used anymore.

**Solution:**

A simple solution is a protection resistor in the signal path to the analog input.

simulate this circuit – Schematic created using CircuitLab

According to application note AVR182, it is allowed to push 1 mA into a pin or pull 1 mA from a pin for the ATmega microcontrollers. That current flows via the internal ESD diodes to VCC or from GND.

With a protection resistor of 4k7 before an input, the microcontroller is protected up to: 1mA * 4k7 + 5.5V = 10.2 V.

The internal ESD diodes can have more than 1 mA, but the maximum is unspecified. It is also dangerous when for example the ATmega is put into sleep mode. Then the 1 mA can lift the VCC voltage and still damage the ATmega microcontroller.

When a voltage divider is used (two resistors, R1 and R2) and the internal reference is used, then the voltage divider can be designed to be protected against very high voltages. For example with a ATmega2560, internal reference of 2.56V, R1=47k, R2=10k. This can measure up to 14.6 V and be protected up to 78 V.

---
Tags: voltage-level, safety
---


# Question
Title: How to properly run four DC motors with an Arduino?
I am working on a project where I have four DC motors that are controlled by two L293D motor drivers. Two of the motors act as the wheels of the robot, and the other two act as a mop.

The Arduino board is powered through the USB port. The DC motors are powered by the L293D motor driver through the 5 V pin on the Arduino. Alongside the motors, an ultrasonic sensor and a water sensor are also using the 5 V pin.

This is what the robot should be doing:
The robot will move forward. If it senses an obstacle through the ultrasonic sensor, it will turn right. If it senses water through the water sensor, the robot will stop moving and the mop will start spinning. After cleaning the water spillage, it will move forward again, just like what it did before.

It seems like the motors are not getting enough power, because whenever I place it on the floor, it doesn't move.

The base / platform of the robot is plywood, which is heavy for the robot, and I think this is a factor that affects the spinning of the wheels.

I also have a 9 V battery, which I think could power the motors, but I don't know how to connect it. How am I supposed to connect it to the L293D motor driver? I think I should connect the positive side of the 9 V battery to the VCC 2 pin of the L293D motor driver. But, where should I connect the negative side of the 9 V battery?

# Answer
With out knowing the demands of the motors (how much current they need under a given load) it is difficult to answer your question. But, in most Arduino designs:

1. Motors are powered independently of the Arduino. And when Arduino Uno is powered through its USB port it should be realized that most common USB power sources are only obliged to offer up to 500mA of current.
2. The motor's power source likely needs to be capable of providing several Amps. A common 9 Volt battery only contains about 500mAh and will likely drain in 10s of minutes if it works at all.

Consider the power pack used in common portable electric power tools. This should give you a perspective of the type of power you will need in order to create a robot with multiple motors.
> 1 votes

---
Tags: arduino-uno, power, motor, robotics, l293d
---