text:
upcoming voltage from a button
i use this simple code for arduino :
const int buttonPin = 2;
const int ledPin =  13;

int buttonState = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin ( 9600 ) ;
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    Serial.println ( buttonState ) ;
  } else {
    digitalWrite(ledPin, LOW);
    Serial.println ( buttonState ) ;
  }
}

it's so basic program, I've seen some people work with Resistors when they use buttons, so i wanted to know why, i plugged in one side of the button to the pin 2 , no matter if i plugged in the other side of the button or no to the 5 volte source, the arduino started giving me some ones and zeroes therefore the blinking of the led, so basically that means there's a certain voltage comming from the button to the pin 2, I wonder why and what's the reason for this ?

I see you are new to Arduino, so let's start:
1) if you say it works you might be using an circuit like this:

which is not all bad but you might find trouble. I explain:
1. When you set pinMode(pin,INPUT); you tell arduino to enable a high-impedance state on that pin: it's equivalent to 100Mohm resistor in series in front of that pin, good for getting sensor readings, but when you use a switch the state/reading of that pin (HIGH or LOW) is "floating" when the switch is opened which will give unpredictable readings.
That's why you need to use a "pull-down" resistor, which means you pull down the value of that pin when the switch is OPENED by using GND as reference value for LOW so you are sure it goes down when switch is opened. The resistor also serves as protection (10Kohm is recommended) when the switch is CLOSED as it stops the high current flow/drain (!!5V pin connected to GND!!) that arduino can't support without (aka short-circuit).
2. So you end up with something like this:

I would personally put the resistor and the GND wire between the button and the digital pin wire.
I hope I was useful! If you need/want more documentation check those two links out:
https://www.arduino.cc/en/Reference/Constants look into "Defining Digital Pins modes" section
https://www.arduino.cc/en/Tutorial/DigitalReadSerial here you have an practical example.

that was a fully understandable explanation, thanks, i managed to do what you explained but using 2 resistors, the same as you did, and I added a 100 hm between the pin 2 and the switch button, and it worked perfectly

Note that there is another, easier way to do this. If instead of setting your pin to INPUT, you set it to INPUT_PULLUP then internally the input line is connected through a resistor to +5 volts. Then when nothing is connected to the pin, it reads as HIGH. You connect your input to a switch, and connect the other pin of the switch to ground Now when you press the switch it grounds the input pin, pulling it low. No resistors needed, but it does mean the state of your switch is reversed (HIGH = switch not pressed, LOW = pressed)


text:
Send information (such as a string) over digital pins
I wan't to send information from my arduino digital pins to another arduino's digital pins like a string, or a char. Can I do this without something like Software Serial?
The reason I am asking is because I am wanting to send information from several serial devices to my raspberry pi from an arduino. Thing is, that Raspberry pi only has one set of UART pins, so I was thinking because I have extra arduino uno's, why not send then information to the arduino and have it write the received information to the raspberry pi's digital pins..
Now that I am writing this, I think I will connect the 2 arduinos via a serial connection, and use software serial to write out to the raspberry pi, in three different stages, to get the information to the pi.
The reason I am using the PI is I want to display this information on a large screen with many different options, in short the GPU capabilities are what I am using the PI for, that and Processing.
Question still stands though, can you send information over digital pins?

If you have a RPi, why do you need Arduinos?

@IgnacioVazquez-Abrams I need one arduino to remotely pilot a platform and receive readings from various sensors connected to it, that will transmit that data wirelessly to a raspberry pi, but it will also need several serial devices connected to it..hence my problem, multiple UART's and a good GPU.

Yes, you can send information to/from your arduino digital pins using a method called Bit Banging. Wikipedia (lots more on Google!)
You can use the Arduino to output as an ad hoc serial port or parallel port. The serial could be asynchronous (UART/RS232/I2C) or synchronous (such as SPI).
The down side is you will have to write a fair bit more software to send/interpret the data.
From your description I gather that data is only going one way - from the Arduino to the Pi. I personally would bit bang SPI as I think this would be the easiest and would not require exact timing.

Thanks for the answer. I will keep this in mind! I am just going to use the arduino for multiple serial connections using software serial..so I don't think I will need to "bit bang", but useful none the less. Thanks for answering the question!

@sa_leinad, Not sure why you are going this way if you want to aggregate all data onto the RaspberryPi.  In order to use SPI or I2C you will have to make adjustments to the RaspberryPi Linux kernal.  If you go RS232 you will have to start getty programs on the RaspberryPi for every serial port you manage to set up.  The USB/FTDI solution may be the easiest to implement on the RaspberryPi.  And there is already an FTDI chip on most Arduino Uno's.

There are many different ways of communicating.
In addition to serial you can use a protocol like SPI or I²C. If the Arduino are in close proximity I²C enables many devices to communicate on a common bus.

The RaspberryPi is a fairly complete linux computer.  As such it can be a USB Host to many USB Devices.  If you need more serial ports simply buy FTDI equipped USB to serial cables, plug them into a USB hub and plug that into the RaspberryPi.

Thanks for the answer. If I didn't want to buy any additional parts, could I use an arduino to act as multiple serial connections for the PI?

Also can I take an existing USB cable and cut off an end to get this? Or does something else take place here?

Actually, yes.  The (most) Arduino Uno contain an FTDI chip.  That is how the Arduino talks to the host computer.  I think what you will still need (unless you have a RasPi with lots of USB ports) is a USB hub to aggregate all the Uno's USB cables.

Your 2nd question:  The USB protocol is very complex.  It is likely that you will never cut a USB cable to get to the data.  Only to get to the 5 volts on the out side pins.

source: Stack Exchange

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

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

sort: votes


text:
How can I interface HMC5883L compass board to a smartphone with OTG?
Friends... I have an idea to attach the compass sensor (HIMC5883L) with my  android smartphone using arduino, but I don't clearly know how to do this. I mean I want to make an OTG compass for smartphone for map navigation etc.(Many Smartphones have compass but mine have not).  If anyone had do this or know how to do this, please guide me. Thanks!

Bluetooth might be easier. I'm not sure if OTG and Arduino go along fine.

A cheaply available USB OTG adapter cable (ask eBay) will connect the Arduino to the phone.
You can then connect the compass sensor to your Arduino and write a sketch to retrieve the data from it and send it through the USB serial connection.
Then you need to write some software for the phone to receive and interpret the serial data and display it as a compass.  That is unless you are happy just to have a simple text display (like the Arduino's Serial Monitor) with the compass information showing in it, in which case there is off-the-shelf software that would do that (search Play)

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


text:
How to read NodeMCU GPIO pin status?
I am setting up a page on NodeMCU running as a web server and I want to be able to turn on and off a light based on the url being clicked.
I want to know how I can get the status so that I can set the URL based on the pin status as well as pass  the GPIO pin status in the JSON from the NodeMCU web server.
The code is here.

Independent of the setting of port direction (input or output), pin can be read through the digitalRead():
int pin_light = 3;
int status = digitalRead(pin_light);

The OP said he has a NodeMCU board. Those runs Lua code. Your example seems to be C-code and would not work on a NodeMCU unless you "reflash" it to standard Arduino C-code. Reading a pin on NodeMCU should be gpio.read(PIN)

The OP said he has a NodeMCU board. Those runs Lua code. Your example seems to be C-code and would not work on a NodeMCU unless you "reflash" it to standard Arduino C-code. Reading a pin on NodeMCU should be gpio.read(PIN)

You are rigth, but question refers an example with code and C and it is tagged with C :blink:


text:
WS2812B LEDs start flickering after some time
I've built a WordClock with a NodeMcu and some ws2812b LEDs some time ago and it worked really well for like half a year but now the LEDs are starting to flicker when the WordClock runs longer than some days.
Video of the problem
I've got a 25w meanwell power supply, has this something to do with undervoltage? The strip is connected on both side to the PSU and I've measured stable 5V on the strip back when I installed them.
Any recommendations?

That looks more like a communication problem than a power supply problem.

that looks like a flash, not a flicker ... the LEDs brighten suddenly ... they do not waver in intensity like candle light .... maybe your code turns off all of the LEDs and then lights some of them, and the code loop gets paused when the leds are lit

It seems, that only the already lighted LEDs flash. Is that correct? (Is not easy to see behind the letters). Are you sure, that the voltage is really stable? If you have an oscilloscope, you could check for that. Please also show your code. Maybe it can give a hint about what is wrong. Just a wild guess: Have you checked, if the controlling Arduino maybe resets for some reason? Depending on the code that might cause such a problem

@chrisl the lighted LEDs are working normally but rather the LEDs right next to them have this flashing problem, I tweaked my code a little bit and reduced the update cycle of my FastLED library to only update when the minute actually changes, maybe this could prevent this from happening because before I used called my update lights function every 30ms.

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


text:
Simple reading and writing on Floppy Disk
I am trying to interface a 3.5" floppy drive (read and write data onto floppy disc). Since I need to write just few bit long number on it (16 is more than enough) I am thinking I could write it track-wise (each track is one bit), which gives me teoretically 80 bit long number, so I could write 4 times 16 bit long number for some redundancy.
I found this code, which solves reading data out. For writing I found this page which says, that writing should be similar easy process.
I attached code I am running here. Reading seems to work, but writing not. The interesting part of code is:
void writeData(byte data){
  Serial.println("Writing");
  digitalWrite(writeEnablePin, LOW); //starting spining a motor
  digitalWrite(motorEnableBPin, LOW); //enabling motorEnable
  stepAllTheWayOut(); //moving head to the edge of drive
  for(unsigned i = 0; i<10; i++){ //repeating 10 times
    for(unsigned index = 0; index<=8; index++){ //repeating 8 times (there are 80 tracks)
      digitalWrite(writeDataPin,bitRead(data,index)); //setting data pin
      Serial.print(bitRead(data,index)); //printing out what is being written
      delay(500); //spinning for a while to write all over the track
      digitalWrite(writeEnablePin, HIGH); //stepping not working when writeEnablePin is LOW
      stepIn();
      digitalWrite(writeEnablePin, LOW);
    }
    Serial.println("");
  }
  digitalWrite(motorEnableBPin, HIGH);
  digitalWrite(writeEnablePin, HIGH);
}

The output is:
Setup done.
Writing
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
Reading
111001000
101010001
110111001
001000101
001011001
111111101
110101101
111110011
111111001
101111110

The output is not what should be written. (the bits are changed every time i run the code)
Any idea what am I doing wrong when writing?

Okay, I have little knowledge but I will try my best. 1)Have you tried erasing the disk completely you might be trying to read already written data. 2) Have you checked the timings of the byte sequence. That's all I can think of, sorry if it's not helpful.

If anyone has any interest/input, please visit Controlling Vintage floppy drives Thanks, Tuc

for(unsigned index = 0; index<=8; index++)

I think that need to be
for(unsigned index = 0; index<8; index++)

Otherwise you are trying to read the 9th bit in a byte.

Nice. That is faulty indeed. Doesn't solve reading-writing problem at all though...


text:
I2C from two masters (ATtiny85, ESP8266) to one slave (ATmega328)
I've been working on a project with I2C protocol where an ATmega328 (Arduino) configured as slave, receives messages from an ATtiny (ATtiny85, ATTinyCore by SpenceKonde) configured as master, or from an ESP8266 (ESP-01, Arduino core) configured as master.
All using the standard wire library, powered with 3.3v (LM1117 regulator), SDA and SCL 4.7kohms pull-ups.
The ESP pins used are RX and TX, with 330ohms pull-ups.
Individually, it works (ATtiny to ATmega; ESP to ATmega), but when i connect the three on the same bus, after the first message it stops working and the ATmega doesn't receive more messages.

Code (modified for readability)
ATmega slave:
#include <Wire.h>

const int ADDRESS = 56;

void receiveEvent() {
    Serial.println(Wire.read());
}

void setup() {
    Serial.begin(9600);
    Wire.begin(MY_ADDRESS);
    Wire.onReceive(receiveEvent);
}

void loop() {
}

ESP master:
#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
const int SDA_PIN = 1;
const int SCL_PIN = 3;

void setup(){
    Wire.begin(SDA_PIN, SCL_PIN);
}

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'e';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(2500;)
}

ATtiny master:
#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
// SDA = 0; attiny85 pin 5
// SCL = 2; attiny85 pin 7

void setup() {
    Wire.begin();
}

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'a';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(1000);
}

After some research I found out that the wire library can only work with a single master, is this correct? And the esp can only work in master mode.
Am I doing something wrong, or is this simply not possible?
Are there any protocol alternatives for this design?
A single device that only cares about receiving messages, and multiple other devices that only care about sending messages to the central.
Thank you for your time!

Apparently someone made a ESP8266 I2C slave library: https://github.com/esp8266/Arduino/issues/1330#issuecomment-276210394. If this is true, I'd go with it and make the 328 the only master. There is a multimaster mode in I2C, but if the ESP cannot enable it then I think it is useless.

The problem is in your implementation. If you REALLY need 2 masters there should be a way to make it work.
At the moment the problem that I can see is that both masters continually poll the I2C data lines, effectively this means that the data on the lines is all mixed up and scrambled together. What could do is have 2 wires connecting both masters. When one of the masters is writing to the slave pull the line high, the other master should read this line as high, and not write data to the I2C lines. When the line drops low, it should then take its turn to write to the AtMega. This method would ensure only one master is using the data lines at one time. The implementation is pretty rudimentary and fairly crude and I'm aware the ATtiny may not have enough pins for this.
The best way to solve your problem I think is to have the ESP8266 as your single master, with your ATtiny and ATmega as slaves. Make the ESP poll the ATtiny for its data/instructions it wants to pass to the Atmega, and get the ESP to pass on this data or instructions to the ATmega along with its own data and instructions. This should be a robust and reliable fix.

When I started I had almost no knowledge of I2C or Wire lib, I just assumed that would be possible to have multiple masters and slaves.
For your first solution, it requires one wire for each master, correct? If I latter want to add another send device, it would require 3 extra pins on each master?
For your second solution, I think this is what I'll do, as I have no more pins available on the ESP for the previous solution.
If I started all from scratch, what would be a good implementation?

Well yes if you want each master to be able to pause every other master then yes, you'd need a line from each one to each of the others, you can imagine tgat this wiring would quickly become over complex. However there is another way to avoid having 2 lines and only having one. You give one of the masters greater priority.  Holding a single line high when it wants to talk, letting the other talk the rest of the time. This actually becomes very complicated on the coding side of things though (much more so than you'd initially think), so is best to avoid.

If you have 1 receive only device, and 2 send-only devices, why not make the receive-only device the master, but have it poll (periodically, repeatedly ask) the slave devices to send any data they have pending. That way, there is only one master, and it only asks for data when it's ready (that is, not receiving from some other device.)
One purpose of a master/slave bus system is to avoid contention (two or more devices talking at the same time.) The master tells each device when to send, and only listens after it asks.

The ESP8266 only supports master mode (I think), so at least one of the send-only devices has to be master.


text:
SoftPWM update limitations
i'm using arduino to dimmer 9 led strips with different output pins after an FFT audio analysis gives results at 60Hz = 16ms. [FFT is performed by a PC and sent to arduino using a RF24 module]
I started the project using SoftPWM on pins D2->D9 & A4 with a lower frequency update but now i'm having problems increasing the frequency update. I have already wired 6 copies of that board and i'm looking for a software solution
To diagnose the problem i performed a test sending a pwm value and zero at a certain frequency, if the frequency is high you can only see a lower emitted power
If I set the pwm once I have a stable signal (led intensity)
If I set the pwm every ~10ms (10ms on @ certain pwm, 10ms at pwm=0) I have an unstable intensity, repeating the test on the pin 6 with a normal analogWrite i don't have the problem. With 10ms i clearly see it blinking at a random frequency (~20Hz=50ms), with 15ms I only see it random fluctuating
I'm using arduino Pro mini - 5V - 2kB
Without signals arduino performs 16k cycles/second (most without changing anything), with a 10ms signal it runs at 14k cycles/second so it seems not a load problem.
Can someone help me regarding this problem?

Should I change library
Should I move to a lower level to rewrite a more performing library
Should I use only 6 std pwm, draw again the board, print them again, weld all components again, and test it again?

Thanks!
PS: I can't create the SoftPWM tag for a reputation problem, can a moderator do that?

there's only so much an AVR can do in software, they are limited in "horsepower". Coupled with your FFT workload, it sounds like you're pretty lucky it works as well as it does. analogWrite is "hardware accelerated" so to speak, so if you can use it instead, that should provide higher capacity. You can get external GPIO expanders or DACs, or use a 2nd pro-mini talking to the 1st over uart.

Sorry, I wasn't explicit. FHT is done by a PC, results are sent to arduino using an RF24 module. If not really needed i want to avoid to modify the hardware, since it's inside a printed PCB and i'm worried I must redesign it to handle a new module. I have 6 identical board that receive RF24 packets and enable/disable leds

The problem is not a SoftPWM limitation but a physical one. SoftPWM have a PWM cycle at 60Hz, that makes impossible to update output faster than 34mS and that explain why I see low frequency trying to change the state with every 10 ms.

Hardcoding the IRS I can reach a much faster PWM cycle, keeping the same PWM frequency I have roughly 60% less of CPU used. With a full CPU load and latest version of the code I can reach ~600Hz PWM cycle. I decided to use a ~300PWM cycle to have enough CPU to perform other tasks (mainly handle RF24 to receive packets @ 60Hz and, if needed, forward them too other bases)
Even at higher frequencies average intensity is not stable, but higher the frequency more stable the result. That can be explained because the eye "average" incoming light and that average is not very stable

Since leds are used to produce visual effects I don't need a very accurate output, and 300Hz are enough. (I also don't have big mosfets and I don't want to stress them with higher frequencies)


text:
Length of uint8_t* const array
I've an array of type uint8_t* const with 6 items, defined like this
uint8_t* const neighbourSet[] = {PEER1, PEER2, PEER3, PEER4, PEER5, PEER6};

Whereas each element in this array is static uint8_t defined like this
static uint8_t PEER1[] {0x86, 0xF3, 0xEB, 0x7A, 0xE8, 0x3B};
static uint8_t PEER2[] {0x86, 0xF3, 0xEB, 0x7A, 0xA1, 0x09};
static uint8_t PEER3[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0xED};
static uint8_t PEER4[] {0x84, 0x0D, 0x8E, 0x03, 0x99, 0xD5};
static uint8_t PEER5[] {0x80, 0x7D, 0x3A, 0xC5, 0x2B, 0x79};
static uint8_t PEER6[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0x1D};

When I do
  Serial.print("size:");
  Serial.println(sizeof(neighbourSet));

I get size:24. I am expecting the size to be 6. could someone explain ?
I don't want to hardcode the total number of PEER in a separate integer variable. I want my for loop to run through each element till the total size of array.
    for (int i = 0; i < sizeof(neighbourSet); i++) {
         //do something for each PEER.
         delay(50);
    }

uint8_t* is a pointer. on AVR it is 2 bytes. on 32bit architectures 4 bytes

you want const uint8_t* const neighbourSet?

Hint: sizeof() gives the number of bytes. You are looking for membersof(). It is often defined as #define membersof(x) (sizeof(x) / sizeof(x[0])).

int totalPeers = (sizeof(neighbourSet) / sizeof(neighbourSet[0])); worked. Thanks Mikael !

@MikaelPatel you should post that as an answer. I was going to post the same, but then I saw your comment.

sizeof() gives the number of bytes. You are looking for membersof(). It is often defined as:
#define membersof(x) (sizeof(x) / sizeof(x[0]))

And in the example above:
for (int i = 0; i < membersof(neighbourSet); i++) {
     //do something for each PEER.
     delay(50);
}

For more practical C/C++ macro and type extensions please see the Cosa Types.h file.

Sizeof doesn't work for pointers


text:
problem in uploading the code
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"
Sketch uses 12452 bytes (38%) of program storage space. Maximum is 32256 bytes.
Global variables use 970 bytes (47%) of dynamic memory, leaving 1078 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

Have you been able to upload before or did this problem occur all of a sudden?

Also like mentioned in the ide you should increase verbosity during upload. Maybe there are some hints where to look for a solution...

Try to upload your code without any device connected to Uno. Disconnect all IO pins. Upload the code via onboard USB port.

It means there is no proper communication between the IDE and your Arduino. The reason can be many things:

RX/TX UART port used
USB port broken
USB cable broken
Arduino broken
USB port drivers not properly installed
Problem inside IDE
...

To troubleshoot you could try:

Disconnect RX/TX jumpers
Try another USB port
Remove other USB devices
Try another USB cable
Try another Arduino
Try another PC/laptop
Reinstall IDE
Reinstall USB drivers


text:
about how to write data in the whole EEprom?
I have interfaced AT24c1024 EEprom with ATmega32.AT24c1024, which has 512 pages each of 256 bytes. There are two mode of writing (byte write and page write).
In page write mode, it is capable of writing 256 bytes for page; if we want to write 258 bytes, then the first two bytes in the beginning of that page will be overwritten.
My question is: what should I do to write in the whole EEprom (i.e) if I want to write 300 bytes, I want to writes 256 bytes in a page then continues to the next page and so on?

In that case you write two pages, the first page containing the first 256 bytes and the second page containing the following 34 bytes.
You can do a speed check to see if writing the second page's 34 bytes by using the byte write is faster, but I doubt that.
In case you want to keep from the second page the remainder of the 34 bytes (the 256-34 bytes following), you first read the second page, than you change the first 34 bytes, than write it back.
Also note that there is a limit on the number of writes on a page. This is called page wearing. So if you write these 2 pages very often, you might want to come up with an algorithm to rotate through all the available pages in your EEPROM, and not writing every time to the same 2 pages.
EXAMPLE
Assume you want to write totalBytesToWrite:
// Calculate the number of pages to write, round up.
int pagesToWrite = int((totalBytesToWrite + 255) / 256;

for (int page = 0; page < pagesToWrite; page++) // Current page to be written
{
    // Calculate number of bytes to be written in this page, for the last page, write remaining bytes, otherwise 256
    int pageBytesToWrite = (page == pagesToWrite - 1 ? totalBytesToWrite % 256 : 256;

    // Write page (btw, I do not know what the second argument char deviceAddress means)
    page_write(n / 256, ??, &memory[n], pageBytesToWrite);
}

Dear sir,I want to use the page write mode,when I use it  to write 300 byte,it will write the first 256 bytes in that page and then overwrite the first 34 bytes in the same page to write the rest 34 bytes....my question..how to continue to write these 34 bytes in the next page?

If you overwrite the 34 bytes in the same page you lose the before written 256 bytes (is that what you want?) ... in the function for writing data to the page I guess there is a page number, can you give the link of the API (functions) for that EEPROM (the library you use) ?

The function containing the staring address you want to write from...

To write 'to' you mean?

The address you want to start  writing data from it

Can you give me a link to the library you use?

void  page_write(unsigned long starting_memory_address, char device_address,char x[],int len){
unsigned long temp;
temp=starting_memory_address>>8;
temp >>=8;//remaining is P0
twi_start();
twi_write_address(device_address|(((unsigned char)temp)<<1));
twi_write_data(starting_memory_address>>8);
twi_write_data(starting_memory_address);
for(int i=0;i<len;i++) {twi_write_data(x[i]);
_delay_ms(10);}
twi_stop();
}

So I guess starting_memory_address should be set to 0 when writing to the first page, and 256 when writing to the second page ... the documentation of the library should tell in more detail.

Does that mean that I should make a condition if the number of bytes is more than 256 then the starting_memory_address should be incremented by 255?

I would make a for loop, iterating through each 256 bytes and write page by page incrementing the address to write to (on the EEPROM) and the source memory (data you want to be stored) by the same iterator value.

OK..could you write me a simple pseudo code for this ...thanks

I tried (but cannot check it since I don't have the library nor the EEPROM).

Thank you sir....I am very thankful for you......my regards...

You're welcome ... you can upvote and accept the answer if it helped please. (next to my answer is a digit (0) and an up and down arrow. By clicking the up arrow you upvote an answer (meaning it's helpful), or downvote (if it's a bad answer). In case of multiple answers, you can 'accept' one answer that solves your problem, by clicking the 'accept answer' button (or some similar text).


text:
expected unidentified id before 'if"
#include <iostream>
using namespace std;
char board[3][3]={{'1','2','3'},{'4','5','6'},{'7','8','9'}};
char turn='X';
int draw=0;
int row,column;
void display_board()
{
    system("cls");
    cout<<"\n\n TIC TAC TOE GAME:";
    cout<<"\n\n PLAYER[1]==O\t\t\t PLAYER[2]==X";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t   "<<board[0][0]<<" |  "<<board[0][1]<<"  |  "<<board[0][2]<<"   \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t_____|_____|_____\n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t  "<<board[1][0]<<"  |  "<<board[1][1]<<"  |  "<<board[1][2]<<"    \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t_____|_____|_____\n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t  "<<board[2][0]<<"  |  "<<board[2][1]<<"  |   "<<board[2][2]<<"  \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t     |     |     \n";
}
void player_turn()
{
    int choice;
    if(turn=='X')
    {
        cout<<"\n\t  PLAYER[1]==O's turn";
    }
    if(turn=='O')
    {
        cout<<"\n\t  PLAYER[2]==X's turn";
    }
    cin>>choice;
    switch(choice)
    {
        case 1:row=0; column=0; break;
        case 2:row=0; column=1; break;
        case 3:row=0; column=2; break;
        case 4:row=1; column=0; break;
        case 5:row=1; column=1; break;
        case 6:row=1; column=2; break;
        case 7:row=2; column=0; break;
        case 8:row=2; column=1; break;
        case 9:row=2; column=2; break;
        default:
        cout<<"Invalid input";
        break;
    }
   if(turn=='X' && board[row][column]!='X' && board[row][column]!='O')
   {
       board[row][column]=='X';
       turn='O';
   }
   else if(turn=='O' && board[row][column]!='X' && board[row][column]!='O')
   {
       board[row][column]=='O';
       turn='X';
   }
   else
   {
       cout<<"Box already filled!\nplease try again!!";
       player_turn();
   }
   display_board();
}
int gameover()
{
    for(int i=0;i<3;i++)
    {
        if(board[i][0]==board[i][1] && board[i][0]==board[i][2] || board[0][i]==board[1][i] && board[0][i]==board[2][i])
        return 0;
        else if(board[0][0]==board[1][1] && board[0][0]==board[2][2] || board[0][0]==board[1][1] && board[0][0]==board[2][2])
        return 0;
    }
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            if(board[i][j]!='X' && board[i][j]!='O')
            return 1;
        }
    }
    draw=1;

    return 0;
}

int main()
{
    system("cls");
    while(gameover())
    {
    display_board();
    player_turn();
    gameover();
    }
    return 0;
}

if(turn=='X' && draw=0)
{
    cout<<"PLAYER[2] WINS!!!";
}
else if(turn=='O' && draw==0)
{
    cout<<"PLAYER[1] WINS!!!";
}
else
{
    cout<<"GAMEDRAW!!!";
}

At which line you got the error?

This is no Arduino code, but C++ code for a PC. There is no cin or cout for Arduinos

if after main function is not in a function

Is this even a question? Ir is it simply a post of some random code as "guess where the error is" game? Why are people even putting in any effort to reply when the OP didn't even bother to.put any effort into the errr "question"?

This fragment is outside of a function:
if(turn=='X' && draw=0)
{
    cout<<"PLAYER[2] WINS!!!";
}
else if(turn=='O' && draw==0)
{
    cout<<"PLAYER[1] WINS!!!";
}
else
{
    cout<<"GAMEDRAW!!!";
}

Some other remarks:

Instead of multiple return statements, it is better to create a local variable, set it, and return that one at the end. So only use one return statement per function (that has a return value).
As chrisl mentions: Arduino does not have cin or cout. Use the Serial class for this.
You can replace the following code:

 switch(choice)
 {
    case 1:row=0; column=0; break;
    case 2:row=0; column=1; break;
    case 3:row=0; column=2; break;
    case 4:row=1; column=0; break;
    case 5:row=1; column=1; break;
    case 6:row=1; column=2; break;
    case 7:row=2; column=0; break;
    case 8:row=2; column=1; break;
    case 9:row=2; column=2; break;

by
row    = (int) ((choice - 1) / 3);
column =        (choice - 1) % 3;

Use an enum as return type for function gameover()
E.g. EGameState { Running, PlayerOneWon, PlayerTwoWon, Draw };
This removes also the global variable draw.
You call function gamover twice, one time within the while loop without checking the result.
Do not use a char for the variable turn but the player number, or a boolean (XPlayerHasTurn), or an enum.

For the person downvoting my answer, why?

it is not Arduino 2. it is only a typo. I think we should apply here on Arduino SE this StackOverflow 'rule' https://meta.stackoverflow.com/questions/252256/behavior-on-questions-caused-by-typographical-errors

Completely agree with 1, but I don't see what is a typo in this problem (unless you mean it's it's maybe copy/pasted wrongly). It can be easily converted to Arduino though (replacing cin/cout by Serial class calls).

as an analogy, on the Movies SE a movie identification questions are off-topic. because it was endless count of trivial question

Ok, so only the remark about cin/cout to Serial class is specific Arduino (but indeed, was not the question itself). Next time I will just make a remark and vote to close.

as per my comment above why would you put any effort into a "question" where the OP has been extremely lazy to a) seemingly randomly selected Arduino SE when the code is not intended for Arduino, too lazy to actually explain there problem, too lazy to even try to find the typo, too lazy to format the code and probably too lazy to accept your answer +1 for your answer (its a good answer) +2 for @juraj for trying to keep the site clean. -10 (if I could) to OP.


text:
Arduino Standalone - photo shows incorrect pin wired to MOSI
I have been building a standalone Arduino on a breadboard following the guide, Building an Arduino on a Breadboard. The guide is generally very good, however, I have yet to get the Arduino working, for a number of various reasons, be it misinterpreted, or misread instructions (the reset pull-up resistor connected to GND instead of Vcc, Tx to Tx, instead of Tx to Rx (and vice versa), to name but a few issues that I have had to resolve).  However, I am sure that the following issue is not down to my careless interpretation or lack of attention.
Look at the photo taken from the webpage, Building an Arduino on a Breadboard, on the Arduino website, showing the Sparkfun AVR programming adapter connected to the ATmega IC.

The MOSI on the adapter is shown to be connected, via a dark green wire, to pin 16 on the ATmega chip, whereas the instructions say:

Be sure to refer to the Arduino pin mapping for help wiring this up.

The MISO pin of your adapter will go to pin 18 or Arduino digital pin    12 of your Atmega chip.
The SCK pin of your adapter will go to pin 19 or Arduino digital pin    13 of your Atmega chip.
The RESET pin of your adapter will go to pin 1 of your Atmega chip.
The MOSI pin of your adapter will go to pin 17 or Arduino digital pin    11 of your Atmega chip.

According to the pinout below, Pin 16 is SS and pin 17 is indeed MOSI.

So, to my mind, the photo is definitely wrong. Indeed I was getting avrdude errors when trying to use a USBasp to load a bootloader, when using the wiring as shown in the photo. When I correctly wired MOSI, from the adapter, to pin 17, the avrdude errors disappeared.
Am I correct in my thinking? Has anyone else attempted to build this circuit, following the instructions on the Arduino website, and come across this issue?
I am just looking for confirmation that I am right, before I contact the owner of the web page.

Dark green wire is indeed incorrect. Not sure what it is you are asking here. Is it still not working with the correction you spotted?

@Gerben - Thanks, I was just looking for confirmation that it was indeed wrong in the photo, and that I wasn't just making a stupid mistake. I shall try to contact the owner of the webpage to get the issue rectified, as I am sure that I am not the only person to get confused by this and lose time trying to figure out what is wrong. It does seem to be working better now, yes, since I have changed the wiring.

I have programmed AVR microcontrollers for a while. I would follow the datasheet, instead of the guide you have.
The Atmega168 Pin Mapping shows SS on 16, MOSI 17, MISO 18, SCK 19 and you will also need to connect to RST 1


text:
What if I have burnt my atmega328p?
Actually I am facing a big problem while programming my atmega328p using an arduino uno as ISP.
I followed a video on youtube  "Arduino as ISP" by Notes and Volts. Which look doing the same steps that the majority followed. For the blinking LED sketch the µC worked very well and it did not show any troubles.
So I  decided to carry on , and at this point I needed to upload a new program but this i wanted to upload my program using "avrdude" command line because my code was written with MikroC pro for avr, and here is the command line :
"avrdude -p atmega328p -b 19200 -C arduino -P COM7 -U lfuse:w:0xf7:m -U
 hfuse:w:0xc9:m -U efuse:w:0xff:m -U flash:w:LED.hex:i "
But unfortunately it did not work well and I have got the following error :
avrdude : invalid byte value <ff> specified for immediate mode
 avrdude : write to file 'ff' failed
 avrdude : safemode : Fuses OK
Seeing that error paniced me , that's why I decided to retry the programmation with an arduino sketch and then happened the big issue when the arduino generate an error message about finding a bad microcontroller [error about the device signature] []2.
My last try to find out if I ruined my µC is with switching the µCs; the arduino original and the one that I had to program and unfortunately It was not a good result :
"avrdude : stk500_recv() : programmer is not responding
 avrdude : stk500_getsync() attempt 1 of 10 : not in sync : resp=0x85"
Looking for more than day on the internet and I could not find a valid solution , except the possibility that I really BURNT my µC and I have to buy another one. And this is specifically why I am asking for your help; I need  to know if SO could figure this trouble out.Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .
Thank you
Regards

Without looking into the exact fuses that you set, there are a few that can cause the chip to not take new programming: If you set it to use an external clock crystal, you then need to have that external clock crystal connected to the chip in order to reprogram it. Or if you set the RESET pin as an output, you need a high voltage programmer to reprogram it. Oh, by the way, have you tried to "write bootloader" in the Arduino UI? If you have overwritten the bootloader it probably won't let you reprogram the chip until you've uploaded the bootloader again.

Swapping the ICs would seem to mean you'd be trying to use the misprogrammed target chip as an ISP programmer; that of course won't work.

@ChrisStratton no I did not try to use the misprogrammed target as an ISP programmer, I tried only to upload a simple blink sketch to it to discover if it still working or not

You can't use a misprogrammed IC in an Arduino as it won't have a valid bootloader (on the ATmega series, ISP can only erase the whole chip, so any attempt to ISP that does not install a working one means there will be no bootloader)

@ChrisStratton ook I see what you mean now ; I did not know this information before thank you for this.
So I guess that I have to forget about this chip and buy a new one, Right??

With a working ISP setup and external clock you should be able to fix it, unless you set the reset disable fuse in which case you need a high voltage programmer.  But getting a new one may be simplest.

@ChrisStratton Would you please tell me how to fix it using a working ISP and external clock? it is not because I do not want to buy a new one but I am afraid to face the same errors even with a new one

after two days of searching on internet, I decided to just reburn the bootloader again on my target µC to discover if it's really burned or not.
SO, I guess it was not damaged because I was able to burn the bootloader and upload the blink led  sketch successfully.

The first part of this could be an answer of the "the problem must have been elsewhere" sort; but the second part where you ask a question is not allowed in an answer, and must be removed.

Trying your fuse settings on an
AVR fuse calculator shows that you
have selected an “external full-swing crystal” as the clock source.
Now your ATmega won't work unless you connect it to an external crystal.
Or you could try just sending a square wave into the XTAL1 pin. Then
you can try to reprogram it.

it's already connected to an external crystal. And when I tried to reprogram it, the arduino software generate an error about selecting a bad µC

What if I have burnt my atmega328p?

get a new one.

Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .

based on the information you have provided, no one can tell definitively. you could have changed the fuse settings, or your 2nd chip didn't have the bootloader, or bad connection, ....
a better approach is to get a separate programmer - usbasp for low prices, or dragon (older debugger with hv programming capability) and go from there.

Actually, I am using the arduino as an ISP  programmer because it was decreed by the company I am working for that's why the possibility of using a separate programmer is not allowed .


text:
Arduino Zero (ATSAMD21G) - I2C - continuous wrong data flow
I encountered a strange behavior while running 2 way transmission tests  between 2 Arduino Zero (ATSAMD21G), one master and one slave. Wrong data is being continuously transferred both ways. The expected data is also being transferred in between. I have to filter out the received data to catch it (line 41 in Master's code and 33 in slave).
I'm using the stock wire libraries (being different for the 2 boards), along with Nick Gammon's "I2C_readAnything".
Master's code
Slave's code
I think this continuous flow doesn't allow the bus to be released. It might be what's making it impossible to communicate with a second master (and maybe causing my previous problem)
I also tried my code between a Mega 2560 (slave) and a Zero (master). Fake data is, this time, only being sent one way (from the Zero to the Mega only).
Is there some specific code to add to send data properly from ATSAMD boards? Is it a bug in the SAMD Wire library?
I also had to add a 1ms delay after sending data from the Master. It wouldn't go through otherwise. Shouldn't it be handled by the ATSAMD or the Wire library?

The code had several issues.
receiveEvent, on the slave side, contained a millis if condition timer that made it time out. I moved the timer to the master side before calling Wire.requestFrom.
receiveEvent, on the slave side, was also confusing real data with incoming requestEvent. I added an if statement to compare the receiveEvent data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the Wire library)
I set the global variables used in events as volatile. The code is working too without this tho.
fixed Master code
fixed Slave code

The Slave I2C clock is 100kHz, the Master has 800kHz. Start with the most normal settings, that means also the Master at 100kHz. The return values are not tested in the Master. I think in this situation you should test them. In the Slave you could test the howMany and increment an error counter if it is not right. The I2C bus is not fault tolerant, that means it should always work 100%. If it is unreliable, you should fix it. How long are the wires ? When you connect a 3.3V board via I2C to a 5V board, did you use a level shifter ? Did you connect the GND's of both boards ?

Do you mean the remaining wrong data I'm filtering out with by testing howMany shouldn't be there? When I test it like you advise, I see it's half of the receiveEvent (not a continuous flow anymore, so it's good enough, the bus gets released after each transaction so multimaster is working too now). That's why I think it's confusing requestEvent with data. I'll understand more once I get my logic analyzer.

The Master sets I2C bus speed. The slave's code doesn't contain speed setting. 800 kHz works fine between 48 MHz Nano but too much with the Mega. The wires are less than 1 m long. I'm using a level shifter between the Nano and the Mega. All on same GND. I'll add a test on the data content in my final application for extra safety.

I don't care if 800kHz worked in the past. You have to fix a number of problems, therefor returning to 100kHz would be wise. If everything works fine, you could try higher clocks speeds. But you are not there yet. The I2C communication should work 100%, not 99%. When the howMany is only half of the receiveEvent okay, then your I2C communication is working 50%. You have to fix the problems to make it 100%. Start by using the default I2C clock speed of 100kHz en test the return values in the Master. Maybe you could also store the howMany in a variable when it was wrong and print that variable.

Same @100kHz. howMany = 0 for half of the receiveEvent. For these, Wire.read returns -1, meaning no data.

Thanks for testing. That is very weird. Normally, only a collision in a Multi-Master bus could cause that. The howMany is the number of valid bytes waiting in a buffer. When you read more than the amount of valid bytes, the Wire.read returns -1. I'm out of ideas. It could still be a hardware problem, do you have pullup resistors ? My best guess is that it is a problem in the Wire library for the Zero. I can find a number of issues with the Wire library for Arduino Zero / Feather M0 / Arduino M0 (all ATSAMD21G).

I made some more tests. Pullups are there, around 2 kOhm. I made a first test with 10 transfers, without howMany. The data was randomly wrong in the serial print, but all good on the logic analyzer! code and result Then I made another test with 10000 transfers, with howMany. Any single transfer was good in both the serial print and the logic analyzer. code and result. I'm confused about the 1st result!

It means to me that the Wire library is sometimes triggering receiveEvent when there isn't any incoming data. It's not a big issue tho since there's no wrong data or collision on the bus.

You need to test it at 100kHz. If you can do the same at 100kHz then I suggest to assume that it is a bug in the library and you should work around it. Perhaps the receiveEvent is sometimes accidently called when the I2C transaction has just started. When the Master requests data, the Master should send a NAK at the end, but it doesn't. I read that when writing a register in a Slave followed by reading that register, sometimes a short delay (1ms) is needed between the Wire.endTransmission and Wire.requestFrom. That means there are already three things to improve for the SAMD21 Wire library.

It's behaving the same at 100 kHz. I only see NACK at the end of the reads, before the stop with the logic analyzer. The howMany workaround made it possible to transmit with 100% success. Thanks for all your advises. Adding the other tests you suggested plus retry on collisions made it possible to use the code for multi-master 2 way transmission.

Start with a single byte, with a very small sketch, with both the Master and the Slave at 100kHz. When that is working 100% reliable, then you can try to transfer a struct.
The Slave RequestEvent function should always return valid data, not once every two seconds. The global variables that are used in receiveEvent or requestEvent and in the loop() should be made 'volatile'. Disable the interrupts in the loop() when reading or writing the global volatile struct.
With your sketch, you have to open the serial monitor for both the Master and Slave.
You could add more tests, for example testing the return value of Wire.endTransmissing, testing the 'howMany' parameter, testing the actual number that Wire.request returns.

I simplified the code to test with a single byte 2 way transfer @100 kHz, using volatiles in events like you advised. I'm still seeing the same behavior (after opening monitor on both of course). Transferring one way only is working properly.
Adding more tests sounds to me that it would only hide that fake data is flowing between the devices (like the filtering I did in my initial code). I have to avoid disabling interrups because my final application relies on them (PID motor control and encoder reading...)

Result on slave:
"Arduino connected
...
ÿ
ÿ
m
ÿ
ÿ
ÿ
..."
(should get "m" only; same behavior on master side)
Master     /
Slave     /
One way only Master

I figured out what didn't work in the simplified test. The millis delay in requestEvent was causing it to timeout. I put this delay before requestFrom in the master instead. I have to test the "howMany" parameter in the receiveEvent so it doesn't confuse incoming data with a requestEvent. This should be handled by the wire library in my opinion.  Fixed code


text:
Issue with photoresistor - the analogRead stays pretty much the same?
UPDATE: If I could I'd downvote myself. I'm a web developer and as I see that my job will be eaten, I'm trying to expand my skill set. Sometimes I wish I had a second pair of eyes or https://en.wikipedia.org/wiki/Rubber_duck_debugging

Previously I was asking which sensor use to measure the light: Which sensor to detect light?
Here is a short video showcasing my issue: https://www.youtube.com/watch?v=VGs_Ax_wlbg
Super simple .INO sketch from https://tkkrlab.nl/wiki/Arduino_KY-018_Photo_resistor_module
int sensorPin = A5; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}
void loop() {
  sensorValue = analogRead(sensorPin);
  digitalWrite(ledPin, HIGH);
  delay(sensorValue);
  digitalWrite(ledPin, LOW);
  delay(sensorValue);
  Serial.println(sensorValue, DEC);
}

I'm worried that my sensor readings are pretty much the same - in shade, brighten up by green laser...
Am I doing it right?
Are values from the sensor in the expected range?
Alternatively: is there any more sensitive sensor I should buy that will tell me more reliably if the there is green laser light pointing at it?

It helps if you plug the sensor into ANALOG 5, not into DIGITAL 5 ...

:) It helps... Thank you for being second pair of eyes and sanity check here!

Could you place a filter on the sensor to block out the non green light?
What are the values you are getting and what do you think they should be?

***** ITS ANALOG 5 not DIGITAL 5 *****
Also try doing this:
delay(sensorValue*10);

The times 10 will help show the differences between each value.

It looks like he is using an LDR breakout. Those probably already have a resistor.

True, my bad. There is a 10k k smd tinynynynyny resistor on it. No external resistor needed.

OMG! ANALOG... So silly, that's why I need second pair of eyes (and some common sense)...


text:
How to use and retrieve data file from AT command in Arduino D1 Mini Wemos (With esp8266)
I stumbled upon an AT command for the ESP8266 that I really need. The following command is "AT+CWLAP", but I have no idea how to use it. I can't seem to find any resource on how to implement it.
I need the SSID, RSSI, and MAC addresses of the AP and pretty much use those data internally. For example (not necessarily doing this but you get the point), depending on the signal strength, choose the best option and print the SSID of the AP.
Is it even possible?

It's not clear exactly what you are asking. You have discovered a command that you want to use it. If you have a problem using it, please note that in your question.

@jose sorry about that. Edited to clarify.

The command is documented in the ESP8266 AT Command Reference, with a non-PDF option at https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/#AT+CWLAP
The response from the AT+CWLAP is a series of lines listing available access points, and for each, you are given their encryption method, SSID, RSSI, MAC, and the channel (or frequency offset and a calibration value).
It would be up to the you to parse the resulting strings to obtain the APs, sort by signal strength, and decide what to do with that information.
EDIT:
Because you are using the Arduino environment/core to write code for the ESP8266, you won't be able to use the AT command set. The AT Commands are available when the ESP8266 has the EspressIF firmware loaded to it, and thus the ESP8266 module is intended to be a peripheral device to some other controller; contrast with your use, where the ESP8266 is the only controller, with the WiFi ability baked in.
In this case, you will need to examine the features of the Arduino ESP8266 core, especially the ESP8266WiFi library, which gives an example sketch for scanning the available WiFi networks.

I learned quite a bit about AT command now. However I'm still having a hard time actually inputting the command. A lot of other sites uses SoftwareSerial to communicate with the module (correct me if I'm wrong). I'm using Wemos D1 Mini, which already includes the esp8266 with the micro controller.
Can I get by using "SoftwareSerial ESP8266(10,11)" *I'm assuming those are the rx tx pins.

The AT commands only work if the original Espressif firmware is loaded, and which is likely not the case with the Wemos D1 Mini. Unless, you mean you have a Wemos D1 and another ESP8266. You can update your question to describe your environment (which hardware, connected to what, using which software.)

Okay, are there any other ways to get SSID, RSSI of all detected APs without flashing the original firmware?
If not, I found a way to flash the original firmware. https://wiki.wemos.cc/tutorials:get_started:revert_to_at_firmware

That depends on what firmware you are using. There is an Arduino core, MicroPython, etc. To what is the Wemos connected? On what pins? Details please!

This is the exact one I got. I don't know what firmware I'm using, but I'm using Arduino to code right now. Anything else? https://www.amazon.com/HiLetgo-ESP8266-NodeMcu-bytes-Development/dp/B073CQVFLK/ref=sr_1_7?ie=UTF8&qid=1502912256&sr=8-7&keywords=d1+mini

I edited my answer to show where to find documentation on scanning available APs from the Arduino ESP8266 core.


text:
ESP8266 Wemos D1 Retrieving Wrong AP Mac Address
Using WiFi.BSSID and WiFi.BSSIDstr gives me some weird mac address.
the code is:
#include "ESP8266WiFi.h"
#include "ESP8266WiFiScan.h"

void setup() {
Serial.begin(115200);
//WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("Setup done");
Serial.println(WiFi.macAddress());
}

void loop() {
   int n=WiFi.scanNetworks();
   Serial.println(n);
   for (int network = 0; network < n; network++){
      Serial.println(WiFi.SSID(network));
      Serial.println(WiFi.RSSI(network));
      uint8_t* mac=WiFi.BSSID(n);
      char APmac[13];
      APmac[0]=0;
      for (int i=0; i<6;i++) {
        char buffer[3];
        sprintf(buffer, "%02x", mac[i]);
        strncpy((char *)(APmac+(i*2)), buffer, 3);
        Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
      }
      Serial.println(APmac);
      Serial.println(WiFi.BSSIDstr(n));

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

The current output is 6D:98:C9:00:00:00 which is completely off. It duplicates this output for other APs too. Is this a hardware problem? I've seen other people using the same codes and it works for them. For reference WiFi.SSID(); and WiFi.RSSI(); both spits out correctly.
edit: I was testing both output to see which ever one was correct and unfortunately they're both wrong

Is your for loop duplicated on purpose: "for(int i=0; i<6; i++){for( int i=0; i<6;i++){"  Also, your code prints the segmented string, and then the output of BSSIDstr() -- are both the same output (and both wrong?)

@josecanuc The duplication was done accidentally. I put in both to show that I've used both and they both put out the same wrong address.

What value do you expect, and how was the correct value determined?

I do have the AP mac address values with me already. I'm expecting the result from the two functions to be the same.

What is the expected value? Your code builds the APmac (or APMAC; you are inconsistent in the variable name), but you never print it.

This seems wrong, you are trying to get String to interpret a byte, but are passing in a pointer to a byte:
String digit = String(*mac, HEX);

Try changing your example to:
uint8_t* mac=WiFi.BSSID();              // Gather the byte array
String APmac;
for (int i=0; i<6;i++) {
   String digit = String(mac[i], HEX);  // String() should see an int, not a pointer to a byte, with the directive to print it in HEX format
   if (digit.length() <2)
     APmac += String("0")+digit;        // Corrected capitalization error
   else
     APmac +=digit;                     // Corrected capitalization error
   //mac++;                             // Not necessary
   Serial.print("["); Serial.print(i); Serial.print("]");
   Serial.println(mac[i], HEX);
}
Serial.println(APmac);                  // Print the constructed String
Serial.println(WiFi.BSSIDstr());        // Print the pre-formatted string

Consider not using the String object, which may help condense the code a bit:
uint8_t* mac=WiFi.BSSID();
char APmac[13];
APmac[0]=0;
for (int i=0; i<6;i++) {
   char buffer[3];
   sprintf(buffer, "%02x", mac[i]);
   strncpy((char *)(APmac+(i*2)), buffer, 3);
   Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
}
Serial.println(APmac);
Serial.println(WiFi.BSSIDstr());

your suggested code did help clean up a bit. I think I found a problem: when I connect to a certain AP and ask for the mac address, I get the right one. I've been using WiFi.scanNetworks(); and been trying to retrieve mac address for each AP that's scanned, however it doesn't seem to like that at all. Any thoughts on it?

Post your code for how you use WiFi.scanNetworks(); and so on, since it may be that there are bugs in the code you are using, which we cannot know about without seeing.

Edited the question to put the whole code

And what is the actual output or error you get from that code.

god... I found the bug. Instead of "n" I should have put "network"....

Yes, i just saw that, too.

Fixed it, and now it works perfectly........


text:
Error while uploading code to ESP8266 through Arduino Mega 2560
I am sorry for posting this question for the nth time but I am still not able to find a solution for this error.
I am trying to upload the WiFiScan(Arduino IDE example program)program code to ESP8266 using Arduino Mega 2560. I followed the procedure given here. And I tried uploading it with "Generic ESP8266 Module" and "Adafruit HUZZAH ESP8266" selected as the Board. But I am still getting the following error.
trying to connect
  espcomm_send_command: sending command header
  espcomm_send_command: sending command payload
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

Edited to add:

Connections-
ESP8266 - Arduino Mega2560
Tx - Tx1(Pin 18)
Rx - Rx1(Pin 19)
Gnd - Gnd
Vcc - 3.3V (Directly from Arduino's 3.3V pin)
CH_PD - 3.3V (Directly from Arduino's 3.3V pin)
GPIO0 - Push button K2 (refer photo)
RST - Push button K1
While pressing the K2 button(Flash button - GPIO0), I clicked the K1 button(Reset button - RST) and then released K2. According to the document, this should bring the ESP8266 to flash mode. Now when I upload the code, it throws the above error.

That tutorial doesn't have anything to do with an Arduino Mega and you didn't tell us how you wired it. We can only guess what is wrong.

Add a photo clearly showing your devices and wiring and you might get a better response.

As suggested, I've included the connection details in the question. @gre_gor, Squats

tx to tx and rx to rx ??? have you tried the obvious? tx to rx and rx to tx, seeing as that's how serial connections work

After googling for several hours, I was able to figure out the reason. Thanks to this link. Transferring data to ESP8266 with Arduino acting as USB to Serial converter did not work. Using a USB to TTL converter, and following this link you can easily transfer data to ESP8266.

My Arduino Mega worked as a USB to Serial converter just fine...

@Fusseldieb could you please tell me how you uploaded data using Arduino Mega?

I just plugged TX to TX, RX to RX, GND to GND and shorted RST to GND, causing the Arduino to loop continuously on reset. I also chosen "Tools" -> "Programmer" -> "Arduino as ISP". Then I uploaded the sketch just fine.

I just plugged TX to TX, RX to RX - no you didn't

Why do I see so many people today with the same Tx-Tx Rx-Rx problem.  It's like there was something in the weather today.  Think of it this way, when you have a conversation with someone, do you talk into their mouth and listen to their ears?


text:
Can I use a 6 pin Bluetooth module in a 4 pin socket?
I have a Funduino joystick shield and it features a 4 pin bluetooth socket in the top right hand corner (just above the D, T, - and + legends).

For some reason, on eBay, 6 pin bluetooth modules are cheaper and more common than 4 pin bluetooth modules.

The joystick shield's 4 pin socket is labelled R T - +. Obviously these correspond with RXD, TXD, GND and VCC on the bluetooth module.
I was wondering:

What is the difference between the 4 pin and 6 pin modules?
Can I use a 6 pin module in the four pin socket on the joystick shield?
What is the function of additional STATE and EN pins on the bluetooth module?
Are these two additional pins necessary as other modules do not have them?

What is the difference between the 4 pin and 6 pin modules?

The 6-pin modules have more pins, used for other features.

Can I use a 6 pin module in the four pin socket on the joystick shield?

I don't see why not, as long as you tie/float the other pins appropriately.

What is the function of additional STATE and EN pins on the bluetooth module?

Whatever the documentation says they do.

Are these two additional pins necessary as other modules do not have them?

Probably not. But they provide additional functionality.

Thanks for the confirmation. Butchering a 6 pin module down to 4 pins certainly seems to be the cheaper option.

Just poked around, and EN is connected to the voltage regulator; pulling it low will shut down the whole module. No idea what STATE does though, since it connects to a GPIO.

After some more concerted searching I have found the answer on Success Using the JY-MCU (linvor) Bluetooth Module:

The module has 6 pins labeled on the back, but most modules only have
  4 of those populated with pogo pins.  KEY & STATE seem to be not
  required, as KEY is used for flashing the device and STATE simply
  indicates if the device is awake or not.  So that leaves only GND,
  VCC, TXD, RXD.  Not shown is Pin 11 which is the RESET pin, resetting
  the module when pulled LOW.

So, the answer is apparently yes, and you can buy a cheaper 6 pin module and remove (snip/desolder) the two additional pins.  The EN pin is also apparently labelled as KEY on some modules.


text:
How to drive SPI MAX7219 7-segment led module using MCP23S17 extender
I have used Nick Gammon's (MAX7219) and (bitBangedSPI) libraries to drive SPI 7-segment 8 digit led modules successfully from the Arduino Uno.  I would like to extend the number of Slave Select (CS) choices by using the MCP23S17 chip.  The Mcp23s17 libraries to use might be https://github.com/dreamcat4/Mcp23s17 or https://github.com/MajenkoLibraries/MCP23S17.  I have found the stackExchange entry How do you use SPI on an Arduino? to be helpful and this entry to be helpful http://www.ermicro.com/blog/?p=1050, but all the examples just turn on LED lights, not digits of 7-segment led modules.
I realize I might have to modify the MAX7219 and bitBangedSPI libraries where the digitalWrite command is used.  However, I'm not sure how to modify or drive these 7-segement modules using the MCP23S17 chip.
A skeleton script to display PI selected on pin 6 on the Uno and address 0x0 of the MCP23S17 is shown below.  I would like to choose which pinout to utilize as well but am not sure how this would be coded.

#include <SPI.h>
#include <bitBangedSPI.h>
#include <MAX7219.h>
// Mcp23s17 library available from https://github.com/dreamcat4/Mcp23s17
#include <Mcp23s17.h>

// Wire up the SPI Interface common lines:
// #define SPI_MOSI             7 //arduino   <->   SPI Master Out Slave In   -> SI  (Pin 13 on MCP23S17 DIP)
// #define SPI_MISO   not used 12 //arduino   <->   SPI Master In Slave Out   -> SO  (Pin 14 on MCP23S17 DIP)
// #define SPI_CLOCK            8 //arduino   <->   SPI Slave Clock Input     -> SCK (Pin 12 on MCP23S17 DIP)

// Then choose any other free pin as the Slave Select (pin 10 if the default but doesn't have to be)
#define MCP23S17_SLAVE_SELECT_PIN  6 //arduino   <->   SPI Slave Select           -> CS  (Pin 11 on MCP23S17 DIP)
// MULTIPLE DEVICES
// Up to 8 MCP23S17 devices can share the same SPI bus and slave select pins.
// Assign each chip a unique 3-bit device address (by setting the A2,A1,A0 pins)
// Then below, device address is optional 2nd parameter to the constructor fn...
// MCP23S17 Mcp23s17_0 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x0);
// ...
// MCP23S17 Mcp23s17_7 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x7);

// SINGLE DEVICE
// Instantiate a single Mcp23s17 object
MCP23S17 Mcp23s17_0 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x0);
const byte chips = 1;
static char outputBuffer[20]; // outputBuffer[] likely 2x the size it needs to be.

 // 1 chip, bit banged SPI on pins 6, 7, 8

MAX7219 display(chips, 6, 7, 8);  // Chips / LOAD / DIN / CLK
void setup()
{
    // Set all pins to be outputs (by default they are all inputs)
    Mcp23s17_0.pinMode(OUTPUT);

    display.begin();
    display.setIntensity(1);
    float pi = PI;
    dtostrf(pi, 7, 7, outputBuffer);
    display.sendString(outputBuffer);

}  // end of setup

void loop() { }

An example of the 8-digit 7-segment display.  They are available on Amazon, Ebay, AliExpress etc. This one has 0.33 inch digits; other modules are 0.56 inch digits.

It isn't really clear to me what you want to do here.  Do you want to just use the pin extender for CS lines?  Then you just need to go into those libraries and rewrite to call whatever function writes a pin high or low on the extender instead of whatever digitalWrite it is calling now.  If you want to try to bitbang a completely separate SPI bus out of the extender then that's going to be a bit harder.  Why are you bit-banging SPI instead of using hardware in the first place?

Answering your second question first -- I have used all the hardware SPI pins for multiple displays which are daisy-chained.  Bit-banging allows me to extend to additional displays but takes up too many pins needed for other devices.  The MCP23S17 seems like the logical choice for extension.  I'm a user of the led control libraries, not a library author.

You can use the three hardware SPI pins to connect to as many displays as you want.  The SPI bus is meant to be used by many things in parallel.

I'm curious how "as many displays as you want" is defined.  I have 18 8-digit display modules to control.  Daisy chaining the cheap 8-digit modules doesn't work well past four and certainly not 18.

it is unclear what 7-segment 8 digit led module you are using? .... is it just an LED array without any drivers/decoders?

I have added an image for clarity.  A max7219 drives the 8 digits.  Each digit has 7 segments of LEDs.

I'm not 100% on what you want to do but I have used both the chips you seem to want to do it with.
The MAX7219 can control 8 7Segment displays.
I don't remember it being an SPI device, you just set the pattern you want in the registers and off it goes.  (It could be that is used such a high level abstraction that I didn't realise it was SPI)
The IOX chip you are referring to is quite similar in behaviour, you setup the registers and away it goes.
On the surface it appears you can do what you want, but I suspect you will hit timing issues unless you want very static displays (maybe < 1FPS).  The time it takes you to establish the correct settings on the IOX chips will be the limiting factor.
You might want to look at the I2C version of the IOX which will require just 2 pins to connect to up to 7 ICs.
Alternatively use a network of microprocessors to each drive the maximum number of MAX7219s that they can, such as Nanos, ESP8266-12/NodeMCU, etc.

The MAX7219 chip is designed to be daisy chained -- connect Dout to the Din of the next MAX7219 (see the No-op Register section in the data sheet). I'm not sure if there is a limit to the number that can be daisy chained.
In fact Nick Gammon's library appears to support this.  The "chips" parameter is the number of daisy chained MAX7219s.
The MAX7219 is does not use SPI. As I understand it the SPI/bitBangedSPI libraries are used as a convenient way to send the data bits with a synchronized clock.

Just daisy chain the MAX7219s as already mentioned. I use SPI directly with the chip all time, it works great with the default modes - 4 MHz clock, Mode 0, MSBFIRST.  Many libraries use software SPI to talk to it, which I think is just a waste of the SPI hardware in the '328P family of chips.


text:
Connecting Arduino to internet through HC-06 and then smartphone
Can I use HC-06 to connect the Arduino to a smartphone (which I am already doing) and thereafter take the data to the internet?

Yes, but not in quite the way you think.
In this case the smartphone is acting exactly like the PC when you have the Arduino plugged in to it. You have a serial connection. Theoretically you can:

Send a request to the smartphone over the serial bluetooth connection
Write some software on the smartphone to interpret that request and perform some action depending on what the request is

That way the smartphone is then acting like an incredibly expensive and bulky ESP8266.

Is there an app that can perform this action for me like receiving the bluetooth serial data like 'blueterm' does and sends the data on some condition?

I am not aware of one. There may be one though. You will have to search Play.

old thread I know..
You can use MIT App Inventor to write/make an app for your Android phone.
This will do several things:

pair with your Arduino/BT device.
take data sent from the Arduino/BT device and parse it
do what you like with that data at that point, save to a database..etc. send info to a map (like google maps)..etc

You havent stated what you want to do with the data after it reaches the phone.
Alternately.. you may be able to get rid of the BT device.. and use an ESP8266 wi-fi module and connect directly to a 3rd party web script/service and dump the data directly to the 'internet'


text:
Proper Attiny85 timer/delay
Im having problems with Attiny85 programming. I am making something similar like this project. But i added function that every day on some time it turns on output - something like alarm clock. The real struggle is to make it active for longer time as one minute.. If current time is equals alarm time wake_HOUR==hour()& wake_MINUTE==minute() then it will run only for a minute so I added changeable field for the time how long output should be active - for example 5 minutes despite 1 minute. I tried to make timer with millis() and after those 5 minutes reset timer but this is where i stuck, because compiling for attiny it shows error, but if i use same code sample just for arduino then its working.. Code below:
#include <avr/sleep.h>
#include <TinyWireM.h>
#include <EEPROM.h>
#include "ssd1306.h"
#include "WDT_Time.h"

#define TIMEOUT 6000            //display timeout
#define UNUSEDPINA 1            //RESET
#define ALARM 4                 //ALARM
#define BUTTONPIN  3            //GND
unsigned int wake_HOUR = 0;     //Hours when it should wake up
unsigned int wake_MINUTE = 0;   //Minutes when it should wake up
unsigned int wake_SECOND = 0;   //Seconds when it should wake up - Not using
unsigned long ALARM_TIME;       //How long alarm should be active- changable in display
unsigned long new_millis = 0;   //Timer
unsigned long interval;         //How long alarm should be active
extern volatile unsigned long timer0_millis;
unsigned int ACTIVE_ALARM = 0;  //alarm activated?

#define SET_UP_BUTTON_THRESHOLD 100   //100k
#define UP_DOWN_BUTTON_THRESHOLD 600  //7k
#define PRESSED_BUTTON_THRESHOLD 1000 //NO resistance

// enum
typedef enum {
normal, sleeping
}  run_status_t;

typedef enum {
time_mode, debug_mode, alarm_mode
}  display_mode_t;

// button field constant
#define NO_FIELD 0
#define YEAR_FIELD 1
#define MONTH_FIELD 2
#define DAY_FIELD 3
#define HOUR_FIELD 4
#define MINUTE_FIELD 5
#define SECOND_FIELD 6
#define ALARM_HOUR_FIELD 7      //Alarm Hour
#define ALARM_MINUTE_FIELD 8    //Alarm Minute
#define ALARM_FIELD 9           //How long should alarm be active - minutes
#define SET_ALARM_FIELD 10      //Activate alarm
#define FIELD_COUNT 10
//#define ALARM_SECOND_FIELD 9

// variables
SSD1306 oled;
static uint32_t display_timeout = 0;
static run_status_t run_status = normal;
static display_mode_t display_mode = time_mode;
static display_mode_t last_display_mode = time_mode;
static bool time_changed = false;
static bool alarm_changed = false;
static uint8_t selected_field = NO_FIELD;

uint8_t wake_SET = 0;
//const char wake_BACK[15] = "GO BACK";

void setup() {
  // setup input pins, also pullup unused pin for power saving purpose
  pinMode(UNUSEDPINA, INPUT_PULLUP);
  pinMode(BUTTONPIN, INPUT_PULLUP);
  pinMode(ALARM, OUTPUT);
  digitalWrite(ALARM, LOW);
  interval = ALARM_TIME*60000;

  // init time
  init_time();

  // init I2C and OLED
  TinyWireM.begin();
  oled.begin();
  oled.fill(0x00); // clear in black

  // init display timeout
  set_display_timeout();
}

void loop() {
  // detect and handle button input
  check_button();
  unsigned long currenTime = millis();
  //unsigned long new_value;
  //setMillis(new_value);

  if (run_status == sleeping) {
    // return to sleep mode after WDT interrupt
    system_sleep();
  } else { // not sleeping
    if (millis() > display_timeout) { // check display timeout
      enter_sleep();
    } else { // normal flow
      readRawVcc();
      readRawTemp();
      draw_oled();
    } // normal flow
  } // not sleeping
  if (ACTIVE_ALARM==1)
  {
    if (wake_HOUR==hour()& wake_MINUTE==minute())
    {
    digitalWrite(ALARM, HIGH);
    new_millis = millis();
    }
    else if (currenTime -new_millis <= interval)
    {
    new_millis = millis();
    digitalWrite(ALARM, HIGH);
    }
    else if (currenTime -new_millis >= interval)
    {
    new_millis = 0;
    digitalWrite(ALARM, LOW);
    }}
  else if (ACTIVE_ALARM==0)
  {
    new_millis = 0;
    digitalWrite(ALARM, LOW);
  }
}
//void setMillis(unsigned long new_millis){
//  uint8_t oldSREG = SREG;
//  cli();
//  timer0_millis = new_millis;
//  SREG = oldSREG;
//}

void enter_sleep() {
  oled.fill(0x00); // clear screen to avoid show old time when wake up
  oled.off();
  delay(2); // wait oled stable

  run_status = sleeping;
}

void wake_up() {
  run_status = normal;

  delay(2); // wait oled stable
  oled.on();

  // update display timeout
  set_display_timeout();
}

void set_display_timeout() {
  display_timeout = millis() + TIMEOUT;
}

/*
 * UI related
 */

void draw_oled() {
  if (display_mode != last_display_mode) {
    oled.fill(0x00);
    last_display_mode = display_mode;
  }
  oled.set_font_size(1);
  if (display_mode == time_mode) {
    // 1st row: print info
    oled.set_pos(5, 0);
    oled.print("TIME");
    oled.set_pos(80, 0);
    oled.print("AcALARM=");
    oled.print(digitalRead(ACTIVE_ALARM));
    oled.set_pos(80, 1);
    oled.print("A_TIME=");
    oled.print(digitalRead(ALARM_TIME));
    oled.set_pos(80, 2);
    oled.print("ALARM=");
    oled.print(digitalRead(ALARM));

    // 2nd row: print date
    print_digit(7, 1, year(), (selected_field == YEAR_FIELD));
    oled.write('-');
    print_digit(7 + (5 * FONT_WIDTH), 1, month(), (selected_field == MONTH_FIELD));
    oled.write('-');
    print_digit(7 + (8 * FONT_WIDTH), 1, day(), (selected_field == DAY_FIELD));

    // 3rd-4th rows: print time
    oled.set_pos(30, 4);
    oled.print("SET ALARM");
    oled.set_pos(3, 5);
    oled.print("HH:MM-->ALARM MIN");
    oled.set_pos(95, 5);
    oled.print("ON/OFF");
    oled.set_font_size(2);
    print_digit(0, 2, hour(), (selected_field == HOUR_FIELD));
    oled.draw_pattern(2 * FONT_2X_WIDTH + 1, 2, 2, 2, 0b00011000);
    print_digit(2 * FONT_2X_WIDTH + 5, 2, minute(), (selected_field == MINUTE_FIELD));
    oled.draw_pattern(4 * FONT_2X_WIDTH + 6, 2, 2, 2, 0b00011000);
    print_digit(4 * FONT_2X_WIDTH + 2 * FONT_WIDTH, 2, second(), (selected_field == SECOND_FIELD));
    print_digit(0, 6, wake_HOUR, (selected_field == ALARM_HOUR_FIELD));
    oled.draw_pattern(2 * FONT_2X_WIDTH + 1, 6, 2, 2, 0b00011000);
    print_digit(2 * FONT_2X_WIDTH + 5, 6, wake_MINUTE, (selected_field == ALARM_MINUTE_FIELD));
    print_digit(6 * FONT_2X_WIDTH + 2 * FONT_WIDTH, 6, ALARM_TIME, (selected_field == ALARM_FIELD));
    print_digit(80, 6, ACTIVE_ALARM, (selected_field == SET_ALARM_FIELD));
  }
  else if (display_mode == debug_mode) { // debug_mode
    print_debug_value(2, 'I', get_wdt_interrupt_count());
    print_debug_value(3, 'M', get_wdt_microsecond_per_interrupt());
    print_debug_value(4, 'V', getVcc());
    print_debug_value(5, 'T', getRawTemp());
  }
}

void print_digit(uint8_t col, uint8_t page, int value, bool invert_color) {
  oled.set_pos(col, page);
  if (invert_color) oled.set_invert_color(true);
  if (value < 10) oled.write('0');
  oled.print(value);
  if (invert_color) oled.set_invert_color(false);
}

void print_debug_value(uint8_t page, char initial, uint32_t value) {
  oled.set_pos(0, page);
  oled.write(initial);
  oled.set_pos(14, page);
  oled.print(value);
}

// PIN CHANGE interrupt event function
ISR(PCINT0_vect) {
  set_display_timeout(); // extent display timeout while user input
}

void check_button() {
  int buttonValue = analogRead(BUTTONPIN);

  if (buttonValue < PRESSED_BUTTON_THRESHOLD) { // button down
    set_display_timeout(); // extent display timeout while user input

    if (run_status == sleeping) {
      // wake_up if button pressed while sleeping
      wake_up();
    } else { // not sleeping
      if (buttonValue > UP_DOWN_BUTTON_THRESHOLD) { // down button
        handle_adjust_button_pressed(-1);
      } else if (buttonValue > SET_UP_BUTTON_THRESHOLD) { // up button
        handle_adjust_button_pressed(1);
      } else { // set button
        handle_set_button_pressed();
      }
    } // not sleeping
  } // button down
}

void handle_set_button_pressed() {
  display_mode = time_mode; // always switch to time display mode while set button pressed

  selected_field++;
  if (selected_field > FIELD_COUNT) { // finish time adjustment
    selected_field = NO_FIELD;
    if (time_changed) {
      wdt_auto_tune();
      time_changed = false;
    } //time changed
  } // finish time adjustment
}

void handle_adjust_button_pressed(long value) {
  if (selected_field == NO_FIELD) {
    // toggle display_mode if no field selected
    display_mode = (display_mode == time_mode) ? debug_mode : time_mode;}
  else {
    long adjust_value;
    if (selected_field == YEAR_FIELD) {
      // TODO: handle leap year and reverse value
      adjust_value = value * SECS_PER_DAY * (leapYear(CalendarYrToTm(year())) ? 366 : 365);
    }
    else if (selected_field == MONTH_FIELD) {
      // TODO: handle leap year and reverse value
      adjust_value = value * SECS_PER_DAY * getMonthDays(CalendarYrToTm(year()), month());
    }
    else if (selected_field == DAY_FIELD) {
      // TODO: handle leap year and reverse value
      adjust_value = value * SECS_PER_DAY;
    }
    else if (selected_field == HOUR_FIELD) {
      adjust_value = value * SECS_PER_HOUR;
    }
    else if (selected_field == MINUTE_FIELD) {
      adjust_value = value * SECS_PER_MIN;
    }
    else if (selected_field == SECOND_FIELD) {
      adjust_value = value;
    }
    else if (selected_field == ALARM_HOUR_FIELD)
    {
      if (wake_HOUR >= 23)
      {
      wake_HOUR=0;
      }
      else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
      { // down button
       wake_HOUR--;
      }
      else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
      { // up button
       wake_HOUR++;
       }
        }
    else if (selected_field == ALARM_MINUTE_FIELD) {
      if (wake_MINUTE >= 59)
      {
      wake_MINUTE=0;
      }
      else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
      { // down button
       wake_MINUTE--;
      }
      else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
      { // up button
       wake_MINUTE++;
       }
        }
      else if (selected_field == ALARM_FIELD) {
      if (ALARM_TIME >= 59) //MAX 1h
      {
      ALARM_TIME=0;
      }
      else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
      { // down button
       ALARM_TIME--;
      }
      else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
      { // up button
       ALARM_TIME++;
       }
        }
      else if (selected_field == SET_ALARM_FIELD) {
      if (ACTIVE_ALARM >= 1)
      {
      ACTIVE_ALARM=0;
      }
      else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
      { // down button
       ACTIVE_ALARM--;
      }
      else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
      { // up button
       ACTIVE_ALARM++;
       }
        }

    adjustTime(adjust_value);
    time_changed = true;
  }
}

I would like to reset timer then when wake_hours&minutes and changeable alarm activation time interval = ALARM_TIME*60000 have passed.
      if (ACTIVE_ALARM==1)
  {
    if (wake_HOUR==hour()& wake_MINUTE==minute())
    {
    digitalWrite(ALARM, HIGH);
    new_millis = millis();
    }
    else if (currenTime -new_millis <= interval)
    {
    new_millis = millis();
    digitalWrite(ALARM, HIGH);
    }
    else if (currenTime -new_millis >= interval)
    {
    new_millis = 0;
    digitalWrite(ALARM, LOW);
    }}
  else if (ACTIVE_ALARM==0)
  {
    new_millis = 0;
    digitalWrite(ALARM, LOW);
  }

Any ideas what kind a timer/delay i could use to make my code work?

Did you try with && instead of &? The meanings are very very different.

You have an awful lot of code in there that has nothing to do with what you're asking...

Its all okey with wake_HOUR==hour()& wake_MINUTE==minute() part. Because in next line i declare that if the interval havent reached then output still is ON

Then i will change my question - Is there any proper way how to make timer that will work in my situation?

@IgnacioVazquez-Abrams, in the case of boolean predicates (like wake_HOUR==hour() and wake_MINUTE==minute() it's the same... :)  ... [both & and && have lower precedence than == which allows rookie mistake to turn out ok]

Trying to run a watch off the WDT oscillator is just silly. Even after calibration, it will be too inaccurate to be anything but a toy.

So i fixed my problem. I didnt use timer what i wanted in the beginning but as the code it self's running clock i used current clock as to activate output and then based on clock to turn off output.
Not always the hardest way is better.
Basically this is what i needed to change:
if (ACTIVE_ALARM==1)
{
if (start_wake_HOUR==hour()&& start_wake_MINUTE==minute())
{
digitalWrite(ALARM, HIGH);
}
if (end_wake_HOUR==hour()&& end_wake_MINUTE==minute())
{
digitalWrite(ALARM, LOW);
}
}
else if (ACTIVE_ALARM==0)
{
digitalWrite(ALARM, LOW);
}

As noted in the comment of IgnacioVazquez-Abrams, in the instances at hand you should be using the && (logical AND) relational operator, rather than the & (bitwise AND) arithmetic operator.
That aside, you should separate things out so that instead of an ungainly if - else series you have some independent cases.  For example:
if (wake_HOUR==hour() && wake_MINUTE==minute()) {
   digitalWrite(ALARM, HIGH);
   alarmMillis = millis();
}
if (millis()-alarmMillis > interval) {
   digitalWrite(ALARM, LOW);
}

This will do the job, as follows:
• During the match-minute, ALARM will be driven high over and over, and new_millis will update to the current millis() value over and over.  Which is OK.
• After the match-minute but before the end of the timed interval, ALARM will remain high and new_millis will remain fixed with the time of the end of the match-minute.  OK, that's as desired.
• After the end of the timed interval, ie, when millis()-new_millis > interval, ALARM will be driven low over and over.  Which is OK.
Note, I don't see a declaration of currenTime or anywhere it is updated.  Hence, it does not represent current time and should not be used as such.
Note, interval should be declared as something like a const unsigned long int, with a value that is a minute shorter than the total length of interval that you want.  (new_millis represents the end of the first minute of the interval.)
Note, new_millis should not be zeroed at the end of the interval.  If the original code were magically made to mostly work, because of  new_millis being zeroed it still would have a bug.  During the first few minutes after each millis() overflow, a false alarm would sound.  millis() overflows are about 49.71 days apart.


text:
How to display an entire incoming string from the serial monitor in arduino ide?
this is my first question in this forum.
I need to receive a string from the Arduino serial monitor and display it when the communication is over. I have a similar problem like the one discussed in this thread:
https://electronics.stackexchange.com/questions/45543/how-do-i-receive-an-entire-string-as-opposed-to-1-character-at-a-time-on-the-ard
Only I'm using the Arduino serial monitor instead of a RaspberryPi to send strings so I can't program the sender to attach an identifier like '\n' at the end of the string.
char inData[20];
char inChar=-1;
byte index = 0;

while (Serial.available() > 0){
  ending[1]=ending[1]+1;
  if(index < 19){

      inChar = Serial.read();
      inData[index] = inChar;
      index++;
      inData[index] = '\0';
      Serial.flush();
  }
  Serial.print(inData);Serial.print("\t");Serial.println();
}

What I receive in the console looks like this:
M
Me
Mes
Mess
Messa
Messag
Message

I need to display only the final string
Message

The code has to know when the incoming string ended and then display it once.
I'd really appreciate any help I can get.

You have two options. The most reliable is to decide that a particular character will serve as an end-of-message indicator. \n is a common choice, but you can choose whatever you are not going to use in the message itself. The other option is to have a timeout: if no further characters have been received for XXX ms, then assume the message is complete.

If you really want a string. Try using Serial.readString(). It will return the full string.
The code could look like this:
if(Serial.available()  > 0)
{
  String message = Serial.readString();
  Serial.println(message);
}

It is worth noting that Stream::readString() works with a timeout, which is 1 second by default, but can be changed with setTimeout().

Thank you, that's exactly what I needed. Now the output in the serial monitor is the entire text input. First post, first issue solved. I'm really grateful.


text:
Correct use of interrupt vs monitoring switch
Background:
I have a uni assignment which requires an autonomous robot to do a number of tasks and then finish in a set spot after being triggered to start by an outside physical interaction. I've set up a light limit switch to detect this interaction.
My approach would normaly be to look for the switch in the loop to go high and then run through my code and put a really long delay at the end.
e.g.
switchState = digitalRead(switch);
 if (switchState == HIGH){
 //do my routine which is a function defined outside of the loop
}

Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

To not need the large delay at the end you could just store the previous state of the button and only run your code when the current state is HIGH, and the previous state was LOW. That was your code only runs once per button press. I think this is what you meant, right?

No, an interrupt here would be pointless.
You use an interrupt to detect a change on an input whilst you are doing something else. It's a good way of getting instant (or near instant) notification of something happening.
If you're using the input to start something going when there's nothing happening then you gain nothing other than extra complexity by using an interrupt. You're not doing anything else, and you don't need an instant response, so just polling the input is the simplest option.

Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

it depends critically on your definition of "go high", ie. if you are looking for a transition to high, or if you are looking for the switch to be high. edge triggererd vs. level triggered.
As is, your existing (level-triggered) logic can be easily implemented via an interrupt, as will an edge triggered logic.
interrupt-driven code is generally more efficient for slow / infrequent inputs: it doesn't waste the cpu's processing power. But it does add a level a complexity that can be difficult to handle for beginners.
As for me, I think it is (practically) impossible to code without the use of interrupts.


text:
If Else Alternative
I've written a function that heavily relies on the If / Else statement but I feel it's a very beginner way to achieve functionality. Are there any better ways to achieve the same functionality?
Code:
void jumpThree() // Update from left then right
{
  if (effectCounter[0] < tiles) // Right, first tile
  {
    Serial << flag[6] << "\t";
    Serial << newRed[0] << " " << newGreen[0] << " " << newBlue[0] << "\t";

    if (flag[6] == 1)
    {
      oldRed[0]   = (tileBuffer[effectCounter[0]] & 0xff0000) >> 16;
      oldGreen[0] = (tileBuffer[effectCounter[0]] & 0x00ff00) >> 8;
      oldBlue[0]  = (tileBuffer[effectCounter[0]] & 0x0000ff);

      Serial << effectCounter[0] << "\t";
    }

    else if (flag[6] == 0)
    {
      oldRed[0]   = (tileBuffer[6 - effectCounter[0]] & 0xff0000) >> 16;
      oldGreen[0] = (tileBuffer[6 - effectCounter[0]] & 0x00ff00) >> 8;
      oldBlue[0]  = (tileBuffer[6 - effectCounter[0]] & 0x0000ff);

      Serial << (6 - effectCounter[0]) << "\t";
    }

    Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

    if ((newRed[0] - oldRed[0] != 0) || (newGreen[0] - oldGreen[0] != 0) || (newBlue[0] - oldBlue[0] != 0))
    {
      // Red difference
      if (newRed[0] - oldRed[0] > 0) // Positive red change
      {
        oldRed[0] ++;
      }
      else if (newRed[0] - oldRed[0] < 0) // Negative red change
      {
        oldRed[0] --;
      }

      // Green difference
      if (newGreen[0] - oldGreen[0] > 0) // Positive green change
      {
        oldGreen[0] ++;
      }
      else if (newGreen[0] - oldGreen[0] < 0) // Negative green change
      {
        oldGreen[0] --;
      }

      // Blue difference
      if (newBlue[0] - oldBlue[0] > 0) // Positive blue change
      {
        oldBlue[0] ++;
      }
      else if (newBlue[0] - oldBlue[0] < 0) // Negative blue change
      {
        oldBlue[0] --;
      }

      if (flag[6] == 1)
      {
        tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
      }

      else if (flag[6] == 0)
      {
        tileBuffer[6 - effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
      }

      // tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
    }

    else if (((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0))
    {
      effectCounter[0] ++;  // Go to next tile
      //flag[1] = false;
    }
  }

  else
  {
    flag[1] = false;
    effectCounter[0] = 0;

    if (flag[6] == 1) // Flip flop between left and right updates
    {
      flag[6] = 0;
    }

    else if (flag[6] == 0)
    {
      flag[6] = 1;
    }
  }
  delay(wait);
}

Hopefully oldX and newX are signed, otherwise you will never get into if(newRed[0] - oldRed[0] < 0) as it is always false if one of both is unsigned.

They're not signed but it does work correctly, any idea why?

This question might belong over at [codereview.se].

If-else is just fine. However, the function might become more readable if you split the code into multiple separate functions.

For part of this you can use the switch case style
Which looks like
switch(flag[6]) {
    case 0  //your code here
             break;       // and exits the switch
    case 1 : cout << '2';
             break;
    default: //all other cases
}

There is also the ? syntax that can help

condition ? result_if_true : result_if_false

If I "refactor" this type of code (really we all get there from time to time) I try to go back to "what I want". From What I understand your code would look like (no code validation this is a educational example)
int bufferoffset=0;
int bufferMultiplyer=1;

if(flag[6] == 0)
{
   bufferoffset=6;
   bufferMultiplyer=-1;
}
oldRed[0]   = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0xff0000) >> 16;
oldGreen[0] = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x00ff00) >> 8;
oldBlue[0]  = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x0000ff);

Serial << (bufferoffset+bufferMultiplyer*effectCounter[0]) << "\t";

Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

int redDiff=newRed[0] - oldRed[0];
int greenDiff=newGreen[0] - oldGreen[0] ;
int blueDiff=newBlue[0] - oldBlue[0] ;
if(redDiff!= 0)
{
  redDiff > 0?         oldRed[0] ++:   oldRed[0] --;
 }
if(greenDiff!= 0)
{
  greenDiff> 0?         oldGreen[0] ++:   oldGreen[0] --;
 }
if(blueDiff!= 0)
{
  blueDiff> 0?         oldBlue[0] ++:   oldBlue[0] --;
 }

    tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
}

for more details on switch case see http://en.cppreference.com/w/cpp/language/switch
for more detail on ? syntax https://stackoverflow.com/questions/795286/what-does-do-in-c

if(greenDiff!= 0) == if(greenDiff)

I personally don't like if(greendiff) because greendiff is not a boolean. I consider that style.

No, if-else is really the simplest way of dealing with that.
If you wanted to abstract it a little since you have repeated code just with separate variables, you could make a little function
// Note: set the right parameter variable types here
// to match your unspecified variables.
static inline int testUpDown(int a, int b) {
    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
}

// Inside your flag tests:
oldRed[0] = testUpDown(newRed[0], oldRed[0]);
oldGreen[0] = testUpDown(newGreen[0], oldGreen[0]);
oldBlue[0] = testUpDown(newBlue[0], oldBlue[0]);

If you wanted an inline conditional variant you could do it with this:
oldRed[0] = ((newRed[0]-oldRed[0]) ? ((newRed[0]-oldRed[0])/abs(newRed[0]-oldRed[0])) : 0);

But who can understand that?  You could always macro it:
#define UPDOWN(A,B) (((A)-(B)) ? (((A)-(B)) / abs((A)-(B))) : 0

oldRed[0] = UPDOWN(newRed[0], oldRed[0]);

//when there are multiple if/if-else/nested if/nested if condition then obviously it creates complexity in the code. I think switch is best option to use in such conditions. plz check switch condition if it is feasible in your program. Moreover i will check it in detail if it still not works. Try.........

@Matt please elaborate the objective of your code?

you can shorten a lot of the vertical space with more compact conditionals, including ternaries to remove double conditionals where one result must follow from another.
For example, you can turn this:
  // Green difference
  if(newGreen[0] - oldGreen[0] > 0)  // Positive green change
  {
    oldGreen[0] ++;
  }
  else if(newGreen[0] - oldGreen[0] < 0) // Negative green change
  {
    oldGreen[0] --;
  }

into just this:
// Green difference
int gDiff = newGreen[0] - oldGreen[0];
if(gDiff) oldGreen[0]+= (gDiff > 0) ?  1 : -1;

authors: 05.พัทธวัฒน์ พลเพชร