text:
RFID + LCD + Arduino Mega 2560 = RFID not printing correctly
My Arduino Mega isn't printing the RFID card's tag it simply prints the card's 2 digits at a time but deletes the previous prints. Can I get help with this?
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <LiquidCrystal.h>

Servo myservo;  //creates servo to control

const int rs = 26, en = 27, d4 = 28, d5 = 29, d6 = 31, d7 = 30;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int R=3;
int G=8;
int B=6;

void setup() {
  lcd.begin(16, 2);
  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...");
  lcd.print("Place your card");
  lcd.setCursor(0, 1);
  lcd.print("Near reader");
  lcd.setCursor(0, 0);
  myservo.attach(7);//attatches servo to pin 7
  myservo.write(179);
}

void loop() {
  analogWrite(B, 255);
  // 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 :");
  byte letter;
  String content= "";
  for (byte i = 0; i < mfrc522.uid.size; i++) {
     lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     lcd.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
     lcd.setCursor(0, 0);
  }
  delay(1000);
  lcd.clear();
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "4F 60 3C D9") {
    //change here the UID of the card/cards that you want to give access
    Serial.println("Authorized access");
    lcd.print("Authorized");
    analogWrite(B, 0);
    tone(4, 900, 100);
    lcd.clear();
    Serial.println("Unlocking...");
    lcd.print("Unlocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(100);
    delay(15);
    Serial.println("Unlocked");
    lcd.print("Unlocked");
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 255);
    delay(5000);
    Serial.println("Relocking...");
    lcd.print("Relocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(179);
    delay(15);
    Serial.println("Locked");
    lcd.print("Locked");
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 0);
    delay(100);
  } else {
    Serial.println("Checking Card");
    lcd.print("Checking Card");
    lcd.setCursor(0, 1);
    delay(100);
    lcd.clear();
    Serial.println("Access denied");
    lcd.print("Access denied");
    analogWrite(B, 0);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(100);
  }
 lcd.clear();
 Serial.println("Ready");
 lcd.print("Ready");
}

you did not give a clear explanation ... what does this mean? deletes the previous prints

What it would do is display the two hexadecimal digits in rapid succession and only see the last two for a split second

still not a clear explanation ... are you talking about LCD or serial monitor window on your computer? ... you are sending data to both of those, and both of those can exhibit the behaviour that you describe

it is my lcd that is not doing what i want it to do

OK i fixed it. It is now this :
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <LiquidCrystal.h>

Servo myservo;  //creates servo to control

const int rs = 44, en = 45, d4 = 46, d5 = 47, d6 = 49, d7 = 48;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int R=3;
int G=8;
int B=6;

void setup()
{
  lcd.begin(16, 2);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Place your card near reader");
  lcd.print("Place your card");
  lcd.setCursor(0, 1);
  lcd.print("Near reader");
  lcd.setCursor(0, 0);
  myservo.attach(7);//attatches servo to pin 7
  myservo.write(179);
}
void loop()
{
  analogWrite(B, 255);
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  lcd.clear();
  Serial.print("UID tag :");
  lcd.print("ID:");
  byte letter;
  String content= "";
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     lcd.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) == "4F 60 3C D9") //change here the UID of the card/cards that you want to give access
  {
    delay(5000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning");
    lcd.setCursor(0, 1);
    lcd.print("Database");
    lcd.setCursor(0, 0);
    delay(5000);
    lcd.clear();
    Serial.println("Authorized access");
     lcd.print("Authorized");
    analogWrite(B, 0);
    tone(4, 900, 100);
    lcd.clear();
    Serial.println("Unlocking...");
    lcd.print("Unlocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(100);
    delay(15);
    Serial.println("Unlocked");
    lcd.print("Unlocked");
    delay(5000);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 255);
    Serial.println("Relocking...");
    lcd.print("Relocking...");
    delay(1000);
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    myservo.write(179);
    delay(15);
    Serial.println("Locked");
    lcd.print("Locked");
    delay(100);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 0);
  }else{
    delay(1000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning Databas");
    delay(5000);
    lcd.clear();
    Serial.println("Access denied");
    lcd.print("Access denied");
    analogWrite(B, 0);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(100);
  }
 lcd.clear();
 Serial.println("Ready");
 lcd.print("Ready");
}

had to remove the lcd.setCursor(0, 1);
from line 57.


text:
Why is my SRAM so quickly filled? There are not more than 60 bytes
I have just gone through all my code. At max I use 60 bytes. I have done everything in order to minimize its usage - I even store booleans as bits, not bytes! What could be happening here?
The only thing that comes to my mind are extremely large arrays, like this:
const uint8_t SBoxes[8][4][16] PROGMEM;

However, these are stored in the program memory as you can see. How can I check they are really there and my memory usage? My code is too large to post it here.
EDIT:
IDE tells me (even though I believe it's very inaccurate):

Sketch uses 7,898 bytes (24%) of program storage space. Maximum is 32,256 bytes.
  Global variables use 1,023 bytes (49%) of dynamic memory, leaving 1,025 bytes for local variables. Maximum is 2,048 bytes.

All my literal strings use F() and there are not many of them.
EDIT2:
Code on pastebin. Just for a quick glance, it is really large.
EDIT3:
My Serial prints
ready
some numbers (that's ok I ask it to print out an array)
ENready
again numburs
Enready
...

I ask it to print ready at the very beginning of my program. I ask it to println End of encr near the end of my setup funciton, but as you see it never finishes the printing.
It always behaves like that when I run out of SRAM.

What does the IDE say how much space was used?

Please post the data declarations. Check that all literal strings use F().

I updated my question. Please, see the EDIT.

What does avr-nm -Crtd --size-sort your_elf_file tell you? Look at symbols of type D, B and V.

On what kind of file should I call it? All I have are .ino files. And it doesn't take my project file as an argument. It tells me it 'is not an ordinary file'.

Build the program with the “verbose compilation” option activated. You will see the IDE creates a file with a .elf extension in a temporary directory. That's the file you should give to avr-nm.

You are also using the LiquidCrystal library and Serial (which uses a 64 byte buffer). Removing all else, you end up with about 260 bytes already. Though, I have no idea where the other 750 bytes go to.

Oh I see, you have just taught me something new. Here it is on Pastebin

About the Serial and LiquidCrystal: Yeah, I forgot about it. Thank you for pointing about, but I am afraid not even this solves the riddle.

If you want to learn a lot of details about the 1975 Data Encryption Standard (DES), implementing it from scratch will teach you a lot. However, if your goal is to actually encrypt something, perhaps it would be better to (a) use a more modern cipher such as Twofish or AES; or (b) use a pre-existing library; or both. See Spaniakos, AESLib, AES-library, etc.

When you are asking yourself what is eating so much RAM, the first step
is to look at the symbol table in the ELF file. If you use a makefile, you
probably know where to find the ELF file. If you are using the Arduino
IDE, go to File / Preferences, check “Show verbose output during
compilation”, compile and look at the output: you will see the temporary
directory where the compiler puts your ELF file.
Now run the command avr-nm -Crtd --size-sort your_elf_file and look
for symbols of type 'D' (data), 'V' (vtable) and 'B' (BSS), in either
upper or lower case. On a Unix-style OS you would pipe through
grep -i ' [dbv] '. Running this on your program gives:
00000068 B tx_buffer
00000068 B rx_buffer
00000034 B Serial
00000021 B lcd
00000016 V vtable for HardwareSerial
00000008 V vtable for LiquidCrystal
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000002 D __malloc_margin
00000002 D __malloc_heap_start
00000002 D __malloc_heap_end
00000002 B __flp
00000002 B __brkval
00000001 b timer0_fract
00000001 D encr
00000001 B debug
00000001 B EEPROM

Obviously, this cannot account for the 1,023 bytes of static RAM your
program is using. What this command misses is the literal arrays and
strings. These can be seen with the command
avr-objdump -j .data -s your_elf_file. The literal strings are quite
obvious in the output, the literal arrays less so. Running this on your
program gives a long listing starting with
Contents of section .data:
800100 00000005 2000010e 040d0102 0f0b0803  .... ...........
800110 0a060c05 09000700 0f07040e 020d010a  ................

Now, on the source code we see:
const uint8_t SBoxes[8][4][16] PROGMEM = {
{{14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
 { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
 { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
 {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13} },
 ...

If you translate this to hexadecimal, you get 0e 04 0d 01 02 0f...,
which appears also by the end of the first line of previous listing. So
there is your culprit: all the big PROGMEM arrays. The compiler does not
honor the PROGMEM attribute on local variables.
My first thought was to make the arrays global, and this does solve the
problem. However, as pointed out by Mikael Patel in a comment, the
documentation on PROGMEM states that “variables must be either globally
defined, OR defined with the static keyword, in order to work with
PROGMEM.” Then, making the arrays static const PROGMEM is a cleaner
solution.

It can't. It doesn't make sense to.

I tested simply defining them as "static" where they stand and data size drops to 311 bytes.

I tried to take them out of the functions to make them global. To make sure the library works I called the input rigth above the arrays. As you can see the IDE says something different (Sketch uses 7,788 bytes (24%) of program storage space. Maximum is 32,256 bytes.
Global variables use 399 bytes (19%) of dynamic memory, leaving 1,649 bytes for local variables. Maximum is 2,048 bytes.). But it is still out of SRAM - the program loops its Serial the same way as before.

There is actually a line in the Arduino PROGMEM documentation about this "Please note that variables must be either globally defined, OR defined with the static keyword, in order to work with PROGMEM." https://www.arduino.cc/en/Reference/PROGMEM

But it is still out of SRAM - the program loops its Serial the same way as before. - let's not jump to conclusions now. What do you mean "loops its Serial" exactly?

Is it printing fff a lot? Well, you told it to do that.

I use the Serial input for debugging. Once it starts printing gibberish or looping (that means it prints something and starts again from the beginning of the program) I know I have run out of SRAM. No, I mean in Serial, fff is for the lcdDisplay - it never comes to the command anyway, it starts looping before.

Please edit your question and paste into it what it is actually printing. We are now trying to guess what you are getting at.

I have just editted it to make it more clear, good idea.

To elaborate on Edgar Bonet's answer and my comment under it, you cannot usefully put PROGMEM variables as local variables because local (non-static) variables have to be allocated on the stack.
void lookUpInSBox(size_t which, byte *address, byte* binaryOutcome, size_t addressFrom){

   ...

    const uint8_t SBoxes[8][4][16] PROGMEM = {

                             /*S1*/

   { {14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
     { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
     { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
     {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13}    },

You could make them global. But if you prefer  not to do that, put static in front of them. Doing that on your code reduced it to 247 bytes.
Global variables use 247 bytes (12%) of dynamic memory, leaving 1,801 bytes for local variables. Maximum is 2,048 bytes.

You expect a bit more than the 60 you counted. The serial buffers take a bit (128 bytes).
See Putting constant data into program memory (PROGMEM) for more information. On a tiny sketch I found the following 346 bytes already in use:

34 bytes for the HardwareSerial instance (Serial)
64 bytes for the Serial transmit buffer
64 bytes for the Serial receive buffer
4 bytes for the Serial transmit buffer head and tail pointers
4 bytes for the Serial receive buffer head and tail pointers
9 bytes for keeping track of millis / micros
4 bytes for memory allocation (__malloc_heap_start, __malloc_margin)
128 bytes for the heap safety margin
6 bytes for a few nested function calls (main -> setup -> getFreeMemory)
16 bytes for the compiler vtable for HardwareSerial
4 bytes for variables __brkval and __flp (used in memdebug)
2 bytes pushed onto the stack in main (to save registers)
2 bytes pushed onto the stack in setup (to save registers)
4 bytes pushed onto the stack in getFreeMemory (to save registers)
1 byte because the stack pointer starts at 0x8FF rather than 0x900

The sketch on my page used dynamic memory allocation so it used a bit more than yours does (for keeping track of it).

Once it starts printing gibberish or looping (that means it prints something and starts again from the beginning of the program) I know I have run out of SRAM

I'm a bit puzzled by all the new/delete you are doing. Why do that? For example:
byte *E;
E = new byte[48/8];
for(size_t i = 0; i < 48; i++){
    insertBit( E, i, bitValue( R, E_BIT[i]-1 ) );
}

// XOR Kn and  E(Rn-1)
byte KxorE[48/8];
for (size_t i = 0; i < 48; i++){
    insertBit( KxorE, i, bitValue( K, i ) ^ bitValue( E, i ) );
}
delete[] E;

Massive amounts of dynamic memory allocation may fragment memory. Can't you rewrite to not do that? You can pass arrays by reference, it just seems weird (and slow) to do all that allocation.

You mean like const uint8_t SBoxes[8][4][16] PROGMEM? I have tried it and although the IDE lowered the numbers of memory usage, the program still loops its Serial input - it is still out of SRAM :( Even if I add your additional bytes to my numbers we get nowhere near 2000.

I don't understand that. Therefore it is not out of SRAM, unless you dynamically allocate memory a lot. See my comment under Edgar Bonet's answer.

See my amended answer about dynamic allocation.

I need both of the E and KxorE arrays. What I can do is not to delete them, but not much more. Originally I was worried about the SRAM so I deleted everything I could. Of course I am going to optimalize its speed, but only when it runs. But thank you for that tip, I didn't know memory allocation would be that slow.

It's not that slow but it is slower than not doing it. If you use local variables rather than dynamic ones, then you save the allocation / deallocation. You would need to modify the functions to take an argument by reference, or pass a pointer (depending on whether or not the function modifies the argument).

If you redesign to not use dynamic memory, at least you know that once you have enough memory at the start, you won't use any more of it.

Yeah, I know. Maybe you have noticed that in order to save even more bytes I use the EEPROM. Well, I can't save more space. That means that even reprogramming it would be useless.

What do you mean you "can't save more space"? If you switch from dynamic allocation to using static arrays, it should work. You have heaps of RAM free (only using 12% at present).

Ok, I guess I don't understand the heap anymore. I thought that pretty much the stack and the heap both occupy the same space - one on each end and the program collides once they have no more space between them. But basically it doesn't matter if I have int[5] or new int[5]. I am going to rewrite it to static arrays.

I've been just told that if I save the arrays in PROGMEM I need to use pgm_read_byte / pgm_read_word to read them. Might this solve the problem?

@SlowerPhoton: “it doesn't matter if I have int[5] or new int[5].”. With the former, there is no risk of memory fragmentation, and there is no risk of you forgetting to delete the array. And to answer your last comment, not using the pgm_read_*() functions is clearly a bug. Whether it's the only bug in your program, I cannot say.

I've been just told that if I save the arrays in PROGMEM I need to use pgm_read_byte / pgm_read_word to read them. - absolutely. They are different address spaces. I didn't look at your code in that level of detail to notice that you weren't.

source: Stack Exchange

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

sort: votes


text:
Bootloader sequence
If I got the picture right(correct me if I'm wrong) the standard bootloader senses the serial comm, and if nothing is read it passes control to the core program, which roughly corresponds to
int main(void) {
    init();
    setup();
    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
    return 0;
}

I wish to understand what happens when  (while the core program is running) I upload a new sketch (using the IDE or avrdude). I guess that the bootloader regains control when something is read in the serial comm, and this happens via a board reset (triggered somewhere inside serialEventRun).
If so, how does this flow interplay with the usage of the serial port? Assume I want to use avrdude to upload the sketch via USB, and also use the serial comm during the program execution.

Opening a serial connection will reset the board, and thus load the bootloader. Which board are we talking about?

Most computers begin execution at (or jump indirect through) location zero on startup. There may be variations, but this is the general idea. Whatever is put at location zero when the bootloader is installed causes the bootloader to gain control on a power-up or a reset. After that, it is up to the bootloader what happens next.
What usually happens is that the bootloader watches the serial port for the start of a "handshake" sequence; when (if) it sees what it is looking for, it replies in a manner that lets the loader program, e.g., avrdude, know that this is the bootloader replying and not some random text that was being sent just at that moment. (If the bootloader doesn't see the the handshake sequence begin within a short period, or it sees something other than the handshake, it starts the existing user program).
From there, the loader program and the bootloader cooperate to transfer the user program to the Arduino and load it into Flash memory at specified locations. Also transferred along with the user program is its starting address. When the upload is finished and verified, the bootloader transfers to the user program's starting address.
At this point, the user program owns the machine, including the serial port(s), and will continue to do so until another power-cycle or a reset. There is no need for the user program and the bootloader to negotiate use of the port; the bootloader owns it from reset to end-of-upload, and the user program owns it thereafter.
Update:

However at that point (while the user program is running) I can start
  an upload (from the IDE or avrdude).

This is possible only because avrdude can send a hardware signal (not contained in the data stream) that the Arduino board uses to cause the chip to reset. It is still the reset process that transfers control from the running program to the bootloader. As an example, on a number of my hand-built boards I did not include that auto-reset circuit. On those boards, avrdude cannot begin a new upload autonomously; I have to manually reset them when I start avrdude.

"At this point, the user program owns the machine, including the serial port(s), and will continue to do so until another power-cycle or a reset." However at that point (while the user program is running) I can start an upload (from the IDE or avrdude).

@leonbloy - only by doing something that resets the chip or convinces part of the running sketch to return control to the bootloader.  An example of the first would be toggling an flow control signal connected via a capacitor to the target MCU's reset.

It sounds like you're missing the fact that the Arduino IDE resets the Arduino board by toggling one of the comm port flow control signals. This causes a hardware reset on the Arduino board and then things happen as you've explained.

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


text:
WiFi module ESP8266-01 for Arduino not working
I am new to using Arduino just bought my first one yesterday, and I also got an WiFi module. The Arduino I got is another brand but should be the same as the Arduino Uno rev 3 and I got the ESP8266-01 wifi module.
I've tried doing some simple examples projects following some YouYube videos, and all those have worked without problem.
What I am trying to create is a simple magnetic door switch. When it's opened I get a signal to my computer. Getting the magnetic door switch wired with the Arduino and getting an LED to light up when the magnetic switch opened worked without problem.
But to set up the wifi module, I can't get it to work.
I have spent hours and hours watching tutorials reading all I can find to trying everything to get this to work, but no luck.
I don't know If I am doing something wrong (probably) or if something is broken.
These are the instructions I am trying currently.
Video of my Arduino setup
For the Arduino board I use 12v DC in and USB from my PC.
Code:
#include "Arduino.h"
#include "ESP8266.h"

#include "SoftwareSerial.h"
SoftwareSerial  ConsoleOut(8, 9);

#define SSID  "ASUS"
#define PWD   "tmpPassword"

void setup() {
  char  *ipAddress, ap[31];

  WiFi.reset(WIFI_RESET_HARD);
  WiFi.begin(9600);
  ConsoleOut.print("flag2");
  if (WiFi.join(SSID, PWD) == WIFI_ERR_OK) {
    ipAddress = WiFi.ip(WIFI_MODE_STA);
    ConsoleOut.print(F("\n\rIP address:"));
    ConsoleOut.print(ipAddress);
    ConsoleOut.print(':');
    ConsoleOut.print("flag1");
    if (WiFi.isConnect(ap))
      ConsoleOut.println(ap);
    else
      ConsoleOut.println(F("not found"));
  } else
    while (1);
}

void loop() {
  if (WiFi.connect((char *)"www.google.co.jp", 80) == WIFI_ERR_CONNECT) {
    if (WiFi.send((const uint8_t *)"GET / HTTP/1.1\r\n\r\n") == WIFI_ERR_OK) {
      int16_t c;
      uint16_t len = WiFi.listen(10000UL);
      while (len)
        if ((c = WiFi.read()) > 0) {
          ConsoleOut.write((char)c);
          len--;
        }
    } else
      ConsoleOut.println(F("Send fail"));
    WiFi.close();
  } else
    ConsoleOut.println(F("TCP connect fail"));
  WiFi.disconnect();
  while (1);
}

Code:

Different from the example sketch is that I use 2K instead of 3K resistors for R2, R4 and 1K for R1, R3. (2K on left side in the video 1K on the right side)
The LED of the WiFi lights red constantly. I don't know what that means,  and the blue LED on the wiFi module lights up whenever I upload a sketch to the Arduino.
Thanks in advance. Any help is really, really appreciated.

Did you set the baud rate of the esp to 9600? Setting it in code is not enough.

@Jamie when I read other people doing that they say they bricked the esp8266, I changed it to 115200 in code, I believe that is the default?not that It really made any difference, if I try to send command in the serial monitor nothing happens.

SoftwareSerial can't handle that speed. 9600 is the maximum. I'll write an answer because I've to paste some code you can use.

@PatrikFröhler What library are you using, could you send a link?

library https://github.com/Hieromon/ESP8266

Use this code to send commands to the ESP:
#include <SoftwareSerial.h>

    SoftwareSerial esp8266(2, 3);

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

      esp8266.begin(9600);
    }

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

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

This simply reads everything from the ESP chip and sends it to the console and vica versa.
To modify the baud rate on the chip, send the following command in the serial monitor:
AT+UART_DEF=9600,8,1,0,0

This sets the baud rate to 9600 and remembers it for further use.

Nothing happens with that code serial monitor blank, what should I have the serial monitor set to when trying to send commands?

I recommend 9600. You probably won't see anything at first. But after a reset you should see your responses. To test responses send the following command: AT, you should get OK bad.

After I reset I only get "   ⸮  ⸮       ⸮⸮  " in the serial monitor nothing happens when trying  AT

The two other problems i can only think of is using other resistors than 1k and a different voltage than 3.3 volt..

Try another library, because I just tested yours and it doesn't work for me as well. https://github.com/itead/ITEADLIB_Arduino_WeeESP8266


text:
Arduino library creation - Calling library and Merging
I am new to creating a library in Arduino. I was able to create a library from YouTube. I want to merge two other libraries into the library I created. Can you please help me to do so?
I already created a keywords.txt file for my library but the keywords are not getting highlighted in orange in the IDE. But it identifies as keywords.
Please guide me how to properly create a keywords file and merge the libraries.
Keywords below:
# -----------------------------------------------------------------------------------
# Syntax coloring for IotBlueEmon library
# -----------------------------------------------------------------------------------

# Datatypes (such as objects)
CurrentSense KEYWORD1

#Methods / functions
begin   KEYWORD2
Counter1   KEYWORD2
Counter2   KEYWORD2
counter3   KEYWORD2
getCNT1   KEYWORD2
getCNT2   KEYWORD2
getCNT3   KEYWORD2

# Constants

please delete the comment. it clutters up the post. you have added it correctly to the question. (there is a little red X next to the comment. it shows up when you hover the mouse pointer over the comment)

If you consult the Arduino Library Specification's section on keywords.txt:

A tab should be used to separate each name from the KEYWORD1/Keyword2/Literal1 identifier.

A true tab character is required, rather than spaces, as you have in your keywords.txt. It is common for text editors to be configured to add a given number of spaces when the tab key is pressed rather than a true tab character. That's great but in this case you will need to be sure that the tab character is used.
Note that the tab requirement will be relaxed in the Arduino IDE 1.9.0 release, which will also accept space(s) as a keywords separator but it's still best to use tabs for backwards compatibility since people will be using pre-1.9.0 IDE versions for years to come.


text:
Setting timer3 in CTC mode - conflict with servo library
I would like to set up a timer in order to call a function 800 times per second. I'm using the Arduino Mega and Timer3 with a prescaler of 1024. To choose the prescaler factor I've considered the following steps:

CPU freq: 16MHz
Timer resolution: 65536 (16 bits)
Divide CPU freq by the chosen prescaler:
16x10^6/1024=15625
Divide the rest through the desired freq
62500/800=19.
Put the result + 1 in OCR3 register.

I've used the following table to set registers of TCCR3B:

The error
It is impossible to compile the code. This is the error returned by the compiler:

Servo\Servo.cpp.o: In function '__vector_32': C:\Program Files
  (x86)\Arduino\libraries\Servo/Servo.cpp:110: multiple definition of
  '__vector_32' AccelPart1_35.cpp.o:C:\Program Files
  (x86)\Arduino/AccelPart1_35.ino:457: first defined here c:/program
  files
  (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/bin/ld.exe:
  Disabling relaxation: it will not work with multiple definitions

The code
volatile int cont = 0;
unsigned long aCont = 0;
void setup()
{
 [...]
  // initialize Timer3
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3A = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3A);
  // enable global interrupts:
  sei();
}

void loop()
{
 // Print every second the number of ISR invoked -> should be 100
 if ( millis() % 1000 == 0)
 {
   Serial.println();
   Serial.print(" tick: ");
   Serial.println(contatore);
   contatore = 0;
 }
}

[...]

// This is the 457-th line
ISR(TIMER3_COMPA_vect)
{
    accRoutine();
    contatore++;
}

void accRoutine()
{
  // reads analog values
}

How to solve the conflict with the servo library?
SOLUTION
Conflict solved using the following code. It compiles but the counter associated with the 800Hz timer doesn't increment its value.
volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  Serial.println("Setup completed");
}

void loop()
{
  if (millis() % 1000 == 0)
  {
    Serial.print(" tick: ");
    Serial.println(cont);
    cont = 0;
  }
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

Since the main problem has been solved, I've created another question here related to the problem of the counter incrementation.

Do you use the servo library in your progam or not?

Servo.cpp probable does also ISR(TIMER3_COMPA_vect)

@jfpoilpret yes, I'm using motors. I will add the lines in the question. I've read that the servo library uses timer1 on the atmega328.

@jfpoilpret Maybe changing the timer will solve the problem.

Just use Timer1, 4 or 5 instead.

Servo defines interrupt functions for timers 1,3,4 and 5 on megas for COMPA. How about using COMPB?

Haven't tried it yet, I'll do it asap.
How many timers are available considering that I'm using functions like millis(), micros(), servo, serial and i2c communication?

@Gerben Thx, I think I would get the same issue using timer1 since it is used by the servo library as well

You are right. They are just hogging all timers. I guess you have to alter the library slightly by removing the #define _useTimer3 line, or try putting a #undef _useTimer3 right after the include.

@BrettM I've tried with COMPB. It compiles but the timer doesn't work. Should I set te output Compare Register OCR3B to 625 instead of OCR3A?

You will need to load ORC3B instead of ORC3A yes. Also you need to enable the Compare B interrupt in TIMSK3 (change OCIE3A to OCIE3B)

@BrettM Could you please answer the question with the suggestions provided

Unfortunately, The Servo library reserves output compare A (OCR*A) on timers 1,3,4, and 5 when loaded on an arduino mega. Each can only have one ISR, so you will not be able to define your own TIMER*_COMPA_vect while you use Servo without modifying the library.
However, each hardware timer is equipped with 2 output compare registers. Servo does not claim any TIMER*_COMPB_vect interrupts, so those are free to use, and work exactly the same.
You should watch out for the Servo libraries activities, it could change the configuration of your timer. The default order is on megas is 5,1,3,4 and to give each 12 servos. It only configures the timer once it needs it, so you should be fine using timer 3 until you add that 25th servo.
To change your code, use OCR3B instead of OCR3A (the Output Compare Registers) and set bit OCIE3B instead of OCIE3A in TIMSK3 (the Output Compare Interrupt Enable bits). Then you to change your ISR function to  ISR(TIMER3_COMPB_vect){}
CTC mode only works with OCR3A, but if you set TCNT3 to 0 in your interrupt function you can get similar behavior. Remember to remove the line that turns CTC mode on using WGM12.

Ok thanks! Any advice on the incrementation of the counter?


text:
How to fix error line number offset in Sublime Text when compiling for Arduino
When compiling for Arduino via the Stino plugin line numbers are not represented correctly in the output. For example, I have an error on line 117 however the output is: sketch_name.ino.cpp:136:1: error:

The #line preprocessor directive is used to tell GCC both what the next line should be numbered as and what filename should be reported, and the plugin is not generating them properly. This is therefore a Stino bug.

In that case, couldn't you just add a #line 1 at the top of the ino file?

Sure, but that shouldn't be the responsibility of the programmer.

Thanks for the suggestions. I tried the #line 1 suggestion @Gerben however the errors are still showing on the wrong line.

Also thanks @IgnacioVazquez-Abrams I've added this to the issues on the Stino github repository.


text:
Error reading from PROGMEM
I was trying to run a code from this https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/
I am pasting it here.
/*
 * ESP8266 NodeMCU jQuery CDN Demo
 *
 * https://circuits4you.com
 */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

//ESP Web Server Library to host a web page
#include <ESP8266WebServer.h>

//---------------------------------------------------------------
//Our HTML webpage contents in program memory
const char MAIN_page[] PROGMEM = R"=====(
  <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

  circuits4you.com

)=====";
//---------------------------------------------------------------

//On board LED Connected to GPIO2
#define LED 2

//SSID and Password of your WiFi router
const char* ssid = "circuits4you.com";
const char* password = "yourWiFipassword";

//Declare a global object variable from the ESP8266WebServer class.
ESP8266WebServer server(80); //Server on port 80

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
 Serial.println("You called root page");
 String s = MAIN_page; //Read HTML contents
 server.send(200, "text/html", s); //Send web page
}
//==============================================================
//                  SETUP
//==============================================================
void setup(void){
  Serial.begin(115200);

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

  //Onboard LED port Direction output
  pinMode(LED,OUTPUT);

  //Power on LED state off
  digitalWrite(LED,HIGH);

  WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only

  WiFi.begin(ssid, password);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  server.on("/", handleRoot);      //Which routine to handle at root location. This is display page

  server.begin();                  //Start server
  Serial.println("HTTP server started");
}
//==============================================================
//                     LOOP
//==============================================================
void loop(void){
  server.handleClient();          //Handle client requests
}

When I deploy this to my nodemcu esp-12e, I a m getting below error
I used the exception decoder
Exception 3: LoadStoreError: Processor internal physical address or data error during load or store
PC: 0x4000bf64
EXCVADDR: 0x4023d581

From the decoder it says the offending line is this one
void handleRoot() {
 Serial.println("You called root page");
 String s = MAIN_page; //<<<<<<<<<<<<<<<<<<<<<< Error on this line
 server.send(200, "text/html", s);
}

It looks like it cannot read from the variable in PROGMEM..
I replaced that line with this code and converting it into a string and the error was gone.
String MAIN_page = R"=====(
  <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

  circuits4you.com

)=====";

Is there something wrong in the code that I am following on how it reads the variable from the PROGMEM flash memory?

server.send_P(200, "text/html", MAIN_page);

In the ESP32, anything declared as const will end up in the rodata segment, which then will go into flash and is read directly from that.. Don't know about the ESP8266.

https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html PS why the UNO tag?

You cannot assign a PROGMEM string directly to a String object. Besides, the whole concept makes no sense, since String objects store their data in RAM regardless.
If you want to use PROGMEM you need to use const char * not String.

String s = (const __FlashStringHelper*) MAIN_page; would work and does use RAM only temporary. it could be useful to replace some parts of the string. But the whole approach by OP to this is wrong.

Yes, I just followed everything from that link.. I am just not sure how they are able to make it work at their end though.

The whole point of using PROGMEM is to save the RAM for other uses.  If you have a huge string that would overflow your RAM then PROGMEM is essential.  However, if the string isn't too large and the program works fine, then just use String instead of PROGMEM.

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


text:
need to get values from a function with structure pointer argument and print on serial terminal
I am developing a code in which I need to print value of structure pointer on serial terminal.
Below is my code snippet:
typedef struct
{
  uint8_t AB;     ///< Address byte (Start byte)
  uint8_t CB;     ///< Command (index) "ASCII-byte"
  uint8_t SI;     ///< Action (sub index) "ASCII-byte"
  uint8_t PH_1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
  uint8_t PH_2;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
  uint8_t PL_1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
  uint8_t PL_2;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
  uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
  uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
} rs485_message_t;

int proto485ComposeMsg(rs485_message_t* msg, uint8_t address, uint8_t command, uint8_t action, uint16_t value){
  msg->AB = address;
  msg->CB = command;
  msg->SI = action;
  msg->PH_1 = (int)((value & 0xF000) >> 12) ;
  msg->PH_2 = (int)((value & 0x0F00) >> 8);
  msg->PL_1 = (int)((value & 0x00F0) >> 4) ;
  msg->PL_2 = (int)(value & 0x000F);
  int checksumRaw = (msg->CB) + (msg->SI) + (msg->PH_1) + (msg->PH_2) + (msg->PL_1) + (msg->PL_2);
  setCheckSum(msg);
}

uint8_t proto485Write(uint8_t address, uint8_t command, uint8_t action, uint16_t value)
{
  int i = 0;
  int stringOne[9] = {int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00)}; ;
  rs485_message_t rs485Msg;
  proto485ComposeMsg(&rs485Msg, address, command, action, value); // value is passed in "raw" format
  Serial.write(rs485Msg);       // getting error on this line
}

Please help... Thank you

You can't just print a structure. After all, how is the program supposed to know how it is supposed to be displayed?
Do you want just the raw data, or do you want it formatted in a human readable form?
For just the raw data you need to cast the pointer to a type that can be printed as an array. For example:
Serial.write((uint8_t *)&rs485Msg, sizeof(struct rs485_message_t));

To print it in a human readable form you will need to take each value that you want to see and print it separately with any data manipulation that you may want.  For example:
Serial.print("Checksum 0: ");
Serial.println(rs485Msg.CS0, HEX);

Another thing you can do is to change your structure into a class and inherit the Printable class.  You can then implement the size_t printTo(Print &p); member function which sends the data to the p object for printing in the format you want.  Then you can just print it directly as you are trying to do in your code.

Thank you so much it solved my purpose

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


text:
Arduino serial read data conversion, getting garbage values
I am developing code on Arduino to read 9 bytes of data from other controller.
I am getting same arrya elements which is transmitted from controller, but when I convert the same it gives me garbage values, Please help.
Below is my code snippet:
int Test::ID_001(void) {
  int result = 1;
  int i = 0;
  char FWV_AB[84];
  digitalWrite(DIR485,HIGH);
  delay(100);
  delay(10);

  int res = proto485Write(RS485_ADDRESS, CMD_COMMAND_FW_AB, CMD_ACTION_FW_AB, 0x0000);      // Send msg to controller board

  Serial.print("msgsend: ");
  Serial.println(" ");
  Serial.println("Received message from controller is: ");

  int  bufferIn1[9] = { int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00) };
  digitalWrite(DIR485,LOW);
  delay(100);
  delay(10);

  delay(DELAY);
  if (Serial2.available()== 0) {Serial.print("Error01 "); result = 0;} // Error for response timeout
  while(Serial2.available() > 0)
   {
   bufferIn1[i] = Serial2.read();

   Serial.print(bufferIn1[i],DEC);     // PRINTS CORRECT VALUES HERE SAME AS SENT BY CONTROLLER
   Serial.print(" ");
   i++;
   if(i == 9){
   Serial.println("Controller board version is: ");
   for(int j=3;j<7;j++){
    Serial.print(int(bufferIn1[j]-48)); } // HERE I AM CONVERTING VALUES INTO READABLE FORM
   }
   }
  digitalWrite(DIR485, HIGH);
  delay(100);
 return result;
}

GETTING VALUES AS "9 49 51 48 48 48 50 48 54" while serial read takes place.
MY DATA is "48 48 48 50" i.e. START FROM 3rd POSITION TO 6th POSITION OF RECEIVED BYTE. IT SHOULD PRINT AS "0002" but it gives me "GQQQ" some times "s)))" and such garbage data instead of 0002 value. Kindly guide.
Thanks you

@Juraj thank you for reply.... by using Serial.write it gives same results as before.

my conclusion is that the output is from a different version of the sketch. sketch doesn't upload?

@Juraj I am able to upload the sketch, can be some issue related to time delay? I am not able to figure it out. As when I read the serial input using "Serial.print(bufferIn1[i],DEC);" line it gives perfect results. but I need to separate the data from that array & convert into readable form. But after first read even if I am trying to read it for second time the same values it gives garbage data. Plese guide

the snippet in Question can't print nothing else then numbers. print(int( ) ) will never print G or Q

after writing line as "Serial.print(int(bufferIn1[j]-48));" it should give number as 0002 but it gives some random number like "20187"

I suggest using a termination character (usually \n is used) and only using an input buffer after the command is complete. Otherwise the content in the input buffer might not be deterministic. E.g. if polling the input buffer (locally, at if (Serial.available()) and writing by the external device do not happen synchronously, then the bytes in the buffer will not be at the intended positions.


text:
Relationship between avrdude's "programmer" and bootloaders
I'm trying to understand the "programmer-id" concept, as specified in -c avrdude's option.
avrdude asks me to choose a "programmer-id" among many it knows of.
Let's say (just as an example) I have a Arduino 2560 to which I connect via USB, and I want to program it using the bootloader.  Then, in this scenario,
is one programmer-id and just one supposed to work?
More in general, one has
1) some particular board (MCU, -p in avrdude)
2) some particular programming method/connection (JTAG, ISP, development board, USB/serial,  etc)
3) (if using bootloader) some particular bootloader code in Flash.
How are these things related with the programmer selection? I guess that some (most?) programmers-ids are specific to some programmer connection/method (AND probably with some hardware family?), and they have nothing to do with the bootloader.  What is the programmer to use for a standard Arduino with bootloader, connected via USB? What more can be said?
Furthermore, the Arduino IDE lets me choose "Upload" and "Upload Using Programmer" (the first works for me, the second doesn't). Why this distinction? Isn't a programmer always used? What does the IDE do, under the hood (does it call avrdude?) when choosing "Upload" ?

If you are using the bootloader, you are not using a programmer. The programmer, when used, is connected to the ICSP pins on the Arduino. The bootloader however expects a well-defined sequence of data from the Arduino through the serial port immediately after reset. The bootloader recognizes that (if received) and reprograms the flash.
If you turn on verbose mode for uploading you will see the programmer type:
-carduino

That is, the Arduino is using the bootloader programming method.
See my post here: What happens when code is uploaded using the bootloader?

Furthermore, the Arduino IDE lets me choose "Upload" and "Upload Using Programmer" (the first works for me, the second doesn't).

Yes, with "Upload Using Programmer" you need a programmer, such as the AVRISP which you would plug into your USB port, and then select that as the type of programmer to use. In this case, your Arduino does not need to be plugged into the USB as the serial port is not used for programming.
Note that some programmers supply Vcc (ie. +5V) to the Arduino and some don't. The AVRISP doesn't.

Furthermore, it seems that that "Optiboot" is a different bootloader than the standard included in the Arduino.

As far as I know, recent Arduino Unos (and probably others) ship with Optiboot. Its main advantage is that it is smaller (only 512 bytes).

More in general, do avrdude need to know the particular bootloader?

I think the smaller boards use STK500 protocol (see links below) and the larger ones (eg. the Mega) use STK500 Version 2. That is because they have a larger address space. So yes, it needs to know the protocol.
When I switched my board type to Mega2560 the "-c" option changed to:
-cwiring

I am guessing from that, the "arduino" is code for "STK500" and "wiring" is code for "STK500 V2".
Protocols

AVR061: STK500 Communication Protocol
AVR068: STK500 Communication Protocol version 2

Thanks! "The bootloader however sends a well-defined... " should be "The bootloader... expects ..."? Furthermore, I see "-cwiring" in my IDE (1.6.9) instead of "-carduino"

Furthermore, it seems that that "Optiboot" is a different bootloader than the standard included in the Arduino. Are they compatible, or should one change the "-c" option ? More in general, do avrdude need to know the particular bootloader?

You are right, it "expects" the protocol. I amended the reply. Your other questions addressed in the amended reply.


text:
Arduino is not responding to a Tiny RTC I2C modules, How to fix?
We have an arduino due with a Tiny RTC I2C module and we're trying to print the current time to the serial monitor. However its not working, currently its printing the time as 2165/165/165 (Monday) 165:165:85 (it should read something like 2016/3/3 (Thursday) 4:15:00). Interestingly it continues to read the same thing, it doesn't change, even if I remove the module from the breadboard completely. I have tried this with two of the modules and both have the same exact results. Does anyone know how to fix this?
My schematics are the same as shown here:
http://www.hobbyist.co.nz/?q=real_time_clock
This is my code, it's just the example code from the imported library for the clock.
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
   #define Serial SerialUSB
#endif

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));

    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println();
    delay(3000);
}

Please add the code you're using.

...and a schematic.

Sounds like wiring issue or just unset clock.

It seems your schematic does not include pullup resistors on SDA/SCL wires. I2C won't work properly without pullups (try 4.7k or 10k).

Alright, I'll try it in the morning, its about 10 here, thanks for the suggestion though.

Still nothing, I realised that because I'm using the due, I should be using pins 20/21 for the sda/slc rather than pins a4/a5. But even after changing those nothing happened.

Maybe show a picture of your wiring.  Also rtc.begin() always returns true, so the test will never fail.

http://i.imgur.com/MTJjsiX.jpg    It's a little hard to see, but the red wire is on the 5v to the vcc, white wire is from ground to ground, brown wire is from pin 20 to sda and the yellow wire is from pin 21 to slc.

It seems on this wiring that you put resistors in series betweens Due SDA/SCL and the RTC SDA/SCL. I don't think this is correct. You should try real pullup resistors from SDA/SCL to 3.3V.

I don't quite understand, are you saying I should be using 3.3v rather than 5v, and where should the resistors be?

I mentioned 3.3V because this is the voltage level used on Due; IIRC, any 5V voltage to an input would damage it. A pullup resistor is a resistor between a line (SDA or SDL) and the positive voltage level. I2C wiring is such that these pullups are necessary for the communication to work.

Still no luck, updated image: http://i.imgur.com/3qyJAZx.jpg    I tried the resistors on the 5v to vcc and the other on the sda, and then again on the slc, neither worked.

You have a couple of problems (although the lack of pull-up resistors is not one of them, because the board you linked has pull-up resistors on it).

The DS1307 needs to operate at a minimum of 4.5 volts, so you can't connect it to the 3.3V pin on the Due. (You need to supply it with 5V).
However the Due is a 3.3V device on its data pins, and thus you can't connect the DS1307 directly to SDA/SDL or you will damage the Due.

Thus you need to supply the clock board with 5V, and use a bi-directional logic-level converter, such as this (using two logic-level MOSFETs):

You can buy level-converter boards, but as you can see, one is easy enough to make up.
Now the clock chip runs at 5V, but the logic levels are converted to 3.3V for the Due.
I tested this with mine, and it worked OK.

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 myclock;

void setup () {
    Serial.begin(115200);
    Wire.begin();
    myclock.begin();
}

void loop () {
    DateTime now = myclock.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    Serial.println();
    delay(3000);
}

Output:
2016/3/6 12:0:20
 since midnight 1/1/1970 = 1457265620s = 16866d

2016/3/6 12:0:23
 since midnight 1/1/1970 = 1457265623s = 16866d

2016/3/6 12:0:26
 since midnight 1/1/1970 = 1457265626s = 16866d

A useful technique for debugging is to run the "I2C scanner" I have on my I2C page. The code is:
// I2C Scanner<!-- language-all: lang-none -->
// Written by Nick Gammon
// Date: 20th April 2011

#include <Wire.h>

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

  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }

  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;

  Wire.begin();
  for (byte i = 8; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
}  // end of setup

void loop() {}

If you don't see your device appear in the Serial Monitor, there is no point wondering why the date doesn't change, because it hasn't found the clock at all. You should see something like this:
I2C scanner. Scanning ...
Found address: 104 (0x68)
Done.
Found 1 device(s).

How the level converter works
For more information, read the Philips Application Note AN97055
In brief (taking SDA as an example):

If neither side is driving SDA low, then VGS is zero (they are both 3.3V) and the MOSFET does not conduct. Hence each side is "pulled-up" to their respective voltages. The low side is pulled up to 3.3V and the high side is pulled up to 5V.
If the low side drives SDA low, then VGS is 3.3V which is high enough for the MOSFET to conduct. Since it conducts it also drags the high side low as well (overpowering the 10k pull-up resistor).
If the high side drives SDA low, current initially flows through the drain substrate diode of the MOSFET (it will be a diode drop above 0V, namely 0.7V), lowering the voltage at the source, until VGS is high enough for the MOSFET to conduct. Once it starts conducting then the low side is pulled further lower.

Do you have an actual photograph of this?

I've pulled it all apart days ago, however thankfully I took a snapshot before I did.

To be honest, the schematic is easier to follow. When looking at photos it can be hard to see exactly what is plugged into where.

Thanks Nick Gammon, I will take a closer look at this soon and try it out.

I just noticed that you are using the pins on the right hand side of the module, I think on the board it's labeled as P1, where as I am using the pins on P2, does that make a difference?

No I don't think that matters. As your page says: The most useful pins are duplicated from P1 to P2.

Do you have an actual photograph of this? The MOSFETs finally arrived so I can try this out now but I'm having trouble reading the schematic...

I think the schematic is a lot clearer than any photograph will be. However see amended reply.


text:
How to return the value in Arduino function (that can be read by the connected device)?
Right now I have an RC car program for Arduino. The code is like this:
void loop() {
  distance = Dist.getDistanceCentimeter();
  if(distance<=5 & distance>1)
  if(Serial.available()) {
    lkf = Serial.read();
  switch(lkf) {
  case 'a':
     forward();
     servoX.write(90);
     lkf=0;
     break;
  }
}

I wrote a TCPclient that can order the RC car to move forward by connecting through TCP and sending the message "a" to the Arduino board.
The problem is how to return the distance to the cilent? Is it simply return distance; or something like system.println(distance);? Thanks for helping.

Use serial.println(distance);.

You are using the USB interface, right? So you just use Serial to send data back. For example, this would send the distance every second:
unsigned long lastSent;
void loop() {
  distance = Dist.getDistanceCentimeter();
  if (millis () - lastSent >= 1000)  // every second
  {
    lastSent = millis ();
    Serial.println (distance);
  }

  if (distance <= 5 & distance > 1)
  {
    if (Serial.available()) {
      command = Serial.read();
      switch (command) {
        case 'a':
          forward();
          servoX.write(90);
          command = 0;
          break;
      }  // end of switch
    }
  }
}


text:
How to make the motor car move left-forward / left-backward/ right-forward/ right-backward
I'm using an Arduino Uno to make a motor car. And I successfully made it move forward / backward / left / right.
void forward(void) {
  analogWrite(EA, 254); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void backward(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void left(void) {
  analogWrite(EA, 180); //speed 0 - 255
  analogWrite(EB, 180); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void right(void) {
  analogWrite(EA, 180); //speed 0 - 255
  analogWrite(EB, 180); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

The problem is, I found it is quite strange if I need to first press left/ right and press forward to turn around. I would like to make 4 extra buttons for left-forward / left-backward/ right-forward/ right-backward. Any ideas to create 4 extra functions for that?
Thanks for helping.
Update: Connection
int EN2 = 14;
int EN3 = 15;
int EN4 = 16;
int EN5 = 17;
int EA = 3;
int EB = 5;

Update: Attempted code and hardware connection
void left_top(void) {
  analogWrite(EA, 128); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void right_top(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 128); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void left_down(void) {
  analogWrite(EA, 128); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void right_down(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 128); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

Left top / right top seem not to move at all, and right top / down is just similar to right / left.
And for hardware, I am using
Arduino  AR 293d

For the motor connection, it's like this:

What are the EA, EB, EN2-5 connected to?

Regarding the pins - I wanted to find out the physical (hardware) connections.
Pending an updated answer I presume the EA and EB will set the speed for two motors and EN2/EN3 and EN4/EN5 control the direction of the motors. If that's the case you could make the car turn sideways but changing the speed of only one of the motors. For example:
void forwardLeft(void) {
  analogWrite(EA,128); //speed 0 - 255
  analogWrite(EB,255); //speed 0 - 255
  digitalWrite(EN2,LOW);
  digitalWrite(EN3,HIGH);
  digitalWrite(EN4,LOW);
  digitalWrite(EN5,HIGH);
}

I assume that EA is the left motor and EB is the right motor. This will make the right one rotate twice as fast as the left one so the car should go forward, but also turn left. If you keep this running the car should end up going in a circle. By making the 128 lower you will change how fast the car is turning.
The other functions should be similar.
Caveat emptor - of course this will mean nothing if the beginning assumptions are incorrect.
EDIT
Can't figure out why it doesn't work without having the thing in my hands. Have not found a schematic for that board, but intuitively it should work as described above.
Things you can do to try to figure out - try different numbers instead of 128, the speed of the motors might not vary linearly with the voltage. What you need to obtain is to have one motor go twice as fast as the other one and in the same direction. That should turn the car around.

sorry just return from work , updated question , would you mind have a look? thanks

yes , the reason fail is because it reads only one character in arundio , the fuction itself has no problem

just go to this link.
Visit to
https://www.arduino.cc/en/Tutorial/PWM
At first use PWM to both right side and left side motor.
When right side motor spin/rotate at 255 value make leftside motor rotation speed at about 100 then you will see that it goes left-forward like wise you do rest of other.
Eg.
void setup()
{
  //LEFT MOTOR
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT); // connect pwm pin of left motor at pin9

  //right motor
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT); motor // connect pwm pin of right motor at pin12
}

void loop()
{
  digitalWrite(7, HIGH);
  digitalWrite(8, LOW);
  analogWrite(9, 100);
  delay(1000);
  digitalWrite(10, HIGH);
  digitalWrite(11, LOW);
  analogWrite(12, 255);
  delay(1000);
}


text:
EBay "Development Programmer Board for ATtiny"
Has anyone tried these? Does the ATtiny have a bootloader? What software is used to program the chip? Arduino compatible?
Looks a lot more convenient than programming the ATtiny via an Uno.
http://m.ebay.com/itm/201536595756
/Ola

Does the ATtiny have a bootloader? does it have an attiny?

If you don't have experience working with AVRs at a low level then stay away from that. It doesn't provide any connection for a programmer and relies on the Micronucleus bootloader already being in place.
If you really want to experiment with ATtiny development then go with either an Adafruit Trinket or a Digistump Digispark (both of which already have Micronucleus loaded), or get an AVR programmer and (optionally) a ATtiny13/25/45/85 development board that includes a 6- or 10-pin programming header

It appears to break out all pins, so I would dispute that it does not provide a connection for a programmer.

@ChrisStratton: You can wire a programmer to it, but it does not use the standard 6- or 10-pin connection used for AVR ISP.

Six pins are pretty much only a "because Arduino did that" idea, but if this is an impediment the asker should probably not be attempting embedded projects at all, as essentially anything but blinking an on-board LED will require making individual connections.

Digispark (micronucleus?) USB connection is not reliable: one has to reconnect multiple times for the sketch upload to succeed. "Arduino as ISP" is much more robust solution, it allows changing the clock frequency, does not take any extra memory and startup does not take extra seconds just to decide if someone wants to reprogram it (I used Arduino Nano as my ISP -- a bit clunky setup, but achieves maximum customizability).

The layout of the 8-pins is compatible with the regular 6-pin Arduino ISP, two of the pins just go unused. Only problem is that not all 6-pin cables will fit with two extra pins in the way, but drilling some extra holes in the connector or soldering an adapter together is pretty straight forward.

Okay, so they did think ahead. Fair enough.

This board supports Attiny25/45/85 MCUs. It is possible to use bootloader with this board. It can be a low speed (1.5MBps) USB device. More info can be found in this article: https://makbit.com/web/firmware/breathing-life-into-digispark-clone-with-attiny-mcu/

ATtiny13A is also supported

I just used one of those boards in conjunction with a cheap tinyISP board to program a DIP8 attiny85 using ISP from Arduino IDE.
The pinout matches if you put the IDC cable the right way around. I used a 10-pin IDC cable - I think you'd have to use at least an 8-pin IDC because a 6-pin wouldn't fit with the extra pins on the programmer board, unless you only soldered on the 6 header pins that you need for ISP.

If you program the digistump bootloader onto the attiny85 then you should be able to use the USB socket on that board to reprogram it. But if it's a blank attiny85 then you have to use ISP to program it in the first place.
Here's how I hooked them up:

You can see from the silkscreen that the pins are clearly designed to match up to the Arduino ISP pinout:

TL;DR: It's basically a bigger digispark with a socket and different header.
Just for completeness:
It depends on the product description, recently I ordered two of your link and some of these. Those seem to be the same board as you asked for, but in your link the "Package includes" only mentions the board without MCU, which would render the question pointless.
Like Ignacio already said correctly, without proper equipment you wont get this to work with the Arduino IDE. Once you have a bootloader (e.g. micronucleus) on it (the MCU), you can use it like a digispark.
In fact the USB connection works just like on the digispark and ist not only for power.
The mounted ATtiny85 was preflashed with micronucleus v1.6 and registered as vendor=16d0, product=0753, which means you could even start with it right away, with Arduino IDE and the digistump board manager.
Personally I use these for prototyping small projects with those tinies on the go where you often don't need a programmer. Once you're done or want to do more you can always remove the bootloader and continue with a real programmer. Or you want to reflash while using the reset pin for I/O, also handy.

I don't see than much usefulness in these boards.
Negatives:

The USB port is only for power. Not for programming.
You have to buy an ATTiny chip to put into the socket. It's not included.
There is no way to put this into a breadboard.
There isn't even a way to get to the output pins. So you have to put the chip into this programmer, program it, remove it from the programmer, and place it back into the circuit.
It seems to use an 8-pin header to break out the 8 pins on the ATtiny. You'd have to use some female jumper wires to connect to them.

Positives:

There is a voltage regulator, so you can connect a higher voltage to the VIN pin
There is an 8-pin ISP header, so you can easily connect a ISP programmer, like an USB-ASP

So in conclusion, some minor plus sides, and some major downsides.
Just place the 8-pin DIP ATtiny in a breadboard.

AVR ISP uses 6 or 10 pins, never 8. You might be able to force a 6-pin connector in there, but you probably wouldn't want to.

@IgnacioVazquez-Abrams Oops. I guess this isn't a programming header, but it's the 8 pins of the DIP-chip broken out into a 2x4 header.

The claim that the USB port is only for power is likely erroneous - the surface mount components next to it strongly resemble those used to enable a software-based "close enough" USB data interface, and bootloaders leveraging that idea exist.  While limited, this type of board can be useful for "blink an LED on USB command" type tasks, or even simple ones that do not need data communication in operation.

@chrisstratton I think you're correct. You'd however still need to program the digispark/mononucleos/trinket bootloader. There also seems to be a led attached to one of the pins for a blink sketch. I however stand by my conclusion that it's a rather useless board. Just get a digispark clone if you want USB support. Or better a USBASP and some bare ATTinys.

The socket is important. One of the huge benefits of using these 8 pin packages is the ability to plug and pull over and over again. Sadly there are few development boards not obsessed with USB. Thankfully this one's is a power header and can be removed easily enough. The Digi/Ada offerings and their clones are not socketed. They are also simple enough to do your own boards.
You can program the x5's with the SparkFun Tiny AVR programmer, based on a design by D.A.Mellis using leads, or by transplanting the mcu. And you can do it from an Arduino, either way you are making up or sourcing a lead, as squid style flying leads are tedious.
Otherwise there is a 2k or so bootloader that can be used, which would be most useful for the 85. Without serial support from USB or FTDI this will be hard.
Software

Arduino with core from https://github.com/SpenceKonde/ATTinyCore
avra and avrdude from the command line for assembler, you could also compile C/C++ from the command line but this is not common.
AVR plugin for Eclipse.
Sloeber stand alone Eclipse based Arduino IDE, some quirks.
Atmel Studio 7 based on Visual Studio, requires Windows, requires genuine "Microchip" programmer. Note this is free and includes an emulator.
There is some effort to get this possible with C-Lion by JetBrains.

.


text:
Arduino GSM shield GSM_READY not ready ever
I am using an Arduino Mega and an Arduino GSM shield. I am using the receive SMS example under GSM in the Arduino IDE. My GSM shield's hardware IP is set correctly.
Here is the sketch:

/*
 SMS receiver

 This sketch, for the Arduino GSM shield, waits for a SMS message
 and displays it through the Serial port.

 Circuit:
 * GSM shield attached to and Arduino
 * SIM card that can receive SMS messages

 created 25 Feb 2012
 by Javier Zorzano / TD

 This example is in the public domain.

 http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

*/

// include the GSM library
#include <GSM.h>

// PIN Number for the SIM
#define PINNUMBER ""

// initialize the library instances
GSM gsmAccess;
GSM_SMS sms;

// Array to hold the number a SMS is retreived from
char senderNumber[20];

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("SMS Messages Receiver");

  // connection state
  boolean notConnected = true;

  // Start GSM connection
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
      notConnected = false;
    else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

void loop() {
  char c;

  // If there are any SMSs available()
  if (sms.available()) {
    Serial.println("Message received from:");
    // Get remote number
    sms.remoteNumber(senderNumber, 20);
    Serial.println(senderNumber);
    // An example of message disposal
    // Any messages starting with # should be discarded
    if (sms.peek() == '#') {
      Serial.println("Discarded SMS");
      sms.flush();
    }

    // Read message bytes and print them
    while (c = sms.read())
      Serial.print(c);
    Serial.println("\nEND OF MESSAGE");

    // Delete message from modem memory
    sms.flush();
    Serial.println("MESSAGE DELETED");
  }
  delay(1000);
}

The issue is this line:
if (gsmAccess.begin(PINNUMBER) == GSM_READY)

The serial monitor outputs everything until that line.
It just never gets past it, so I assume it cannot connect? The SIM has no pin code: I have tried it with my phone. The SIM has full signal strength when in my phone. I have tried my other SIM card also but the same thing happens.
This seem to be the same question, yet no answer:
http://forum.arduino.cc/index.php?topic=270551.0

I Have The Same Problem.
But First Of All you have to set your modem Network Band according to your cellular Network Band.
GSMBand band;
String newBand= "GSM_MODE_EGSM_DCS";// Your Band In My case That was
  band.begin();
  Serial.println("Modem restarted.");
  String bandName = band.getBand(); // Get and print band name
  Serial.print("Current band:");
  Serial.println(bandName);

band.setBand(newBand);

Band Help:
  GSM_MODE_EGSM                ---- E-GSM(900)
  GSM_MODE_DCS                 ---- DCS(1800)
  GSM_MODE_PCS                 ---- PCS(1900)
  GSM_MODE_EGSM_DCS            ---- E-GSM(900)+DCS(1800) ex: Europe
  GSM_MODE_GSM850_PCS          ---- GSM(850)+PCS(1900) Ex: USA, South Am.
  GSM_MODE_GSM850_EGSM_DCS_PCS ---- GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

Then You Have To use
gsm.access.begin();

You could always try setting a pin code and then retry
http://arduino.cc/en/Tutorial/GSMToolsPinManagement
What version of the Arduino IDE are you using ? Also, are you sure you are suppying the board correctly ? "It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use."

I had the same problem. Then I used gsm.shutdown(); before gsm.begin(PINNUMBER). After that it goes past gsm.begin(PINNUMBER) but not always. I don't know if this is the right way to do it, but it works for me.


text:
RESTful API with ESP8266 and arduino mega
Anybody had worked with ESP8266 to post data to RESTful web service? I was trying but it's not posting anything. Tried with a test server:
http://www.posttestserver.com/

Serial.println("\nSetting AT+CIPSTART");
String client_conn = "AT+CIPSTART=\"TCP\",\"";
client_conn += SERVER;
client_conn += "\",";
client_conn += PORT;
Serial.println(client_conn);
Serial2.println(client_conn);
delay(3000);
while (Serial2.available() > 0) {
    c = Serial2.read();
    Serial.print(c);
    if(c=='\n\r' || c == '\r\n')
    Serial.println('\n\r');
}

It showed me that it got connected
Now I created POST string
String data = "{JSONBODY}";
String post = "POST /post.php HTTP/1.0\r\n";
post += "Host: posttestserver.com\r\n";
post += "Content-Length: ";
post += data.length();
post += "\r\n";
post += data;

Transmitting data
Serial2.print("AT+CIPSEND=");
Serial2.println(post.length());
delay(1000);
if(Serial2.find(">")) {
    Serial2.println(post);
    while (Serial2.available() > 0) {
        c = Serial2.read();
        Serial.print(c);
        if(c=='\n\r' || c == '\r\n')
            Serial.println('\n\r');
    }
    delay(5000);
    Serial2.flush();
    delay(5000);
}

Returned nothing
Closing connection
delay(1000);
Serial2.println("AT+CIPCLOSE");
while (Serial2.available() > 0) {
    c = Serial2.read();
    Serial.print(c);
    if(c=='\n\r' || c == '\r\n')
        Serial.println('\n\r');
}
delay(5000);
Serial2.flush();

Connection closed
But It returned nothing. posttestserver returns data path where it stored.

There must be two CRLFs between the headers and the data, thus replace post += "\r\n"; by post += "\r\n\r\n";. 2) c == '\r\n' does not make sense, as \r and \n are two different characters.

Thanks man, I will try it and let you know @EdgarBonet :)

@EdgarBonet Thanks man. Another thing I had to do is, I had to add a 1000uF capacitor across VCC and GND as due to data transmission it fall short of power.


text:
Controlling stepper motor direction with push buttons
I'm trying to control the direction of three 28byj-48 stepper motors using the ULN2003 drivers. I am using 6 push buttons, 2 for each motor. what I want is for each motor to be stationary by default and rotate forward when I press on one button and reverse when I press the other.
You can find my code below. When I use the same approach for coding for one motor, it works fine with a suitable speed. But once I add all 3 motors, motor A and C perform fine but with low speed, motor B keeps rotating forward from the start, stops while I'm pushing its forward button and nothing happens when I push its reverse button. I have checked my circuit several times and there's nothing wrong with it.
#include <Stepper.h> //including stepper motor library

//defining pins section

// pins for motor A:
int stepAIN1Pin = 5;
int stepAIN2Pin = 4;
int stepAIN3Pin = 3;
int stepAIN4Pin = 2;

// pins for motor B:
int stepBIN1Pin = 9;
int stepBIN2Pin = 8;
int stepBIN3Pin = 7;
int stepBIN4Pin = 6;

// pins for motor C:
int stepCIN1Pin = 13;
int stepCIN2Pin = 12;
int stepCIN3Pin = 11;
int stepCIN4Pin = 10;

int stepsPerRevolution = 2048; // amount of steps per revolution for the 28BYJ48 motor

int buttonA1Pin = A5;  // pushbutton 1 pin for clockwise rotation of motor A
int buttonA2Pin = A4;  // pushbutton 2 pin for counter clockwise rotation of motor A

int buttonB1Pin = A3;  // pushbutton 1 pin for clockwise rotation of motor B
int buttonB2Pin = A2;  // pushbutton 2 pin for counter clockwise rotation of motor B

int buttonC1Pin = A1;  // pushbutton 1 pin for clockwise rotation of motor C
int buttonC2Pin = A0;  // pushbutton 2 pin for counter clockwise rotation of motor C

Stepper myStepperA(stepsPerRevolution, stepAIN1Pin, stepAIN3Pin, stepAIN2Pin, stepAIN4Pin); // stepping sequence for motor A

Stepper myStepperB(stepsPerRevolution, stepBIN1Pin, stepBIN3Pin, stepBIN2Pin, stepBIN4Pin); // stepping sequence for motor B

Stepper myStepperC(stepsPerRevolution, stepCIN1Pin, stepCIN3Pin, stepCIN2Pin, stepCIN4Pin); // stepping sequence for motor C

void setup()
{
  // Setting up the pushbutton pins to be an input:
  pinMode(buttonA1Pin, INPUT);
  pinMode(buttonA2Pin, INPUT);

  pinMode(buttonB1Pin, INPUT);
  pinMode(buttonB2Pin, INPUT);

  pinMode(buttonC1Pin, INPUT);
  pinMode(buttonC2Pin, INPUT);

myStepperA.setSpeed(15); // Setting the speed for motor A

myStepperB.setSpeed(15); // Setting the speed for motor B

myStepperC.setSpeed(15); // Setting the speed for motor C
}

void loop()
{

int buttonA1State, buttonA2State, buttonB1State, buttonB2State, buttonC1State, buttonC2State;

  buttonA1State = analogRead(buttonA1Pin);
  buttonA2State = analogRead(buttonA2Pin);

 if ((buttonA1State != 0) && !(buttonA2State != 0))  // if we're pushing button 1 and NOT button 2
  myStepperA.step(stepsPerRevolution/8);

 if (((buttonA2State != 0) && !(buttonA1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperA.step(-stepsPerRevolution/8);

  buttonB1State = analogRead(buttonB1Pin);
  buttonB2State = analogRead(buttonB2Pin);

 if (((buttonB1State != 0) && !(buttonB2State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperB.step(stepsPerRevolution/8);

 if (((buttonB2State != 0) && !(buttonB1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperB.step(-stepsPerRevolution/8);

  buttonC1State = analogRead(buttonC1Pin);
  buttonC2State = analogRead(buttonC2Pin);

 if (((buttonC1State != 0) && !(buttonC2State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperC.step(stepsPerRevolution/8);

 if (((buttonC2State != 0) && !(buttonC1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperC.step(-stepsPerRevolution/8);

  }

Please don't put phrases like "Urgent" into the title. You won't get faster results with this.

@chrisl sorry I'm new here! fixed

As I see in the source code of the stepper library, the step() method is blocking, until the given steps are done. With this it would be difficult to drive more than one stepper at a time. I think the AccelStepper library uses a non-blocking step function.

Also: Why are you doing an analogRead(), but don't use it as an analog value. Depending on how you connected the pins, the returned values may be zero only a few times when they should be zero, due to electric noise. Why don't you use digitalRead()?

@chrisl thanks a lot! it worked properly by changing to digitalRead()

your choice of variable names is confusing .... it is difficult to tell at a glance what each variable does ..... try using something like  button_A_FWD_pin instead of buttonA1Pin  and  button_A_FWD_state instead of buttonA1State

Try using digitalRead() for button presses. Chances are your buttons, especially when on a breadboard, don't return exactly 0 for analogRead().
IMHO, simple On-Off switches should always connect your pin to either Vcc or GND, with either the internal pullup turned on (if connected to GND), or an external pulldown resistor in place.
To debug this, you might want to Serial.println() the values of your button states to your Arduino IDE and observe if their values are like you'd expect.


text:
UART ESP and MEGA2560
Could someone help me with some suggestions please?
Using ESP8266 and MEGA2560 on UART interface i want to display the message received on the mega serial to the LCD connected to it on i2c. The problem is that the LCD shows some strange unknown character and the serial monitor corresponding to mega shows this :
LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on

when it should display this:
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF

the code for ESP is this:
int pinLed = 16;
void setup()
{

 Serial.begin(115200);
 Serial.begin(115200);
 pinMode(16,OUTPUT);
 delay(500);
}

void loop()
{

digitalWrite(16,HIGH);
Serial.print("LED on\n");
delay(5000);

digitalWrite(16,LOW);
Serial.print("LED OFF\n");
delay(5000);

}

the code for mega is this:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include<SoftwareSerial.h>
LiquidCrystal_I2C lcd(0x3F,20,4);

void setup()
{

  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  while (!Serial)
  {

    Serial.print("Attempting to connect! ");
    Serial.print("Trying again...");
  }
}

  void loop()
{

  if (Serial.available()>0)

  {
    char c = Serial.write(Serial.read());
    Serial.print(c);
    lcd.print(c);
  }
}

Solution to your problems.

Use println instead of print.
Change char c = Serial.write(Serial.read()); to char c = Serial.read();

Use:
println *emphasized text*

instead of
print *emphasized text*

use println instead print

why should they use println?


text:
What do the charactors " '/2' " mean in the variable declaration?
I'm working on an RS485 project, In the CPP file there are const variables declared in the following manner:
#include <RS485_protocol.h>
const byte STX = '\2';
const byte ETX = '\3';

What does the '\2' and '\3' mean?

The '\2' and '\3' are characters with octal code 2 and 3. Which is nothing more then 2 and 3 in octal and in decimal. The author could simply write const byte STX = 2; const byte ETX = 3;.
Characters with ASCII code 2 and 3 are control characters STX (start of text) and ETX (end of text). Control characters are invisible characters used to control the terminal or as mark characters in communication.

Perhaps the question is more about the '' than the 2 and 3. A list is here: https://en.cppreference.com/w/cpp/language/escape


text:
RFID RC522 reads the previous tag serial with different tag
I hope someone can help me.
I'm using a Mega with RC522, and this happens:
I use a tag, it reads the right serial (e.g. AA:BB:CC:DD). Then I use a second tag and sometimes it gives me the correct value (e.g. 00:11:22:33), but often it gives me the previous tag serial (AA:BB:CC:DD). After a few attempts, it finally gives me the right one (00:11:22:33).
I really can't find what's wrong and i'd be grateful if someone could shed some light.
Here's the code:
if (RC522.PICC_IsNewCardPresent())  {
           RC522.PICC_ReadCardSerial();
          String strID = "";
        for (byte i = 0; i < 4; i++) {
          strID +=
            (RC522.uid.uidByte[i] < 0x10 ? "0" : "") +
            String(RC522.uid.uidByte[i], HEX) +
            (i != 3 ? ":" : "");
        }
        String seriale = strID;

        if (seriale != "0"){

          for(h=0; h<=numerogiocatori -1;h++){

            if (seriale == seriali[h]) {
              lcd.clear();
              lcd.print("Saldo Gioc. ") ;
              lcd.print(h + 1) ;
              Serial.print("tag ID: ");
              Serial.print(seriale);
              Serial.print(" .    ");
              lcd.setCursor(0, 1);
              lcd.print(totaledenaro[h]) ;
              delay(1500);
              lcd.clear();
              lcd.print("Importo");
              lcd.setCursor(0, 1);
            }
          }
        }}}

Thanks to anyone willing to help!

I tried at the beginning but wasn't working, thank you for improving it.

Dario, would you mind sharing your conditional IF solution?

One rule for writing safety code is :
The return value of non-void functions must be checked by each calling function, and the validity of parameters must be checked inside each function.
You forgot to check if the tag has been readed i.e the return value of PICC_ReadCardSerial. If it fails the value is not updated, that is the reason why the value is still the old one.
Using the following code (from the ReadNUID example of the MFRC522 library https://github.com/miguelbalboa/rfid/blob/master/examples/ReadNUID/ReadNUID.ino)
// Init array that will store new NUID
byte nuidPICC[4];

void loop() {

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    Serial.println(F("NUID has NOT been readed."));

  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
    rfid.uid.uidByte[1] != nuidPICC[1] ||
    rfid.uid.uidByte[2] != nuidPICC[2] ||
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    printHex(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
  else Serial.println(F("Card read previously."));

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

void printHex(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
  }
}

the result is

A new card has been detected.
  The NUID tag is:
  97 C6 6E 09
NUID has NOT been readed.
  Card read previously.
  A new card has been detected.
  The NUID tag is:
  CC 16 5D 83
  A new card has been detected.
  The NUID tag is:
  97 C6 6E 09
NUID has NOT been readed.
  Card read previously.
  A new card has been detected.
  The NUID tag is:
  CC 16 5D 83

Sometimes when the second tag is used the tag is not read and the uid remains the same.

Thanks man. I did solve it applying a conditional IF to the ReadCardSerial, but your version is much better!

"One rule for writing safety code is" +1.