text:
Error : stray '\' in program
I got this error in the following program:
#include <SoftwareSerial.h>
#include <dht.h>
dht DHT;
int a;
String temp;
String humid;
SoftwareSerial esp(0, 1);
#define SSID "abcd"
#define PASS "99999999"

void sendAT(String cmd) {
  Serial.print("SEND=");
  esp.println("cmd");
  Serial.println("cmd");
}

boolean connectwifi() {
  Serial.println("AT+CWMODE=1");
  delay(2000);
  Serial.println("AT+CWLAP");
  String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";
  sendAT(cmd);
  delay(5000);
  if (Serial.find("ERROR")){
    Serial.println("Recieved:Error could not connect");
    return false;
  }
  else{
    Serial.println("Wifi connected \n");

  }
  cmd="AT+CIPMUX=0";
  sendAT(cmd);
  if(Serial.find("Error")){
    esp.print("RECIEVED ERROR");
    return false;
  }
}

  void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  esp.begin(115200);
  send("AT");
  delay(5000);
  if(Serial.find("OK")){
    Serial.println("Recieved:OK\n ESP ready to send data\n");
    connectwifi();

  }

}

  void loop() {
  // put your main code here, to run repeatedly:
  a=DHT.read11(5);
  temp=DHT.temperature;
  humid=DHT.humidity;
  Serial.println("temperature: ");
  Serial.println(temp);
  Serial.println("humidity: ");
  Serial.println(humid);
  Serial.print("\n");
  updateTS(temp,humid);
  delay(3000);

}

void updateTS(String T, String H){
  String cmd="AT+CIPSTATRT=\"TCP\",\"api.thingspeak.com\",80";
  sendAt(cmd);
  delay (2000);
  if (Serial.find("Error")){
    Serial.print("Recieved :Error\n EXIT1");
    return;
  }
  cmd="GET/update?key=CJWN3VJZCQVTJD2J&field1="+T+"&field2+"+H+"\r\n";
  Serial.println("AT+CIPSEND=");
  Serial.println(cmd length());
  if (Serial.find(">")){
    esp.print(">");
    esp.print(cmd);
    Serial.println(cmd);
    }
    else{
      sendAT("AT+CIPCLOSE");
    }
    if (Serial.find("Error")){
      Serial.println("Recieved: Error \n EXIT2");
    }
    Serial.println();
}
    }
}

The error message displayed is:
arduinoo_sketch:21: error: stray '\' in program

   String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

   ^

arduinoo_sketch:21: error: stray '\' in program

arduinoo_sketch:21: error: stray '\' in program

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:21:47: warning: missing terminating " character

   String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

                                               ^

arduinoo_sketch:21: error: missing terminating " character

   String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

   ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'boolean connectwifi()':

arduinoo_sketch:22: error: expected ',' or ';' before 'sendAT'

   sendAT(cmd);

   ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:24:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if (Serial.find("ERROR")){

                          ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:34:25: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if(Serial.find("Error")){

                         ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void setup()':

arduinoo_sketch:44: error: 'send' was not declared in this scope

   send("AT");

            ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:46:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if(Serial.find("OK")){

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void loop()':

arduinoo_sketch:64: error: 'updateTS' was not declared in this scope

   updateTS(temp,humid);

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void updateTS(String, String)':

arduinoo_sketch:75: error: 'sendAt' was not declared in this scope

   sendAt(cmd);

             ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:77:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if (Serial.find("Error")){

                          ^

arduinoo_sketch:83: error: expected ')' before 'length'

   Serial.println(cmd length());

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:84:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if (Serial.find(">")){

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:92:28: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     if (Serial.find("Error")){

                            ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: At global scope:

arduinoo_sketch:97: error: expected declaration before '}' token

     }

     ^

exit status 1
stray '\' in

Syntax highlighting should have given you a hint.

Offhand, I spotted that where it says String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";
it should say String cmd="AT+CWJAP="\"abcd"\",\"99999999\"; - before I saw the error messages - the compiler caught it - so just chase down each line indicated in the error messages.

By properly formatting your code (ctrl-T in the IDE), you realize what is wrong with your code... In
  String cmd = "AT+CWJAP="\"abcd"\",\"99999999"\";
               sendAT(cmd);

See how sendAT(cmd); is indented as if it was part of the previous line? It means you have some trouble with the quotes.

At least one example is here:
String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

You probably meant
String cmd="AT+CWJAP=\"abcd\",\"99999999\"";

This is a pretty trivial issue, you should be able to fix it simply by proofreading your sketch carefully.


text:
Using TXD1/RXD1 on ATmega1280 for USB communication
I have a few MakerBot Mightyboards running off ATmega1280 chips that can no longer use their standard USB port to connect to a computer (to make a long story short, there's a little inductor that blew up between the USB port and the 8u2 chip and it is essentially impossible to replace). I have noticed, however, that they have headers for the RXD1 (PD2) and TXD1 (PD3) pins on the 1280 as seen in this picture:

Would it be possible to hook up an external 8u2 (or similar) chip programmed as a USB to serial converter (something like this) and use it as if it were the normal USB port (e.g. for uploading firmware)?
(I wanted to add atmega1280 as a tag, but it doesn't seem to exist)

How on earth did you manage to blow up a resistor?!?!?!

Just noticed I actually got mixed up and the parts I'm talking about are inductors. They're tiny surface-mounted ones, and they're placed right next to the USB port. The boards are quite old (about 5 years) so I'm guessing a slight power surge over USB caused them to literally blow up (there's burn marks on the boards that have this).

Not directly, no.
The USB interface connects to TX0 and RX0 - you have access to TX1 and RX1. The bootloader is set to look at TX0 and RX0.
You would have to compile and install a new version of the bootloader that is set to use TX1 and RX1.

Thanks! I highly doubted it would work out-of-the-box like that. Do you happen to know what changes I would have to make to the bootloader for this to work (and where I could get said bootloader)?

No idea, I have never compiled the bootloader. I think there's something included with the IDE somewhere. Or Google optiboot as an option.

Alright, I'll try that out. It might take a while though since I'm waiting on parts. I'll make sure to post any new info I might have.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
analogRead() inside a loop always returns 0
I wrote Arduino code to receive analog input from different voltage dividers connected to four pins (A0 to A4) and analog input from a temperature sensor (LM35) to A5. analogRead inside the for loop always returns zero whereas analogRead outside the for loop returns correct values.
What has to be changed to get correct values?
int time=0,y=0;
float volt;
String str;
int countParallel=0;
float voltage[]={0,0,0,0};
float temperature=0;
int sensors_pin[]={A1,A2,A3,A4,A5};
String x="";

// the setup rouontine runs once when you press reset;
void setup() {
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(50);
}

// the loop routine runs over and over again forever;
void loop() {
  Serial.println(analogRead(A5)*500/1023);
  delay(1000);
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
      x += (char)inChar;
    }
  }
  // Parallel Disharging
  //  Serial.println(x);
  if(x.toInt()==1) {
    digitalWrite(13,HIGH);
    if(countParallel<1) {
      digitalWrite(6, HIGH);
      digitalWrite(7, HIGH);
      countParallel++;
    }
   for(int i=1,x=14;i<=5;i++,x++) {
    if(i<4) {
      Serial.println(analogRead(x)*(5/1023));
      delay(100);
    } else if(i==5) {
      Serial.println(analogRead(x) * p(500/1023));
      delay(100);
    }
    if(volt<2.8){
     digitalWrite(i+1,HIGH);
   } else if(temperature>40) {
     digitalWrite(2,HIGH);
     digitalWrite(3,HIGH);
     digitalWrite(4,HIGH);
     digitalWrite(5,HIGH);
    }
  }
}

// Series Discharge
if(x.toInt()==2){
    for(int i=A0;i<=A4;i++){
      if(i<A4) {
        voltage[i] = analogRead(sensors_pin[i]) * (5/1023);
        Serial.println(10);
        delay(100);
      } else if(i==A4) {
        temperature = analogRead(sensors_pin[i])*(500/1023);
        Serial.println(9);
        delay(100);
      }
      if(volt<2.8) {
        digitalWrite(i, HIGH);
        delay(100);
      } else if(temperature>40) {
        digitalWrite(2,HIGH);
        digitalWrite(3,HIGH);
        digitalWrite(4,HIGH);
        digitalWrite(5,HIGH);
      }
     }
  }
}

voltage[i]=analogRead(sensors_pin[i])*(5/1023)

Is equivalent to
voltage[i]= analogRead(sensors_pin[i])*0
          = 0;

You are using an integer division, not a floating point divsion. 5 / 1023 evaluates to 0, 5.0f / 1023 evalues to 0.00488... You have repeated this error throughout your lower loop code, which is why you're only getting 0.
In your outer loop you printed it as
Serial.println(analogRead(A5)*500/1023);

Which will first multiply by 500, then divide by 1023, which works. But since you put the above expression in parenthesis, it was first evaluated.

As a side note, it's 1024 rather than 1023.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Run two stepper at same time
I am trying to run two stepper motor at same time with different RPM.
I decided to use two rotary encoder for change the RPM separately.
But,
I am in problem with driving stepper at same time due to the delay time of the step pulse.
How can I generate separate(different duty cycle) step pulses for stepper motors? It's the main problem that I faced.
I have used some Arduino libraries and all of that library has same system for step pulse generation. But, I couldn't understand those well.
void AH_EasyDriver::setSpeedRPM(long RPM)
{
   float DIV = RPM*this->MOTOR_RESOLUTION;
    this->STEP_DELAY =  60000000.0L/DIV;
 }

This function calculate the step time for given specific RPM
void AH_EasyDriver::move(int NUMBER_OF_STEPS)
{
   while(STEPS > 0) {
    if (micros() - this->LAST_STEP_TIME >= this->STEP_DELAY) {
      this->LAST_STEP_TIME = micros();
      STEPS--;
      stepMotor();
}
}

}

This function rotate the motor the motor in STEP_DELAY using stepMotor() function.
void AH_EasyDriver::stepMotor()
{
  digitalWrite(this->STEP_pin, HIGH);
  delayMicroseconds(100);
  digitalWrite(this->STEP_pin, LOW);
  delayMicroseconds(100);
}

This function makes CONSTANT step pulses.
I removed some lines in the function. This is the link for original .cpp file.
All of stepper controlling libraries has this functions.
I couldn't understand how this functions can change the RPM. Can someone explain this?

This is a complex task; if you want to see an example of multi-motor coordinated movement, look at an open-source Arduino based 3d printer or light duty CNC machine firmware.

When using a normal stepper driver, you say the driver to do one step, by sending him one pulse. The length of these pulses does not have a meaning. they are constructed, so that the driver can sense them. The driver does not make smaller steps than 1 full step, if you don't tell him on extra pins (The library you use can utilize those pins too). So the stepMotor() function is correct. You can drive the motors with different speeds by doing a step for each motor in different intervals (different number of steps per time).
Your move() function blocks the execution of other code, until the motion is completed. You are doing this with the while( STEPS > 0 ) loop. You need to modify your code to be non-blocking. This is normally done in the way, that is shown by the BlinkWithoutDelay example of the Arduino IDE. You are using it too: You have to use the millis() or micros() function, to check if it is time to do a step.
Replace the while with an ´if´-statement:
if( STEPS > 0 )

and make the STEPS variable a member variable of the class instance. Then make sure you execute the function often enough, so that it will not miss the time to do a step. Do the same with the second motor. For example something that looks like this:
void setup(){
  ...
  stepper1.doSteps(100);
  stepper2.doSteps(200);
}

void loop(){
  stepper1.move();
  stepper2.move();
}

Here in the setup function the steppers are told to move 100 and 200 steps. (You would have to write the function doSteps(int number_of_steps) yourself). The motion is then done by the move() functions, when it is time to do so. Since these two functions are looped very fast, they shouldn't miss the time for a step.
This is also the way the AccelStepper library works, which is also a common stepper library.

While the width of a step pulse might not matter within limits, the time between pulses is extremely important, and not trivial to achieve for multiple motors.  You don't seem to be explaining a viable mechanism for accomplishing that.

I'm not sure how you mean this. In my understanding the driver goes one step, when it counts one pulse. You do pulses in a slow or faster series, depending on how fast the stepper should run. Surely it this not a method for high speed/high precision, but a way you can go, if the circumstances aren't too tough. Maybe I have misunderstood something how the driver works. Please correct me. I can then edit or remove my answer if it is wrong

In the real world it is often necessary to make coordinated moves between two motors, for example imagine a circle in X and Y axis.

For doing such a motion you would have to modulate the speed of the motors (essentially making the time between the pulses depending on a function). But the OP used it in a more simple way. I think the more complex functionality of drawing circles or anything else is out of the scope of this question.

Though it can also be done with my method by varying the speed of the motors during the motion. But the used function of this library are not good for this, I think

The method to produce simultaneous pulses is simple, but requires a different approach similar to Direct Digital Synthesis (DDS).

Keep one counter variable per motor
Increment each counter variable by a set amount in a fixed time loop
When a counter variable reaches a threshold value, generate a very short step pulse
When a threshold is met, subtract the threshold value from the corresponding counter

The amount that each counter variable is incremented sets the generated pulse rate, reaching the threshold faster or slower, therefore setting the motor speed. A value of 0 stops the motor, a value equal to the threshold generates a step pulse for each iteration of the loop, reaching the highest speed. An arbitrary number of motors may be controlled simultaneously as long as the code can run within the fixed loop time. Since a step can only occur at fixed intervals, the rate of the timed loop should be several times the fastest step rate you intend to use to minimize timing jitter.
This style of control is often implemented using a timed interrupt service routine (ISR) which is a short function set to repeat at a several kHz frequency, interleaving with the rest of the program. This allows a slower loop to run a control algorithm simultaneous to the step generation.
If not using a timed interrupt function, the step generation loop must busy-wait until a set time has elapsed before repeating again. This means you cannot do much else than drive the motors until you stop and break out of the loop.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Problem in bootloading 328p using Arduino as ISP. Please help me in figuring out the problem.I have uploaded the verbose below
Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM8
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Error while burning bootloader.

I had the same problem yesterday. So look at the help offered to me and the solution.

it is wrong wiring

@Decapod So that's it? I have re checked the wiring numerous times.

Could you post a picture of your wiring?

@PeDro. It must be a wrong wiring or a bad contact in the wiring. Follow the arduino procedure carefully and verify the wiring again

there is great community called avrfreaks.net great with anything with AVR.
There is thread going with exactly same issue. follow it.
one quick thing try different 328p chip if it works mostly this one is bricked.
still want o experiment try changing crystal, fuse-bit , ISP , external clock generator.


text:
Timer for Control Motor using Limit Switch
Im not good in arduino, but I have project that control motor using limit switch.
The rule is:

When switch OFF, motor ON
When switch ON, motor OFF for 1 hour (i dont want use delay because cannot multitasking so it will be stopped another program which have to running in the same time)
After 1 hour, motor ON (although switch state still ON)

What type of timer I have to use? And how the code? Thanks. Sorry if i dont have any codes.

You can do a 1 hour delay with millis() (though it's not 100% accurate). If the time now, minus the time when the switch got pressed, is more than one hour then turn on the motor.

There is no need to do a complex thing like using extra timers for this. You can use non-blocking code with the millis() function, like in the BlinkWithoutDelay example of the Arduino IDE (You should really try it and understand how it works). The millis() function returns the number of milliseconds since the Arduino has powered up and it will overflow after about 50 days (and with the code from the mentioned example this wouldn't be a problem either).
Basically you save a timestamp of the last event and check, if it is time to do something. For your case I would add a boolean, indicating, that the motor should be off and that the state of the switch doesn't matter anymore. Then (I assume that you want to disable the motor again by switching to OFF and ON again) you would have to reset this variable, when the switch goes to OFF state again. Something like this:
boolean state=true; // on by default
unsigned long timestamp=0;

void loop(){
  if(switch_on() && state){
    state=false;
    // switch off the motor here
    timestamp = millis();
  }
  if(switch_off()){
    state=true;
  }
  if(!state && millis()-timestamp > INTERVAL){
    //switch on the motor here
  }
}

Be sure to have a good code for checking the switch state, since most mechanical buttons need debounce code. In the above code I replaced this with simple functions to illustrate the timing functionality.

you only need to debounce the switch OFF, when the motor starts up


text:
Working with long strings
So I need some tips on working with long strings with the arduino. I have a barcode scanner working. This barcode scanner reads a persons driver license. the result is a lengthy character string of varying length that's 300+. Using substring doesn't work when looking for a certain section of the string and indexOf results in a -1 in most spots. Is there anyway getting around this? Right now I have the data just stored in a string variable.
Thanks.

Don't use String. It's slow, inefficient, and makes swiss cheese of your memory. Use the standard C string.h library routines (already included and available in your sketch).

This doesn't really sound like a task to which an Arduino is well suited.  You can probably make it work, but it's likely not the best choice.

Since the Arduino Uno only has a few KB, 300 bytes is a considerable amount.
My advice:

Define a fixed char[300] array, where 300 is the max amount of characters you want to support.
Use the C (string.h) library as Majenko already suggests.

The last thing you want is that the string will be copied somehow, using up double the amount of data, or triple. It's hard to see what's going on under water, by casting or even by implicit casting a copy can be made, so 600/900 bytes are used.
For the default library, searching should work for strings longer than 256 characters. You can even write them yourself, for example if you can make it more efficient if you know something about the characters (e.g. if you can skip some because you know some patterns exist or don't exist).
Update after your comment below.
What you can try:

Try (if existing) an example sample for the barcode scanner to see if the hardware is ok. If not possible try to make a minimal sketch.
Double check the wiring (although it seems easy).
Try different wires (maybe a jumper wire is malfunctioning).
Try another sketch using serial, but without the barcode scanner (to verify RX/TX is not broken on the Arduino).

Searching substrings, with strstr() or strcasestr() works, of course, with strings of any length. And note that, if the program is light enough, it would make sense to allocate 1 KiB to the string.

@EdgarBonet True ... I rephrased my answer slightly, thanks!

The barcode scanner is the heaviest part of this build. I have a few I2C devices, and maybe 5 digital outputs at most. The physical aspect with outputs is really light.

I updated my answer.

In response to your answer, I'm pretty sure the hardware is fine. I WISH it was serial but all I was given to work with is a USB scanner and USB shield. When scanned in and stored in the string variable, I can Serial.print the data just fine. My issue only comes when searching the string. For drivers license, there are delimiters like "dbb" to indicate date of birth. I'm essentially trying to search for the occurrence of this delimiter and extract the date of birth, turn it to a julian date, compare with an RTC module, and make sure the person is over 21.

Can you put in your question the exact code you use for searching? (including a Serial.print of the values before and after your search).

I don't have the code with me currently, but I was just using Serial.println(DL.indexOf("dbb")); and I received a -1 for the output. I'm using indexOf to get the index, add 3 to bypass the delimiter, and then I was going to get the next 8 digits for the date. When I am able to, I am going to put it into a character array and use strstr() as suggested. If I do Serial.println(DL); I get the data displayed just fine.

my answer posted

So when printing my string variable, I get the full, uninterrupted string displayed to me. I decided to index through my string with a for loop and come to find out, I had many null characters included in the string itself. I did a check to make sure that the character isn't a NULL character before appending it to my string upon creation, and that seemed to do the trick. indexOf is working now.
Reason I decided to index through my string is because I tried to string.toCharArray(buff, DL.length()); and despite the length, I would only get one character pushed into buff.
Thanks for all the tips guys!

Functions of the “str” family, like strstr(), expect NUL-terminated strings, and thus they can't handle character arrays with embedded NULs. Arbitrary character arrays, however, are handled just fine with functions from the “mem” family, like memmem(), which is the equivalent of strstr() for arbitrary arrays.


text:
Initializing an array within a class
I'm making a game of snake on the adafruit Neopixel shield and have run in to a problem. How do you fill out an array (in this case a 5*8 array) with values once the class has been called.
This is my code so far
H file
#include <Arduino.h>
#include <Adafruit_NeoMatrix.h>
#include <streaming.h>

class Snake : public Adafruit_NeoMatrix
{
    public:
    Snake();
    void drawSnake();

    private:
    int snakeBoard[5][8];
};

CPP file
#include "Snake.h"

Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800)
{
  begin(); // start the matrix
  show();

  int snakeBoard[5][8] = {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}};
}

void Snake::drawSnake()
{
  for(int y = 0; y < 5; y ++)
  {
    for(int x = 0; x < 8; x ++)
    {
      Serial << "X: " << x << " Y: " << y << " Value" << snakeBoard[x][y] << endl;
      delay(100);
    }
  }
  drawPixel(5,5,Color(0,0,255));
  show();
}

When I run the program random garbage is printed in the serial monitor.

When initializing an array you need to use an =

And in your constructor you declare a new array named snakeBoard which is deleted automatically once you leave the constructor. This array covers up the array declared in the class definition

As already mentioned by @chrisl, you are creating a new local variable which overshadows your class member.
An easy way to get what you want is to memcpy your initial values into the array:
Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800)
{
  begin(); // start the matrix
  show();

  int initialSnakeBoard[5][8] {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}};
  memcpy(snakeBoard, initialSnakeBoard, sizeof(initialSnakeBoard));
}

You can achieve the same thing by utilizing C++11 constructor lists to initialize your members (see here):
Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800),
  snakeBoard {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}}
{
  begin(); // start the matrix
  show();
}

You also have an error in your drawSnake routine: You confused the order of the indexes. With snakeBoard[5][8] you declare 2-dimensional integer array with 5 rows containing 8 elements each. Then, snakeBoard[0] will be a pointer to the first row (which has 8 elements). So the first index is y and must only range from 0 to 4 inclusive. The function must be:
void Snake::drawSnake() {
    for(int y = 0; y < 5; y ++)
    {
        for(int x = 0; x < 8; x ++)
        {
            Serial.println("X: " + String(x) + " Y: " + String(y) + " Value " + String(snakeBoard[y][x]));
            delay(100);
        }
    }
}

This then prints all the expected array elements to the the Serial port, as tested on my Arduino Nano.


text:
Serial Monitor appears unreadable characters

Hello
My serial monitor keep showing these unreadable characters. Anyone know what is going on? Many thanks!

maybe the data is binary, not ascii

Can you try a minimal example of Serial.begin(9600); Serial.println("Hello world!");?

@MaximilianGerhardt Hi yes one line of hello world appeared

Then start adding connections, components and code until the error shows up. Does connecting RX to the Arduino change anything?

@MaximilianGerhardt Yes connecting to RX looks normal but after connected ground to ground unreadable codes appear

Since the Serial connection to PC works correctly: Maybe you have changed the communication mode of the headset to 57600 baud like described on this site (though this is a wild guess)

It can have many reasons, but the most likely are:

You set the baudrate wrong
You set the stop/start bits wrong
You send wrong data
The cable is bad

It helps if you show your sketch(es), for sender/receiver and possibly your circuit.

Hi Michel thanks for your suggestions, these are my sketches and circuit: https://imgur.com/a/Ksg4w

It seems the baudrate is correct, start/stop bits is hard to see. Probably the date you send is wrong, you should check what happens in the Brains functions you call and what is returned (which is what you send).

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
When does the pulsein() function start counting?
I have an Arduino Pro mini 3.3V, 8 mHz and I want to use the pulsein() function for a low-going pulse. My question: Does the timer start when the function senses a LOW on the input pin, or when the function senses a high-to-low transition, or either?
Code snippet:
pinMode(3,INPUT); // Signal input to Arduino from pin 2 on LM339  - D3
int pwindow = 6000; // Maximum timeout value for pulsewidth
long pcounterA = 0; // Unfiltered Pulse Width of Channel 1
pcounterA = pulseIn(3,LOW,pwindow);
Serial.print(pcounterA);

Thanks for any help.
JT

Slight nitpick: mHz is millihertz; MHz is megahertz.  That's a difference of 9 orders of magnitude.

According the official Arduino Reference: PulseIn
Fragment:

Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
  HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
  waits for the pin to go LOW and stops timing. Returns the length of
  the pulse in microseconds. Gives up and returns 0 if no pulse starts
  within a specified time out.

Further, from that same page, **Please also note that if the pin is already high when the function is called, it will wait for the pin to go LOW and then HIGH before it starts counting. **


text:
Arduino IDE: How to get PROGMEM const length?
I have defined a byte array as a constant in the Atmel's flash memory:
const uint8_t eye [] PROGMEM = {
  0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
  0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff
};

How can I (repeatedly) read the length of this constant in the program? All the available functions in avr/pgmspace.h do not deliver the proper length, no matter how I use them. I tried strlen(eye), strlen_P(eye), strLen_PF(eye) and also sizeof(eye). I'm new to C, so I'm not sure about the whole pointer stuff.

Have you tried sizeof(eye)/sizeof(eye[0])?

you already know the length ... it is 16 bytes

@jsotola Indeed, but I want to read the array length in a function that gets an array as parameter.

sizeof(), when provided with a pointer to a const (or a pointer to anything else for that matter), which is what you have when you pass it to a function, gives you the size of that pointer. On an 8-bit Arduino that will always be 2.  strlen() only works on strings - null-terminated arrays, which that isn't.

Size 2 is exactly what I got in the function. Isn't there a way to get the size of an array when you just have the pointer address to the array?

No. You can only determine such things at compile time (sizeof is an operator, not a function). Setting a const or creating a #define macro containing the size calculated at compile time (as in C_Elegans' answer) is the way to do it.

Probably the best way would be to define below it
const int eye_len = sizeof(eye)/sizeof(eye[0]);

If the linker does link time optimization, or if you only use it within the same file (and declare it static), it shouldn’t cost any memory, otherwise it will take up two bytes of ram.

That works, although I don't know how. Guess I have to read more about C.

Sizeof(array) gives the size of the entire array in bytes, and sizeof(array[0]) gives the size in bytes of one element in the array. Divide the first by the second and you get the number of items in your array. In this case you could do without the second sizeof, but it makes it still work even if you change the data type in the array.

@needfulthing all of the strlen stuff wouldnt work because this isnt a string (which needs to be null terminated). The sizeof returns the size of the array in bytes, so if you want to know the number of items in the array, you take the size in bytes and divide that by the number of bytes that each item takes up. In this case though, uint8_t is 1 byte, so just sizeof(eye) should also have worked on its own, and it's odd that it didnt originally work for you.

@BeB00 could be that he used sizeof(eye) in another file, and it gave him the size of a pointer

That totally sounds logic. I confused a lot of things by using length functions for strings on a byte array (which counted on because of missing null termination) and receiving the pointer length instead of the array length. That's what you get when making yourself too comfortable in high-level languages... :)

Update: I found another solution for my small arrays and put the size in the first byte of the array, in the example I'd read eye[0] and iterate over the rest. This way the arrays keep their size info with them and I don't have to rely on external variables holding the value :)

Update 2: I combined that with the most simple compression algorithm that holds the number in byte n (being 1...x) and the value in byte n+1, so I get
const uint8_t eye [] PROGMEM = {
0x03,0x10,0xff
};


text:
SSD1306 - Is there a way to scroll a certain number of pixels only?
For a hobby project, I am trying to make some sort of little game with an ATtiny85 and an SSD1306 OLED display, mostly to see how much I can do with the least hardware possible. Something like Captain Rectangle rescues the Circle Princess from the Evil Triangles.
I have been seeing what I can do with an SSD1306 (datasheet), specifically horizontal scrolling. It has a feature to scroll the display horizontally (left or right) at a certain rate, i.e. 1 pixel per given number of frames. This is achieved by issuing three commands:

The first command sets up the scroll.
The second command starts the scroll.
The third command stops the scroll.

While letting the display unit take care of scrolling all by itself sure takes a load off the minimalist MCU, what I really want is to just scroll 1 pixel right away (OK if it takes the display milliseconds to do this). Is there a reliable way to do that?
Some things I have tried:

Draw a column of pixels, setup and start the scroll, stop the scroll right away, delay 10ms, repeat.  The screen does not do much scrolling--I think it only scrolls every x number of attempts, depending on the timing of when the OLED wants to do scrolling vs. when I tell it to stop.
Stop scrolling, draw a column of pixels, setup and start the scroll, delay 10ms. In a preliminary demo, this appears to mostly work, but obviously I will have to read more about the timing of the scrolling to really know, and besides this is a fragile solution--if the OLED scrolls 1 too many or too few pixels, then the MCU program's understanding of what should be on the screen will not line up with that of the display.
I also looked at the "Set Column Address" command, which specifies column start address and end address of the display data RAM, but that has no effect on data already displayed--it does not move visibly on the screen, but only affects subsequent writes--where the address pointer points, and what columns it may point to.

BTW, I am using vertical memory address mode, i.e. I send data one column of pixels at a time, since that is what would have to be drawn when scrolling horizontally 1 pixel.
I see there are more options to try with vertical scrolling, though my screen size (128x64) is not conducive to that.
I could also try re-writing everything on the display every 10ms, but first, did I overlook anything in the datasheet?

If someone with privileges could please add an SSD1306 tag, that would be great.
BTW, I'm using Arduino IDE and a Trinket, but I think that's immaterial.

are you not able to add the tag yourself?

the SSD1306 datasheet that you posted ... search for the word "vertical" in the datasheet


text:
Making profit from Arduino
I have been experimenting with Arduino for a couple of months, and, riding on the back of my 16 years as a high school science teacher (I am now back at university as a student), I can see a few potential improvements for existing science experiments in the high school teaching lab. My question is this: can I make packages based on Arduino and legally sell them to schools for a small profit? Since I’m no longer a teacher, I wouldn’t be using them myself, so I’d have to at least recoup my costs.

There are plenty of kits out there already.  What would make yours unique?  What would you do differently to market it to schools that other vendors aren't already doing?  Those are the questions you have to ask yourself and have the answers to.

The Arduino itself is open, and you can use it to make commercial products.
Note however, that for commercial products, a lot of additional requirements may be needed (regulations, safety, certifications), especially since it will be used in public places among (many) other people. You don't want students to be injured/die because of a badly designed device.
Not that I think you might not capable, but it might be something to keep in mind, that your project is maybe more than just creating some software and adding some packages and sell them.


text:
Problem of fetching data from web page using Arduino Uno and ESP8266
Project goal is to control a relay over web.
I made a php page that receives the post data from Arduino then store the values sent into a mysql database (which is the relay status now).
Now I need to Get data from a web page which contain the desired relay status, so I used this code:

#include <SoftwareSerial.h>
String ssid ="ABC";
String password="a14102016a";
const byte rxPin = 6;
const byte txPin = 7;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200);
  reset();
  connectWifi();
  delay(2000);
}

//reset the esp8266 module

void reset() {

ESP8266.println("AT+RST");

delay(1000);

if(ESP8266.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network
void connectWifi() {

String cmd = "AT+CWJAP=\"" +ssid+"\",\"" +password+ "\"";
ESP8266.println(cmd);

delay(4000);

if(ESP8266.find("OK")) {

Serial.println("Connected!");

}

else {

connectWifi();

Serial.println("Cannot connect to wifi"); }

}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /ard/sensor.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() +4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

But the response from server was
    Module Reset
Connected!

AT+CIPMV⸮=1

OK

AT+CIPSTART=4,#TCP","192.068.1.161",80

4,CONOECT

OK

AZ⸮⸮R5NDOi⸮j

O⸮C⸮⸮
Qecv ⸮&⸮ѕ⸮5

SEND OK

+IPD,4,501:HTTP/1.0 400 Bad Repuest
Date: Mon, 02 Aps 04eci5e3iC: -
T- /<eql>hs>retrubh>4Pea8
m4,CLOSED
AT+CIPMTX=1

OK

AT+CIPSTART=4,"TCP","192.068.1.161",80

4,CONNDCT

OK

AR⸮⸮R5⸮DOi⸮j

O⸮C⸮⸮
Qecv 33 bytes

SEND OK

+IPD,4,501;HTTP/1.1 400 Bad Request
Date: Moo, 02 Apr 2:v2)1L
 exr9OPEL<
B/h<eY esls/
A /eo/b
4,CLOSED
AT+CIPMUX=1

Sometimes I get HTTP/1.0 400 Bad Repuest
and sometimes HTTP/1.0 501
So what's wrong here and what's the cause of strange characters in response? How to retrieve the correct data from web page?

a valid HTTP request needs more the a GET line. you must send some mandatory HTTP headers.

You cannot use SoftwareSerial at such a high baud rate. Try 9600.

The http headers need to end with two newlines. Also use HTTP 1.0 instead, to prevent persistent connections. So try "GET /ard/sensor.html HTTP/1.0\r\n\r\n"

@Juraj GET is the only mandatory request header for HTTP 1.0. In HTTP 1.1 Host is also required.

@Juraj Thanks.. I've changed my request to be String cmd ="GET /ard/sensor.html HTTP/1.1\r\nUser-Agent: curl/7.37.0\r\nHost: %s\r\nAccept: */*\r\n\r\n";     ESP8266.println("AT+CIPSEND=4," + String(cmd.length()));
Still no clear response

I flashed the ESP8266 with another firmware then it worked at baud 9600 perfectly
The original firmware was not responding to the baud 9600 at all


text:
Coding Arduino's samples/period and cycles/sample configurations for input signal
Am I able to code the Arduino so that I can change cycles/sample of an input waveform and a number of samples/period configurations? I would like to modify these parameters in order to be able to store a high-frequency sinusoid but taking into account Arduino's 16MHz clock.
For examples, I have a 40,000kHz sine wave. I would like to sample it at 10 samples/period and having 10 cycles/sample. As a result, I need a (40,000kHz * 10samples/period * 10 cycles/sample = 4MHz clock, which Arduino can supply). Compared to a more standard 128 samples/period and 256 cycles/sample, which would require a 1.3GHz clock.

No, an Arduino cannot do this.

@Chris Stratton  So does it mean you always have a fixed sample/period of 128 and cycles/sample of 256?

It means you can't come anywhere near your goal, so adjustability is beside the point.

The limitation is in the ADC which by default takes 104 µs to make a sample. Now you can speed up the ADC, sacrificing accuracy, but even then you can probably practically only reach a sampling time of 13 µs. Plus you would have the issue of where to put these 400,000 samples in the 2KB of RAM you have.
To sample at 400,000 times a second you would need to sample every 2.5 µs, which you can see is way shorter than 13 µs.
Plus, you not only need space to put these 400,000 samples, but it would take time to store them.
For more information see my page about the ADC which has a lot of details about sampling times, frequencies, accuracy, etc.


text:
How can I handle micros() double rollover?
I know that I can handle a single rollover with subtraction:
if (micros() - lastTime > period) {
  lastTime = micros();
  ...
}

But how it can be handled if this is not true or it is not checked for more than 70 minutes (without using uint64_t)?

What is the objection to using millis() if you are timing rather long periods?

I'm using my implementation of micros() and I don't want to implement millis() because it makes the ISR bigger. Also the precision.

So just to be clear, this is your version of micros you are asking us about? How about posting the code to it?

It's the same as Arduino's version except that in ISR(TIMER0_OVF_vect) there is a single variable increment. The code needs to run with as little interruptions as possible and I want to be able to run something with irregular long intervals.

It's the same as the Arduino version, except it's completely different, is that it? I gather this is top-secret code.

It is the same, and it has nothing to do with the question: `
#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
volatile uint32_t timer0OverflowCount = 0;
ISR(TIMER0_OVF_vect) {
++timer0OverflowCount;
}
uint32_t us() {
uint32_t m;
uint8_t t;
uint8_t oldSREG = SREG;
cli();
m = timer0OverflowCount;
t = TCNT0;
if (((TIFR0 & (1 << TOV0)) && (t < 255))) ++m;
SREG = oldSREG;
return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
} `

What exactly is the problem? Do you want period to be more than 70 minutes?

If you want to measure times longer than 70 minutes with
micros(), you will have to use uint64_t, and there is nothing
wrong with that.

The code needs to run with as little interruptions as possible [...]

You don't need to do the 64-bit arithmetic within the ISR. You could
very well implement an interrupt-driven 32-bit version, and then extend
it to 64 bits in non-interrupt context. Example:
// Your ISR-based implementation.
uint32_t micros32();

// Extend to 64 bits.
uint64_t micros64() {
    static uint64_t time64;
    time64 += micros() - (uint32_t) time64;
    return time64;
}

This should work as long as you call micros64() often enough.
Presumably, you will have something like
if (micros64() - lastTime > period) { ... }
within your loop, so this should be no issue as long as you never block
your loop.
Actually, you can push this idea even further. If you can guarantee that
micros64() will be called at least once every 65.5 ms, then you
could have your ISR increment only a 16-bit counter.

Thank you, this will solve the issue. The last part will be a nice further optimization for my case.


text:
had dice code but lost it during recovery
I had the dice code, but reset and forgot to back the code up, now I need help creating the code again, I can't get the select button to proceed to the loop when pressed here's what I have so far:
#include <LiquidCrystal.h>
// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

//used for later
String line2 = "Press Select to roll"; // Scrolling line

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

// read the buttons
int read_LCD_buttons()
{
 adc_key_in = analogRead(0);      // read the value from the sensor

 // For V1.0 comment the other threshold and use the one below:

 if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result
 // For V1.1 us this threshold
 if (adc_key_in < 50)   return btnRIGHT;
 if (adc_key_in < 195)  return btnUP;
 if (adc_key_in < 380)  return btnDOWN;
 if (adc_key_in < 555)  return btnLEFT;
 if (adc_key_in < 790)  return btnSELECT;

 return btnNONE;  // when all others fail, return this...
}

void setup() {
 randomSeed(analogRead(1));
 lcd.begin(16, 2);              // start the library
 lcd.setCursor(3,0);
 lcd.print ("Catan Dice");
 lcd.setCursor(0,1);
 lcd.print("Press Select to roll");
}

void loop() {
//local varables
int buttonState = read_LCD_buttons(); // read the button pad
int lastButtonState = btnNONE; // previous state of the button

//Dice
int DiceOne = random(1,7);
int DiceTwo = random(1,7);

  if (buttonState != lastButtonState) {
  // if the state has changed, increment the counter
  if (buttonState == HIGH) {
  // if the current state is HIGH then the button went from off to on:

if (btnState == btnSELECT)
  lcd.setCursor (0,4);
  lcd.print(DiceOne);

  }

}
lastButtonState = buttonState;

}

can anyone help me plz

I see you have edited the question and completely changed the sketch. What is the error message this sketch is giving you?

You know that LCD shield buttons are usually multiplexed to the analog pin A0? If I've googled correct schematics, this applies to this one too. Therefore no pin change interrupts nor external interrupts can be used.
Maybe analog comparator module with correct threshold.

can someone help me with my project, the problem is up top


text:
How to declare a Dynamic Array?
I want to define an unknown size for an array. However, I know that this cannot be done on the arduino. So what other methods do you suggest? I tried using vectors by downloading the library ArduinoSTL, but it doesnt work. (It only prints Serial.println(Signal); once, referring to the code in the pastebin link below)
Here's my code with vectors:
#include <ArduinoSTL.h>
#define sensor1 A0

using namespace std;

int Signal;
int Threshold = 550;

vector<int> startTime;
vector<int> endTime;
unsigned long measureTime;

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

void loop()
{
  //Serial.println(analogRead(sensor1));
  int i = 0;
  measureTime = millis();

  while ((millis() - measureTime) < 10000)
  {
    Signal = analogRead(sensor1);
    Serial.println(Signal);
    if (Signal < Threshold)
    {
      startTime.at(i) = millis();
      Serial.println("1");
    }
    if (Signal > Threshold)
    {
      endTime.at(i) = millis();
      Serial.println("2");
    }
    i++;
  }
}

unknown size? the size of the MCU RAM is known and there are no concurrent programs,  so declare a maximum possible array and you are good to go

The vector is empty after its default constructor. And nothing was ever added into it in your code. So you can't use anything like idexing by vect[index] or method vect.at(index). And as there are no exceptions available, who knows what it does after the out of range call.
You should consider ring buffer instead, using dynamic memory is tricky on such constrained platforms. Even using Arduino's String class is often source of memory fragmentation and out of memory type errors.


text:
Delete line from text file
In order to make an algorithm work, I'd like to delete the first line of a text file. I'm having a hard time finding an example for that though. I was thinking that there should be the possibility to delete up to a \n. Could you point me to a solution?
Oh, I'm using a standard Arduino Uno
Thank you

Is it necessary to re-write the file, or is this a file whose later contents will be read and processed by the Arduino? If the latter, then you can just read and throw away a character at a time until you get to '\n' after you open the file.

Well, in this case, the Arduino is connected to Wifi and serves each produced data point as a .csv to a server. I suppose this counts as "processing by Arduino".
So what you suggest would work. I'm not sure though how one would go about to "throw away a character". Is there a search term for that, so I can check it out? Thanks!

To read the file, you would use fopen() to open it and get a file handle. Then you use fgetc() to read one character at a time and check that character to see if it's '\n'. By "throwing away", I mean that the character you read can just be overwritten by the next one you read -- you don't have to build a string or anything or try to save the character for later in the program.

What you can do is:

opening a file (to read)
opening a new file (to write)
since a line can be long (more than arduino's memory), it's best to read it character by character, thus:
use a boolean to denote when to start removing a line (set to e.g. Remove = TRUE)
For every character you read:

If Remove is TRUE, don't write to the output file, otherwise write it
If the character is \n or \r (check how line ends are), set the boolean to False (e.g. continue writing)

Remove file to read
Rename written file


text:
Problem while interfacing LCD screen with Arduino
I tried to interface an LCD screen with my Arduino but I have a problem - Nothing is being displayed on my LCD screen:

Here is the code:
#include<LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);  // sets the interfacing pins

void setup()
{
 lcd.begin(16, 2);  // initializes the 16x2 LCD
}

void loop()
{
  lcd.setCursor(0,0);           //sets the cursor at row 0 column 0
  lcd.print("16x2 LCD MODULE"); // prints 16x2 LCD MODULE
  lcd.setCursor(2,1);           //sets the cursor at row 1 column 2
  lcd.print("HELLO WORLD");     // prints HELLO WORLD
}

Probably your background is not set correctly (there is a way to change the contrast).

Contrast looks good in the photo -- one row of all-on blocks indicates an uninitialized display.

Your photo doesn't clearly show where the wires are going. Can you create a schematic showing the wiring setup, or at least a better photo that clearly shows where each wire from the LCD goes to the Arduino?

@josecanuc the uninitialized screens can be seen even if the contrast is set wrong;

In the setup() you have to state what pin the Vo (display contrast pin) on the LCD is connected to. Before the
lcd.begin(16,2)

try
analogWrite(pin Vo is connected to, contrast you want to set the screen to);

An example would be:
analogWrite(6,80);


text:
Output 20x20 Image to Arduino serial monitor
I am working on an Arduino project where I need to display a black and white (no gray) image to the serial monitor. It doesn't need to be high resolution, so something like 20x20 would work. I will be using this several times a second to make video of a sort, but it doesn't need to be a very high fps (4 or 5 would work). Currently I am just using unicode blocks and printing them (at a baud rate of 500,000) to the serial monitor, but it ends up having a very bad screen tear sort of effect. Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?
Thanks!

I think the serial monitor is clearly not the right output device for this kind of information at that update rate. It is text-line oriented and you have so little control over the "device". Consider one of the many low-res LCD or OLED displays.

Is the "screen tear" a result of not using fixed spacing fonts?  I think you can set the font to be used under File:Preferences, and it not then perhaps in preferences.txt (restart the IDE to see it).

"everything at once", I think you'll be limited to the speed of sending 20 lines across, either as 20 discrete Serial.write's, or in a for:loop.

The Arduino IDE's serial monitor is, to put it bluntly, awful.
Switch to a proper ANSI compatible serial terminal emulator (Tera Term, Putty, Minicom, whatever) and use ANSI control sequences to manipulate the screen.
The simplest ones to use are:
Serial.print("\e[2J"); // Clear the screen
Serial.print("\e[1;1H"); // Move the cursor to coordinate (1,1)

Use the first one to clear the screen in setup(), then use the second one at the start of the loop to move to the top-left corner of the screen (1,1 is top left - the coordinates are given as Y;X not X;Y and start from 1 not 0).
Print your 20 lines of 20 characters as either space (nothing) or your chosen "pixel" character.  The spaces overwrite the existing characters to help reduce flicker (clearing the screen every time would be just awful).
The way serial works (sending one character at a time sequentially) there is no such thing as "All at once". The above is the best you can get without writing your own program to interpret incoming serial data representing an image frame and displaying it.

Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?

No, serial isn't the right technology for that. By its very definition, it transmits data one bit at a time, one byte after the other. What you're after is to transmit the data in parallel. You're already making the closest approximation to parallel you can using serial - transmitting the data at the highest rate you can to minimize the skew. The longer the time between frames and the shorter the time to transmit one frame, the better your result will be. But you may have reached the limit for 5fps with the available serial hardware.


text:
My Arduino keeps telling me the button is being pushed
My code is simple simple for the button.
There is no reason why this shouldn't work... I think. I honestly have no clue what's wrong.
Output:

Code:
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <Bounce2.h>

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

int led = 13;
int led2 = 12;

Bounce debouncer1 = Bounce();

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int buzzer = 10;

Servo LockServo;

int ServoPos = 0;

void setup()
{
  debouncer1.attach(buttonPin);
  debouncer1.interval(5); // interval in ms

  pinMode(buzzer, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP); // Push Button as INPUT wiith pullup
  buttonState = digitalRead(buttonPin);
  LockServo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Approximate your card to the reader...");
  Serial.println();
  pinMode(led, OUTPUT);
}

void loop()
{
  debouncer1.update();
  buttonState = debouncer1.read();
  if (buttonState == HIGH) {
    Serial.println("Button Pushed");
    // turn LED on:
    digitalWrite(led, HIGH);
    ServoPos = 0;
    LockServo.write(ServoPos);
  }
  else {
    digitalWrite(led, LOW);
    ServoPos = 180;
    LockServo.write(ServoPos);
  }

  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "20 96 2E A5") //change here the UID of the card/cards that you want to give access
  {
    Serial.println("Authorized access");
    Serial.println();
    digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
    ServoPos = 0;
    LockServo.write(ServoPos);
    tone(buzzer, 20000);
    delay(500);
    noTone(buzzer);

    tone(buzzer, 15000);
    delay(500);
    noTone(buzzer);
    delay(15);
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);
    ServoPos = 180;
    LockServo.write(ServoPos);
  }
  else {
    Serial.println(" Access denied");
    tone(buzzer, 10000);
    delay(500);
    noTone(buzzer);

    tone(buzzer, 30000);
    delay(500);
    noTone(buzzer);
    digitalWrite(led2, HIGH);
    delay(3000);
    noTone(buzzer);
    digitalWrite(led2, LOW);
  }
}

if (buttonState == HIGH) { means the button is NOT pressed when using pinMode(buttonPin, INPUT_PULLUP);

you are asking about a pushbutton problem, yet your code has a bunch of stuff for servos and MFRC522 .... please reduce the program to the code necessary to demonstrate the issue with the pushbutton

When using a pull-up mode on an input pin, that means that when nothing is connected, the pin floats up to HIGH. The connected button should have one side connected to your input pin, and the other to GND, so that when you press the button, the input pin is pulled to GND (that is, LOW).
So your comparison to trigger on a button press should be if (buttonState == LOW)


text:
Two batteries sharing ground?
I need to power my arduino and 2 DC motors requiring 6V each, I want to power the DC motors with a 6V battery through the vM pin on an h-bridge and use a 9V battery to power the Arduino itself.
On my breadboard I have a dedicated power line and ground line on each side, is it okay to share the ground between both batteries and consequently share grounds for any servo motors or sensors i connect?

What sort of H-bridge?  If it's the dreaded L239D or L298 you probably want more than 6v for the motor supply anyway, 6xAA would likely run your motors and your Arduino.  Anyway, yes, you need a common ground between the battery packs, though preferably the Arduino and the power side of the motor driver have independent wires to the battery packs, and only meet there.

@ChrisStratton It's actually a motor controller my bad, it's this one: Sparkfun TB6612FNG. I just wasn't sure if I could power the DC motors with an external battery and connect ground to common arduino ground.
So you're saying it's okay to use a 9V battery to supply voltage to arduino via its Vin and gnd pins AND use the external battery to power the motors and share ground with the Arduino?

@DenKart that driver requires some additional protection, pay attention to flyback when reversing polarity (changing direction of motor) and stopping the motor. The collapsing EM field can kill your arduino as well. Google for ways to protect your hardware. Do you have an oscilloscope?

The TB6612FNG is much better than the L293.  That might be okay with 6v (4 cells) though you could also consider five or six - you can just run the motor at a lower PWM.

@ChrisStratton Also here's a sketch of my circuit, could you tell me if this is fine? https://ibb.co/iEhKMc I included the specs of the h-bridge too as a note

@user2497 Could you elaborate on more protection? I've been using it just fine to drive my motors forward, backward and stopping.

Your sketch does not show a TB6612FNG, it shows an L293D workalike that shares most of that obsolete design's problems.

@ChrisStratton Couldn't find the motor controller on Fritzing so I put that one and included the pins on the TB6612FNG. I'm just wondering if my circuit is fine with the two batteries?

@DenKart Well, no problem then. The datasheet advises caution. I guess I’ll not need to worry about this then.

Not only can you share the grounds - sharing the grounds is required for there to be any form of meaningful circuit for signals to get around the place.
To copy-and-paste a blog post I wrote some time back:

A lot of the time on the Arduino forums we get questions regarding wiring things together. One common format is:

I want to connect my 12V powered LED strip to my Arduino but I can’t get it to communicate. I have checked all the connections and they seem fine. I have a 12V power supply for the LEDs and the Arduino is powered from the computer.

And 9 times out of 10 the first question we have to ask in return is:

Have you connected the grounds together?

And guess what the reply to that usually is? Yep:

No, do I need to? And isn’t that dangerous, connecting a 12V ground to the 5V Arduino ground?

That in itself shows a fundamental lack of knowledge about what “ground” actually is. So let’s start by clearing that up:
Ground, technically, is just a name given to a point in your circuit. That point is a point chosen by you against which all other voltages in the circuit are measured. Often it is the point of lowest potential, such as the – side of a battery, or the – connection of a power supply. Or it may have been chosen for you, such as the ground signal from the USB connection to your computer.
The 5V pin of the Arduino isn’t actually 5V – it is 5V with respect to the ground pin. Equally, you could rename the 5V pin to Ground, and what was the ground pin then becomes -5V with respect to [the new] ground.
So ground has to be a single point in your circuit against which all voltages “make sense”.
Let’s take a look at the typical circuit from the original question. An Arduino connected to some 12V device (such as some 12V LEDs):

Here you can see the Arduino connected to, for example, a 5V USB charger. It could be a battery, or it could be the USB port on your computer. It doesn't matter. Connected to that is a 12V device which then has its own 12V power supply. Now. Where is ground in that circuit?
The 5V pin of the Arduino is 5V with respect to the ground pin of the Arduino. So seen from the Arduino’s point of view ground is, in the image above, the bottom line of the Arduino’s power circuit (charger -). However, the 12V of the external circuit is 12V with respect to the – side of the 12V PSU. So seen from the point of view of the 12V device the ground is the lower side of the 12V circuit – the “PSU -” connection.
That doesn’t sound too bad, does it? Each device’s power is correct with respect to the power supply it is running off. As far as that goes, sure. However take a look at the data signal going from the Arduino to the 12V device. What voltage is that at?
Well, seen from the Arduino’s point of view, with respect to its ground, since it is generating the signal, it is a 5V signal. But, what about what the 12V device sees? What voltage is that signal with respect to the 12V circuit ground?
Given that voltages aren’t absolute – they are only relative to a reference point within the same circuit, it is impossible to know what the voltage is there.
There’s something more fundamental at play here though which can help you to understand it even better. In the image above there are two red arrows in loops. That is the flow of the current around the circuit (shown as conventional current flow). The key phrase there is around the circuit. Current has to flow out of a supply, through a circuit, and back to the supply from where it came.
In the circuit above the current can flow out of the 5V, through the Arduino, and back to the 5V again because there is a complete loop there. Likewise there is a loop from the 12V supply, through the 12V device, and back to the 12V supply again. But there is no such loop for the signal from the Arduino to the 12V device.  If we think of the Arduino’s output pin as a small power supply there really should be some way for the current to get out of the Arduino, through whatever it is connected to, and then back to the Arduino again. There is no way for that to happen in this circuit.
So you connect the grounds. As soon as you do that a lot of things start to happen. Let’s do that now and see how the circuit looks:

The grounds are now linked by the green wire at the bottom. Immediately we can now see a loop has appeared where the current from the IO pin can flow through the 12V device, out of the ground connection of the device, along the green wire, and back up through the ground connection of the Arduino.
In actuality the loop is a branch from the 5V power loop. Current goes from 5V into the Arduino where it splits, some to run the Arduino and some out of the IO pin. From there it goes through the 12V device, down to ground, then joins the current flowing out of the ground of the Arduino to go back to the 5V supply. It’s useful to think in terms of discrete loops though so you can get a better idea of how the ground fits into things.
Also, now, since the ground of the 5V section and the ground of the 12V section are one and the same (in a schematic all points along a line are the same point) any signals generated from the 5V side are recognisable by the 12V side as 5V since the reference point (ground) is the same for every point in the circuit.
But isn’t it dangerous?
Absolutely not. Not only is it not dangerous, it’s safer than not connecting grounds together. Since now the whole circuit has a single baseline voltage to reference everything from 12V is 12V and 5V is 5V. Without that link the voltage difference between ground on the 5V side and 12V on the 12V side could potentially be many hundreds of volts (especially when the distances between the two points is great). For fully isolated systems, such as battery powered devices, that is not a problem. For anything using power supplies though it can be quite dangerous. And that leads me on to my next point – a slight variation on the question:
I built a circuit with a 12V device powered from a power supply which is controlled by my Arduino. It all works well. But as soon as I run the Arduino from a battery instead of my computer it stops working.
This is a classic case where the grounds haven’t been connected together by the user, but there exists another path linking the grounds together. This is most often the earth connection of the computer and the earth connection of the power supply being linked together through the house wiring:

As you can see the current loop still exists, it just takes a longer route. As soon as you remove the Arduino from your computer and power it from batteries – or a power supply that has no connection to earth – the lower part of that loop disappears completely and you are back to the original circuit with only 2 loops. And it stops working.
Connect the grounds together manually, though, and you reinstate that portion of the loop, making it all work again.
So there you have it. If you have multiple power supplies in your project, whatever they may be (except in special circumstances) you must connect the grounds together for it to work. If it works without connecting the grounds together then you are inadvertently relying on some pre-existing ground connections to do the job for you, and that is likely to fail if your setup ever changes.


text:
Unable to get response for BLE AT commands in Arduino Uno
I am trying to establish connection between two BLE (BT43) through AT commands from an Arduino Uno. I am not getting any response from the AT commands. The connections are as follows:
Arduino Tx --> BLE Rx
Arduino Rx --> BLE Tx
Arduino 3.3v --> BLEVcc
Arduino Gnd --> BLE Gnd
Can someone please help me with this? Thanks in advance!
this is my code
#include <SoftwareSerial.h>
SoftwareSerial BTserial(6, 7); // RX | TX

const long baudRate = 115200;
char c=' ';
boolean NL = true;

void setup()
{
    Serial.begin(9600);
    Serial.print("Sketch:   ");   Serial.println(__FILE__);
    Serial.print("Uploaded: ");   Serial.println(__DATE__);
    Serial.println(" ");

    BTserial.begin(baudRate);
    Serial.print("BTserial started at "); Serial.println(baudRate);
    Serial.println(" ");
}

void loop()
{

    // Read from the Bluetooth module and send to the Arduino Serial Monitor
    if (BTserial.available())
    {
        c = BTserial.read();
        Serial.write(c);
    }

    // Read from the Serial Monitor and send to the Bluetooth module
    if (Serial.available())
    {
        c = Serial.read();
        BTserial.write(c);

        // Echo the user input to the main window. The ">" character indicates the user entered text.
        if (NL) { Serial.print(">");  NL = false; }
        Serial.write(c);
        if (c==10) { NL = true; }
    }

}

Your wiring appears to be correct, what arduino model are you using? What pins are arduino TX/RX exactly? What does your code look like?

I am using arduino uno and i have connected  ble tx--> arduino 6th pin, ble rx pin--> arduino 7th pin

Thanks mystery for your reply. I have added the code to my question. I  have set the baud rate to 115200 and I am not getting response for the AT commands which i enter in serial monitor.

The Uno only has 1 HW UART interface (your Serial object), which is connected to the usb port. You can't connect the bt module to these  and communicate independently. On the Uno, your only alternative is Software Serial as used in your code. Double check if specified pins (6, 7) are NOT the ones of the hardware serial AND are actually connected to the bt module. Also look up the default baud rate of the bt module (115k seems quite high as initial value).

The pins(6,7) are  connected to my ble module only and regarding the baudrate, 115200 is the default baud rate they have given in the document and i also tried different baud rates of

You are missing critical info on page 10 datasheet i.e. not connecting CTS and RTS.
It maybe possible handshake is necessary for communicating to this module.
Give it a try using with some board with Synchronous UART.
Also can try grounding CTS. i.e. connect blue-tooth moduls's CTS to 0V.
read this for more clarity.
Hope this solves your problem.

The  module(BT43) I use doesn't have any routing for CTS and RTS pins and that is why i didnt connect CTS and RTS

I don't have this module but if you are using same as shown in datasheet link above you have 11 RTS and 12 pin CTS follow datasheet for pinout

Since these modules are connected to their respective Arduinos to give them BLE capability, Rx and Tx should be connected to the same, not crossed.

According to 2.6 of https://www.ampedrftech.com/datasheets/BT43_Datasheet.pdf this is not true and the lines should be crossed, as usual.

EDIT
Just found this*:

On Arduino or Genuino 101 the current maximum RX speed is
  57600bps *https://www.arduino.cc/en/Reference/SoftwareSerial

You may be over max speed for Uno.
What are you using to send data via Bluetooth?
Are you sure data is being sent to the device?
Android App
You can try my android app that I created for this specific type of testing.
You can get it at : http://raddev.us/btmessenger.apk
If you point your Android device at that, it will download the app and ask if you want to install it.
In case you're afraid it is malicious you can get the Open Source code to the simple app at GitHub : https://github.com/raddevus/BTMessenger
To use:

pair your bluetooth device
Type a message in top TextEdit box.
Press the [Send] button.

Baud Rate Issues
Generally if you get the baud rate incorrect you'll just see garbage characters.
Here's a write up I just did on setting up Bluetooth devices. It may help you work through some issues.
https://www.codeproject.com/Articles/1254611/Bluetooth-Messenger


text:
Slowly decreasing the speed on a steppermotor over time
I am currently working on an elevator for my examsproject in school.
It's a quite simple simulation of a lifesize elevator.
I'm currently using a steppermotor for the elevatorchair and it's set with a certain speed.
However, in a real elevator, the speed would slowly decrease as it's progressing towards it's destination for a more pleasant ride for the passengers. I'd like to make the same simulation.
I was thinking of using the millis to periodically increase the delays over time, but I don't know whether alternative methods could be used for better results.

Some stepper libraries already support acceleration out of the box. You'd have to check if you can make the acceleration/deceleration slow enough, as the purpose is mostly to prevent missed steps.

millis() sound like a good way to go.
Check the estimated time until arrival (stopping), and in steps (you define yourself) you changen the (PWM) speed of the stepper motor.
Note, also for accelerating you can use the same step schema but reversed.
There are other ways, but I think those will be too complicated, like setting a (hardware) timer for the next speed change. Changing the speed in ms-accuracy will be more than enough.
Do not use delay, since you still want to be responsive for pressed buttons, and (safety) sensors.

Response to your answer that is a comment and will be deleted high likely: Hello Soren, this is not an answer, so you have to put it either as comment, or update your question (the latter is best). I understand the for loop (and I kind of understand, being Dutch). In principle the delay is possible, but it will get you in trouble when wanting to read button states/sensor states (imagine a safety sensor is activated exactly in those 5 ms, you either miss it or have a 5 ms delay). It's better to use millis() over delay, unless you don't have anything else that needs to be responsive.


text:
Control solenoid valve with arduino running on battery
I built a simple setup according to this tutorial using a 9v battery (in the meantime replaced it with a 120A battery):
https://www.bc-robotics.com/tutorials/controlling-a-solenoid-valve-with-arduino/
Also i attached a humiditiy sensor to measure the soil-humidity.
My plan is:
2 times a day (evening and morning before sunrise) wake up arduino and check humidity, if it is below a certain %, open the 12v-valve, wich i operate at 9v (like the one in the tutorial).
I read a lot about how to reduce power on the arduino and found this tutorial for the pro mini, wich seems a LOT easier than to modify the standard arduino uno:
https://www.whizzy.org/2015/06/howto-very-low-power-usage-on-pro-mini-v2-arduino-clone/
Now, my question is:
would a pro mini v2 work as well for controlling the valve? On the uno, i have the vin-pin wich provides the 9v for the valve, on the pro mini instead, as far as i understood, i need to use that pin (named RAW pin there) as power supply for the arduino... but how would i get out the 9v from the arduino like i did on the uno? Is there any possibility at all?
Thanks in advance!

there is nothing about a battery in the tutorial. how did you connect the battery to Uno if you connected the solenoid to Vin, where I would connect the battery too?

Hi, thanks for your resonse!
I connected the battery to the standard jack.. (wich obviously is not present on the pro mini)

Because you are using a 9V battery, do not remove the power regulator as per the instructions in your second link. You need that regulator to lower the voltage down to the 3.3V or 5V (depending on the version chosen).

You can connect more than one wire to a single Arduino pin.

@sa_leinad:
Thanks, that was one major doubt, even if it sucks a lot of energy.. (i would choose the 3.3, since i do not need a lot of processing power, it does not need to be fast or super-precise timing).
In another tutorial (on the uno however) they talk about replacing the linear regulator with another one by soldering out the default one and putting in a dc-dc regulator... do you think that that would work to save power on the mini too?

@Gerben:
You mean connect two wires to the raw-pin? and when the first one inputs power, the second one gets 9v too beside the arduino?

@pixx: Yes, there are more efficient DC-DC regulators out there, particularly switchmode regulators. It won't save you a lot, but the difference may be worth it.

Exactly. That’s what I meant.

Vin and the barrel jack are the same power input on Uno.
RAW is the label for Vin on Mini Pro.
You can connect the + of the battery to power rail of the breadboard and from there to Vin/RAW pin of Arduino and to the solenoid powering contact.

Thanks!
That sounds great! I connect the + from the battery to lane 1 for instance and from there one pin goes to the arduino and another pin to the solenoid if i understand the solution?


text:
Can I use 1 clock module for multiple Arduinos?
I want to connect an RTC to a master Arduino, send the time data to a slave Arduino through I2C, then connect an LCD to the slave and print it out.
can it be done? A think it would mean that the slave Arduino is a master for the LCD a the same time and it would mess up my code. Any input would be highly appreciated.

the LCD is I2C? what model?

I believe it's SPI. The model is LCD1602.

LCD1602 is just a description of the size - a 16x2 character LCD. What specific LCD is it you have?

And does it have the I2C backpack?

I2C allows for multiple masters. So you could connect the RTC to both Arduinos at the same time. Though you might have to do a bit of extra work to prevent the Arduinos from accessing the RTC at the same time. Either prevent those collisions, or gracefully handle them when they occur (which depending on how often you access the RTC, might be very rare).

The LCD is connected over SPI. The MCU can be an I2C slave and the SPI master. There is no conflict.

From what I understood. I think you are trying to pass time to 2 ardruinos using one RTC.
m.a. = master arduino
s.a. = slave arduino
                            RTC
                            /\ (i2c)
                        m.a.  s.a.-------------(LCD)
                         L______|(spi)

No you cannot
but you can read time in master and then relay it to slave using your own protocol (i.e. "Apr  4 21:20:16 IST 2018") and let it print to LCD.
      RTC ------ m.a. ======= s.a. ++++ (lcd)
            i2c          spi
        (read reg.)  (pass string)

Humble NOTE:- If possible draw some digram while you are explaining circuit. It will be far easy to understand and answer than explaining circuit. may be draw on paper and upload to igmur/drive and add link in question or upload it here.
My ascii digrams may not be best but I think they pass message clearly.

The actual wording of the question is clear and without conflict: " connect an RTC to a master Arduino, send the time data to a slave Arduino through I2C, then connect an LCD to the slave and print it out."

there was ambiguity as in subject it was mentioned about connecting to two arduinos.

The word in the subject says "for" not "connecting to"

my mistake I misinterpreted it. But I still felt it was not very clear so mentioned it. This was my view.


text:
How does the build process in Arduino IDE work for ESP8266
How does the build process for esp8266 work in arduino IDE. Arduino ide uses avr-gcc to compile programs For atmel micro controllers. Does it uses same for compiling programs for esp8266?

Does it uses same for compiling programs for esp8266 ?.

No. It uses xtensa-lx106-elf-gcc. The compiler has to match the architecture.
Most of the build "process" (as in the actions that are taken) is the same, but executables specific to the EXP8266's XTensa core are used. There's also a few extra things in there, like building the (optional) SPIFFS image, etc.

What about uploading code to the board, does it use avrdude for that. Is uploading process same for various boards like nodeMCU or wemos D1.

No, it uses the ESP8266 specific program, called esptool.  Every executable run is the ESP8266 specific one.


text:
MKR1000 - Connecting to Pubnub
I don't know if it's a stupid question but I need some help.
I am trying to follow this tutorial and I want to connect my arduino to PubNub. In the tutorial it says that I have to 'open PubNub.h and switch the comments for the Ethernet and WiFi lines' with some code provided there. But, when I open the file PubNub.h the only thing in there is this:
/* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */
#include "PubNubDefs.h"

class PubNub PubNub;

I'm quite new to this so I don't know much. I hope someone can help. Thank you in advance!

It appears the tutorial is now outdated and the PubNum library does not need the changes described in the tutorial.
The PubNub library has an example titled PubNubWifi101 which shows the client type being set with a #define before including the PubNub headers:
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

I don't have a MKR1000 to test with, but I was able to compile the example from the tutorial by adding that single #define after the #include <WiFi101.h>.


text:
Send IR success but doesn't turn on the TV
My circuit is simple:
IR sensor (from left to right): PIN 11, GND, 5V
IR transmitter: GND, PIN 1 (via resistor). (BTW: all of the tutorials I read says that the PIN should be 3 but from some reason it sends only when it connected to PIN 1. How do I know? because I can "see" the light via the mobile's camera like the image below)

I'm trying to "record" an IR signal and sent it. The code come from gits I found:
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);
IRsend irsend;

boolean recording = true;
decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (recording) {
    if (irrecv.decode(&results)) {
      Serial.println("IR code recorded!");
      //irrecv.resume(); // Receive the next value
      Serial.print("Recorded ");
      Serial.print(results.rawlen);
      Serial.println(" intervals.");
      recording = false;
    }
  } else {
    // replay mode
    for (int i = 0; i < 3; i++) {
      Serial.println("Sending recorded IR signal!");
      irsend.sendRaw((unsigned int*) results.rawbuf, results.rawlen, 38);
      delay(40);
    }
    delay(2000);
  }
}

https://gist.github.com/jeje/3027236
Like you can see in the image, the signal is sent but it does nothing to the TV (I record the TV's remote of course)

Are you sure your remote runs at 38kHz?

@Majenko thanks! I'm not. I thought that it's kind of generic. How can I know? Can I print it somehow?

You can only really know by connecting a photodiode up to an oscilloscope and examining the actual waveform directly.

Can I use the arduino to exam it?

pin 1 is Serial TX. on Uno. what is your board?

Pin 3 is way more sensible on an Arduino Uno/Nano because it can do PWM. The library needs to pulse out a 38kHz PWM modulated waveform at a PWM capable pin. The reason you are able to see the infrered LED light up at pin 1 is because that is the TX of your UART at 9600 bits per second, way slower than the IR PWM. You must use the pins outlined in https://github.com/z3t0/Arduino-IRremote

Also double check the contents of results.rawbuf becore sendRaw, e.g. by serially outputting every byte. Maybe you're sending something different than what you want.

I believe, I see an receiver IC on your board. If it is one for 38kHz modulated IR signal and you receive pulses from it, then your remote definitely works with 38kHz

@MaximilianGerhardt the thing is I can't see the light in pin 3 and also, it doesn't work. I can see the light in all of the remotes I have. Why it's different in the arduino?

@chrisl I don't know what is receiver IC. Also, why do you think it's not working?

By the way, my arduino is uno r3 based on atmega328p-pu. And I can't find it in the list of the IR library.

Try attaching an visible led for debugging. Most remotes the the code multiple times, so that might explain why you can see those codes, but not on your own, is your own is just too short.

Your Uno R3 belongs to the ATMega328 section of that table, i.e. transmit on Pin 3 (and using Timer2). And you are right, you should see something there on Pin 3. I would exchange the IR LED for a normal red LED and look at in a dark room. You should see a very dimm light being emitted. What's the value of your resistor?

Can you tell us what is your TV model ?
Let me explain why: the freq and codes used in remotes are (almost) normalized. Therefore, by knowing your TV model, you could find the right IR protocol. There are libraries for IR codes in Arduino, if your TV model IR protocol matches one available in arduino IR lib, then you're done.

I will try to connect regular led to PIN 3. Thanks! I tried 220 and 1k resistors.


text:
Arduino MKR1000 as Access Point
I want to turn my Arduino MKR1000 into an Access Point. My code is the following:
#include <SPI.h>
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

WiFiServer server(80);
char ssid[] = "MKR1000";
int status = WL_IDLE_STATUS;

void setup() {
  delay(1000);
  Serial.begin(9600);
  Serial.print("Creating access point named: ");
  Serial.println(ssid);
  if (WiFi.beginAP(ssid) != WL_CONNECTED) {
    Serial.println("Creating access point failed");
    while (true);
  }
  server.begin();
  printStatus();
}

void loop() {

}

void printStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  Serial.print("To connect, join the network and open a browser to http://");
  Serial.println(ip);
}

After uploading this, in the serial monitor I get this:
Creating access point named: MKR1000
Creating access point failed

I'm new to this so I really don't know what's the problem. I hope someone knows what's going on.Thank you in advance.

Hopefully you mean you want the board to function in AP mode for connected clients to exchange messages specifically with it.  Trying to actually make it a wifi access point in the sense of a wifi router is not a viable idea.

Yeah sorry, that's what I meant.

I found this reference for Wifi.beginAP() in the Wifi101 library, which I hope is the correct one - apologies if it's not.
It says that beginAP() returns either WL_AP_LISTENING or WL_CONNECT_FAILED, so checking for WL_CONNECTED is not sensible.
Try this:
if (WiFi.beginAP(ssid) != WL_AP_LISTENING) {
  Serial.println("Creating access point failed");
  while (true);
}


text:
Interaction between Analog Pins when measuring a DC voltage- a common issue?
Just set up a replacement "Piduino" - a RPi3 connected by USB to an Arduino Uno.  The previous one was the victim of a Diet Big Gulp - spilled on the voltage divider breadboard.  Whoops.  The tiny breadboard with the voltage divider began to rust inside so it got really difficult to keep it working correctly.
This is for the plot named "Indoor 12V Lighting System" at https://www.SDsolarBlog.com/montage
I built a new Uno/breadboard from scratch and swapped it in with the breadboard stuck onto the plastic case.  All nice and tidy.
But the analog inputs were really strange.  It would read really close, but then minor changes to the software would produce wildly varying results.
Imagine my surprise when this morning I discovered that I had plugged the divider's analog input to A4 instead of to A1 where it belonged.
Now that it has been fixed all is well.  As long as the correct pin is being used in the digitalRead it seems not to matter, perhaps.
Here is the plot from before then after I moved the input to the correct location:

The actual voltage was falling from 12.7 down to 12.5, and after moving the pin it settled down to the correct reading.  Then I turned on the charger while the sun is up.  It is tracking the voltmeters perfectly now.
Clearly, the problem was that I was reading the wrong pin.  My fault, obviously. But it got me wondering just how much they affect each other.
So my question is about why I was getting any readings at all?  I would have hoped that the analog inputs were truly separate from each other.  Instead, it appears as if there is crosstalk of some kind.
Is this a common issue?

New information
I see that it has been pointed out that this was discussed in this Q&A:
Should all unused analog input ports be tied to ground for accurate A2D measurements?
But since that does not call it an imperative, just "one of the problems with using analog" I would have assumed that this is not common, so perhaps there is an implied answer there.
It would be a project all by itself to use half the small breadboard to distribute ground to all the other analog pins.  And I've never seen this referenced in any of the documentation.  Nor is there a tag for crosstalk.
So my question still stands:  Is this common when measuring a DC voltage?

You wrote: “Is this a common problem?” I fail to see any problem in what you describe. The behavior you experienced is perfectly normal and, usually, unproblematic.

TNX for the comment.  In response I posted this morning's plot that shows before and after moving it to the correct pin.  The actual voltage was slowly dropping from 12.7 to 12.5 the whole time.

The real problem is not crosstalk. The problem is you were reading the wrong pin. Is that a common problem? Yes, it happens, as people are often distracted. The fix is pretty simple, and you figured it out yourself: read the correct pin. Problem solved.

Mea Culpa.  All true.  I am surprised it showed any reading at all.  It makes me wonder if when I use multiple analog inputs I should use pins that are more widely-separated, kinda like how we use the urinal bank in bathrooms..?  ;-)

Majenko just explained how the internals work, and it makes perfect sense.    It is not crosstalk at all.  He gets the Accepted Answer on merit.

This is normal and expected behaviour.  There are a number of factors that influence it, and it will help to understand the basic internals of the ADC.
In simple terms the front-end of the ADC looks like this:

simulate this circuit – Schematic created using CircuitLab
The MUX selects which pin (A0-A5) is being sampled. Switch SW1 connects the Sample And Hold capacitor C1 to that selected input, which then charges (or discharges) to the same voltage as the input.
After the acquisition period switch SW1 switches position and the ADC circuit is connected to the capacitor.  Over a period of clock cycles the ADC works out what the voltage across the capacitor is and stores the result in the ADCH and ADCL registers.
Now - on a pin that has nothing connected to it, what voltage will be across that capacitor when SW1 is switched to charge it? Well, this is where your strange results come from:

Any charge already in the capacitor will still be there (which is why it can be good to connect the unused ADC pins to ground through a resistor, to remove that charge).
Signals, either in wires, IC pins, or the silicon circuitry in the chip itself, will be capacitively coupled with what is next to it.

That last one is the most critical for your results.  Capacitive coupling.
Place two wires next to each other and they will, through capacitance, try and get the same charge on them. Under most circumstances that attempt to influence the charge is completely swamped out by what is being send down the wire. But, when there is nothing being sent down the wire that charge becomes noticable. A1 will attempt to "float" to the same level as A0, because they're next to each other. A2 will try and float to the same level as A1, A3 to A2, etc.
If you put a signal in to A0 and plot all 6 inputs you will see each has a progressively lower amplitude copy of the signal. It's hopping, capacitively, between the pins. And all because there's nothing to stop it.
If you think "Ah, but it's DC. DC doesn't go through capacitors", then you're wrong.  Wrong in thinking it's DC.  There's a lot of mistaken assumptions about the labels "AC" and "DC".
DC is not what you have.  Yes, there is a "DC component" to what you have (which is manifest as the average of the voltage over time), but there is a large AC component as well.  That AC component is what you are graphing in the form of your changing battery voltage.
Voltage is far more complex than just DC or AC. What you think of as AC is actually a waveform with a fundamental frequency (e.g., 60Hz) and zero "DC offset". Add a DC offset to the signal and it's still AC, but compared to the "lower" end of whatever adds the DC offset, it's just the waveform is "shifted up".
Pure DC, and what doesn't pass through a capacitor, has no signal components. There is only 0Hz and nothing else. Pure DC is almost impossible to create without highly specialized equipment. All voltages in normal life vary, and that variance is the AC component of the signal.

Right on.  Excellent answer, Majenko.  Very thorough.  That explains a lot.  So it is not true crosstalk in the wiring at all.  Got it.  Thanks.

If you do read the 6 inputs, you will greatly enhance the coupling between them, as you will be connecting C1 to each of them in turn.