text:
Why is the SPI response mis-ordered?
I have a Raspberry Pi and an Arduino Micro. The two are connected by a SPI bus, the RPi is the master; the Arduino the slave.
I need to send 5 bytes to the Arduino and get 5 bytes as an answer.
The answer is pre-calculated so when the Arduino receives the first byte, it already knows what to answer.
I don't understand why the response I get is mis-ordered. I get the right bytes (value), but they seem shifted in time.
Arduino code:
// Data received
volatile unsigned char rx_buffer[5];

// Data to be sent
volatile unsigned char tx_buffer[5];

// Triggered to true by the interruption when message is complete
volatile bool message_ready(false);

// Useful to keep trace of where we are in the message
unsigned char bytes_received = 0;

// SPI interrupt routine
// Message consists of 5 bytes: never less, never more
ISR (SPI_STC_vect)
{
  SPDR = tx_buffer[bytes_received];
  rx_buffer[bytes_received] = SPDR;

  if (++bytes_received == 5) // Reached the end of the buffer
  {
    bytes_received = 0;
    message_ready = true;
  }
}

void setup (void)
{
  pinMode(MISO, OUTPUT); // Set Slave Output as output
  SPCR |= _BV(SPE); // Slave mode
  SPCR |= _BV(SPIE); // Turn on interrupts

  // Reponse to be sent
  tx_buffer[0] = 'a';
  tx_buffer[1] = 'b';
  tx_buffer[2] = 'c';
  tx_buffer[3] = 'd';
  tx_buffer[4] = 'e';
}

void loop (void)
{
  // When message is ready, print it on serial port
  if (message_ready)
  {
    message_ready = false;
    Serial.print((char) rx_buffer[0]);
    Serial.print((char) rx_buffer[1]);
    Serial.print((char) rx_buffer[2]);
    Serial.print((char) rx_buffer[3]);
    Serial.println((char) rx_buffer[4]);
  }
}

The RPi uses a C++ program and WiringPi 2.39 to communicate (I also made a similar program with Unix spidev/ioctl calls, same results)
#include <iostream>
#include <thread>
#include <chrono>

#include <wiringPi.h>
#include <wiringPiSPI.h>

using std::cout;
using std::cerr;
using std::endl;

int main(void)
{
  // Initialize wiringPi
  if (!wiringPiSPISetup(0, 150000))
  {
    cerr << "Could not initialize SPI!" << endl;
    return 1;
  }

  // Create message and response arrays
  uint8_t message[5], response[5];
  message[0] = 'z';
  message[1] = 'u';
  message[2] = 't';
  message[3] = ' ';
  message[4] = '!';

  std::chrono::steady_clock::time_point begin, end;
  unsigned count(0);
  while (1)
  {
    // Change the number at the end of the message: "zut 0", "zut 1" etc..
    message[4] = *std::to_string(count++).c_str();
    if (count == 10)
      count = 0;

    // Copy the message into response because reponse is going to be overwritten
    for (unsigned i(0); i < 5; ++i)
      response[i] = message[i];

    // Count time and transfer the message (and get the reponse at the same time)
    begin = std::chrono::steady_clock::now();
    if (!wiringPiSPIDataRW (0, response, 5))
      cerr << "Could not send message!" << endl;
    end = std::chrono::steady_clock::now();

    // Inform user
    cout << "Sent: " << message << endl;
    cout << "Received: " << response << endl;
    cout << "Duration: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << " microseconds" << endl;

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  }

  return 0;
}

The outputs are the following,
Arduino (read over serial):
zut 0
zut 1
zut 2
zut 3
zut 4
zut 5
zut 6
zut 7
zut 8
zut 9
zut 0
zut 1
zut 2
zut 3

Everything looks good on the Arduino receive side!
RPi output (std::cout/cerr):
Sent: zut 0
Received: eabcd
Duration: 374 microseconds

Sent: zut 1
Received: eabcd
Duration: 359 microseconds

Sent: zut 2
Received: eabcd
Duration: 357 microseconds

Sent: zut 3
Received: eabcd
Duration: 384 microseconds

Sent: zut 4
Received: eabcd
Duration: 389 microseconds

Sent: zut 5
Received: eabcd
Duration: 384 microseconds

Sent: zut 6
Received: eabcd
Duration: 386 microseconds

Sent: zut 7
Received: eabcd
Duration: 391 microseconds

Sent: zut 8
Received: eabcd
Duration: 385 microseconds

Sent: zut 9
Received: eabcd
Duration: 387 microseconds

Sent: zut 0
Received: eabcd
Duration: 387 microseconds

Sent: zut 1
Received: eabcd
Duration: 387 microseconds

Sent: zut 2
Received: eabcd
Duration: 390 microseconds

Sent: zut 3
Received: eabcd
Duration: 386 microseconds

I get the bytes eabcd but I expected abcde.
Why isn't the RPi receiving the bytes in the correct order? Don't hesitate to ask for additional information.

Have you tried to send two different strings? It might show you why it's "shifted". Anyway to not be shifted, you'll have to fill the data register in slave device BEFORE master even starts the transfer.

Did you try changing the order of writing and reading the SPI register (SPDR) in the ISR?

Switching the write/read order (before/afer) in the SPDR does not change the behavior. @KIIV you are right, this solved my problem, I'm going to write the answer now!

@RobertoLoGiacco I can't until 13 hours, thanks for the reminder!

@KIIV gave me the answer:

Anyway to not be shifted, you'll have to fill the data register in slave device BEFORE master even starts the transfer.

What happens is that when an SPI transfer is complete, we enter the ISR (SPI_STC_vect), this means that 1 byte (8 bits) has been received. This also means that the response has been sent, because SPI is full duplex!
So the SPDR must be filled with the next byte to be sent before entering the ISR. If you modify the SPDR inside the ISR, this will set the next byte to be sent; it will not be sent until a byte is received.

Fixed Arduino code
// Data received
volatile unsigned char rx_buffer[5];

// Data to be sent
volatile unsigned char tx_buffer[5];

// Triggered to true by the interruption when message is complete
volatile bool message_ready(false);

// Useful to keep trace of where we are in the message
unsigned char bytes_received = 0;

// SPI interrupt routine
// Message consists of 5 bytes: never less, never more
ISR (SPI_STC_vect)
{
  // Store incoming byte
  rx_buffer[bytes_received] = SPDR;

  if (++bytes_received == 5) // Reached the end of the message/buffer
  {
    bytes_received = 0;
    message_ready = true;

    // Let's send another message next time!
    changeTxMessage();
  }

  // When next byte is received, this will be the response
  SPDR = tx_buffer[bytes_received];
}

// This changes the response message sent by the Arduino to the RPi
unsigned count(0);
void changeTxMessage()
{
  // Update message
  switch (count++)
  {
    case 0:
      tx_buffer[0] = 'c';
      tx_buffer[1] = 'r';
      tx_buffer[2] = 'a';
      tx_buffer[3] = 'z';
      tx_buffer[4] = 'y';
      break;
    case 1:
      tx_buffer[0] = 'k';
      tx_buffer[1] = 'a';
      tx_buffer[2] = 'n';
      tx_buffer[3] = 'j';
      tx_buffer[4] = 'i';
      break;
    case 2:
      tx_buffer[0] = 'b';
      tx_buffer[1] = 'u';
      tx_buffer[2] = 'x';
      tx_buffer[3] = 'o';
      tx_buffer[4] = 'm';
      break;
  }

  if (count > 2)
    count = 0;
}

void setup (void)
{
  pinMode(MISO, OUTPUT); // Set Slave Output as output
  SPCR |= _BV(SPE); // Slave mode
  SPCR |= _BV(SPIE); // Turn on interrupts

  // Reponse to be sent
  tx_buffer[0] = 'a';
  tx_buffer[1] = 'b';
  tx_buffer[2] = 'c';
  tx_buffer[3] = 'd';
  tx_buffer[4] = 'e';

  // Prepare first byte to be sent as a response
  SPDR = tx_buffer[0];
}

void loop (void)
{
  // When message is ready, print it on serial port
  if (message_ready)
  {
    message_ready = false;
    Serial.print((char) rx_buffer[0]);
    Serial.print((char) rx_buffer[1]);
    Serial.print((char) rx_buffer[2]);
    Serial.print((char) rx_buffer[3]);
    Serial.println((char) rx_buffer[4]);
  }
}

Changes done:

On setup(), SPDR is filled with the first response byte
Added a new function void changeTxMessage() that changes the response message sent by the Arduino for demo purposes.

Arduino output:
zut 0
zut 1
zut 2
zut 3
zut 4
zut 5

RPi output:
Sent: zut 0
Received: abcde
Duration: 241 microseconds
Sent: zut 1
Received: crazy
Duration: 231 microseconds
Sent: zut 2
Received: kanji
Duration: 232 microseconds
Sent: zut 3
Received: buxom
Duration: 249 microseconds
Sent: zut 4
Received: crazy
Duration: 254 microseconds
Sent: zut 5
Received: kanji
Duration: 254 microseconds

Everything looks good!

Further thoughts
One thing I don't understand with the old code: why did I receive eabcd the first time I get an answer, the first byte should be random because I did not set the SPDR?! Maybe it's kept in memory during Arduino upload.

Performance
I cannot achieve high bit rates with this code. 250 000 Hz is the maximum I can reach (wiringPiSPISetup(0, 250000)) before getting problems in the communication. Example at 0.5 Mhz:
Arduino log:
zut 0
zut 1
zut 2
zut 3
zut 4
zut 5
zut 6
zut 7

RPi log:
Sent: zut 0
Received: bzut
Duration: 143 microseconds
Sent: zut 1
Received: czut
Duration: 136 microseconds
Sent: zut 2
Received: kzut
Duration: 135 microseconds

I expected to reach at least 2 Mhz, I think I'll open a new question for that.

To reach 2 MHz on Arduino Micro you will have to replace the ISR with a tight communications loop. The ISR overhead is just too large on a 16 MHz MCU. You might even have to turn off interrupts (Timer) to achieve reliable communication.

authors: Андрей Лазаренко


text:
More speed from ATMEGA328 Internal Clock
I have a board that is designed and produced. It was designed to use an Atmega328 with the internal clock. There is no space on the board to place an external clock. After completing these and testing them I have found that 8Mhz is too slow to complete my main loop actions seamlessly. The main loop involved shifting data out to 20 registers. Is there any way to speed this up without going back to the drawing board on the PCB design? Can another AVR be substituted as a drop in replacement with a faster internal clock? Can the internal clock be made to run faster or doubled to achieve 16Mhz?
The application is a matrix display that has 50 columns and 7 rows. The registers are the display buffers and represent the current state of the display. Because of the multiplexing in the matrix, only 1/5 of the pixels are illuminated at any given time. In order to trick the eyes into seeing all lit at the same time the speed needs to be faster. The display flickers with the interal clock. If I connect and UNO board instead of using the on board ATMEGA328 (QFP) it works good. So the difference between 8Mhz and 16Mhz is visible. If I can double the speed of the display loop than that is a solution. Below is the loop, for reference, latchPin = 8, clockPin = 12, dataPin = 11.

You have to optimize your code, you may can do the shifting out using hardware SPI. Show your code and describe your application.

What is this function shiftOut it uses GPIO pins?

OK then from the reference "This is a software implementation; see also the SPI library, which provides a hardware implementation that is faster but works only on specific pins". This is what you need.

Ideally improve the efficiency, but you could consider glueing an oscillator on top of the ATmega or somewhere on the PCB to improve your prototype, and then doing a re-spin of the board design when you need a quantity where such re-work is impractical.  Note that there are a lot of ARM MCUs that cost less than an ATmega and can run faster with internal clocks, though they are not through-hole.

@TannerEwing Yes, it does not.

shiftOut() relies on digitalWrite(), which is dead slow by AVR
standards. You could probably get a factor 5, or even 10, by
reimplementing shiftOut() using direct port
access instead.
Using SPI (as suggested in the comments) would be even faster, but you
would need to clock out of pin 13.
Edit: here is an attempt at such implementation. Note that it is
completely untested. Note also the small delay meant to avoid the thing
being too fast. You may try to play with the delay value.
#include <util/delay.h>

/*
 * Especialized and faster shiftOut().
 * This assumes no one is touching PORTB at the same time.
 *
 * dataPin = 11 (PB3), clockPin = 12 (PB4), bitOrder = MSBFIRST.
 */
void myShiftOut(uint8_t val)
{
    for (uint8_t i = 0; i < 8; i++)  {
        // Send data bit.
        if (val & 0x80)
            PORTB |= _BV(PB3);
        else
            PORTB &= ~_BV(PB3);
        val <<= 1;

        // Toggle clock twice.
        PORTB |= _BV(PB4);
        _delay_us(0.5);
        PORTB &= ~_BV(PB4);
    }
}

When the SPI bus is not possible, then this is the way to do it. Arduino has bitSet() and bitClear macros which result into the same I/O bit instructions. The 'val' should shift the 0x80 to the right. It is not possible to delay "0.5" only unsigned long numbers, and delayMicroseconds() could be used, or the delay by clock cycles (I forgot the name).

@Jot: You wrote: “The 'val' should shift the 0x80 to the right”. Shifting 0x80 to the right works also, although it produces slightly less efficient code, as it requires an extra register to hold the bit mask. Shifting val to the left, with the fixed mask 0x80, allows the compiler to use a bit-test instruction (sbrs) and never store the bit mask. “It is not possible to delay ‘0.5’ only unsigned long numbers”. This is incorrect. Delaying by 0.5 µs (or even 0.125 µs, given an 8 MHz clock) works perfectly well with _delay_us() (not with delayMicroseconds()). Try it!

I'm very sorry, I made two mistakes. You are right. I have tested it in software and _delay_us(0.5) results in a delay of 0.506 µs (according to a software approximation. Thank you. I learned something new.

I wrote the following earlier but the moderator deleted:
"
A few things to try.
An external oscillator.
An external rc oscillator.
Optimized code: the code left a lot to be desired.
Optimized hardware: there is no reason you shift out the same value so many times. That's a waste of time.
"
edit: just give you some sense on a 16MIPS ATmega:
1) your code executed in 2.54ms -> a refresh rate of 400Hz;
2) your code software-optimized can be executed in 0.103ms -> a refresh rate of 1Khz;
3) your code both software and hardware optimized can be executed in 0.054ms -> a refresh rate of 2Khz.
what it tells you is that:
1) raising the clock isn't the only way to speed up execution;
2) there is a fundamental limit for this topology on how many shift registers you can drive before it starts to flicker;
3) to drive the most out of your design, you have to pay attention to both software and hardware. that's why embedded engineers get paid a lot of money to do;
BTW, the higher clock rate, the more likely you will run into timing issues in a long chain of shift registers. 20 - 25 shift registers are likely the limit in real life applications.

It is 8MHz and not faster.
The only way to make it faster is to add an external crystal with two capacitors and change a fuse for external clock.
Many ATtiny chips can run at higher frequencies with the internal clock. Do you use a DIP package of the ATmega328(p) ?
Did you optimize the code ? The ATmega328(p) has highly optimized code to change an output pin. At what rate do you want to shift out data ?

Double the execution time is easy. A digitalWrite() takes about 5µs and a optimized I/O instruction is 0.125µs, that is 40 times faster.

This is the slow Arduino shiftOut code: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_shift.c

source: Stack Exchange

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

authors: Павел Труфанов

sort: votes


text:
ESP8266 send number in IP address
I want to easily send a number from a phone to my esp8266.
I have an app that sends the number in the format IP/number.
How can I modify the code to give my the number behind the IP address as an integer?
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

MDNSResponder mdns;

// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

ESP8266WebServer server(80);

String webPage = "";

void setup(void){

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (mdns.begin("esp8266", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }

  server.on("/", [](){
    Serial.println("device connected");
  });
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

So it would do something like this for and should be looking through every i between 0 and 200. :
server.on("/"+String(i), [](){
    Serial.println("i");
  });

First of all use the event function server.on with a path that corresponds to your function and use a url like this:
192.0.2.2/recordnumber?num=100

With a url parmeter for your number. Your code might look like this:
At the top:
int nums_size = 0;
const int nums_max = 128;
int nums[nums_max];

In setup:
server.on("/recordnumber", [](){
    int num;
    if(server.hasArg("num")) {
      String num_str = server.arg("num");
      if(num_str.charAt(0) == '0') {
        num = 0;
      } else {
        num = num_str.toInt();
        if(num == 0) {
          server.send(400, "text/plain", "not a number");
          return;
        }
      }
      if(nums_size < nums_max) {
        nums[nums_size++] = num;
        server.send(200, "text/plain", "saved");
      } else {
        server.send(500, "text/plain", "full");
      }
    } else {
      server.send(400, "text/plain", "bad params");
    }
});

First you need to extract the string that contains the number (after the /). Since it is already stored in consecutive memory you can pass the pointer to the character after the / symbol to the C function atoi to convert it to an integer.
I assume the pointer is already \0 terminated.
You can use the C function strchr to search for the / symbol.
Tip: use a C compiler on a desktop/PC to check how these functions work. Once you know how to use them, copy them in your Arduino code. This is much faster than uploading/debugging sketches probably.

My phone accesses the ESP via it's IP address for instance: 192.168.2.2/100 or 192.168.2.2/200. The ESP should than store these values 100 and 200 into integers but these numbers could be any number

I adapted the answer, use strchr to search for the / symbol, than use atoi

But in order to extract the right part of the string how do you store the whole  incoming IP address in a string?

WiFi.localIP() is already pointing to a string, you can use this as input for strchr to search for the /  symbol, than you can use atoi.

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


text:
Dynamically switching pin out
I have a connector with 10 pins, and a bus which uses 2 of the 10 pins.
What I need to do is, in software, attach my arduino to 2 of the 10 pins. I cannot wire it directly as the 2 pins required may be in a different position in different environments.
What are my options?
EDIT: Just some background. I have to connect to an OBD II port of a vehicle and cannot to the CAN bus. On some vehicles is may not be on the standard pins in the OBD connector, so I would like to be able to programatically switch the pins being used, in software.

Could you connect all 10 pins to the Arduino and select which of them to use in the Arduino software?

No, mainly due to the bus requirements - think SPI, only works on certain Arduino pins.

If there are other requirements not stated, it would be useful to edit them into the question. I can think of a few ways of doing this. Whether any of them will be suitable depends on what you're trying to do.

Fair point. I tried to be as generic as possible to keep it simple, but I have added background in case it helps.

Probably you need two SP10T switches, where you can programmatically decide which of the SPI pins will be sent to which of the 10 outputs which are connected to the 10 pin bus.


text:
How would one send radio signals from Arduino at a non-standard frequency
TL;DR: How would one send a fixed radio signal at 447,54MHz with Arduino?
Background: I recently purchased a (receive only) SDR and recorded my garage door fob. I found it sends a fixed signal at the frequency 447,54MHz, which I was able to decode. Now I want to try activating the garage door via Arduino. The standard 433MHz senders obviously don't work, since they have a totally different frequency.
I tried searching for senders of my frequency (447MHz) and also for senders with different or variable frequencies. I didn't really find much. Also I read in some post (that I don't remember currently), that building an own sender circuit is not easy (since the exact PCB design plays a big role in the behavior in the ciruit). It didn't seem, that this would be a valid way for me.
Has someone here experience with such frequencies? While I know, that this site doesn't do product recommendations, maybe I just searched for the wrong term and you can help me with that. Or maybe there are no (or very very few) "maker-ready" products for this out there currently. Maybe the creator of the garage door system wanted a non-standard frequency for security-through-obscurity (since that doesn't protect against attackers with a sending SDR).
Also I researched about frequency bands. Normally I would think of a garage door fob as a Short Range Device (SRD), but instead my frequency is right above (and outside) of the band PMR. Maybe this is because the system is really old (can easily be between 15 and 30 years).
I'm kinda lost on how to proceed here, or if proceeding is even viable here.

you have to find a 447,54 MHz transmitter that has a digital input pin ... your question is not about Arduino, so you are limiting your success by posting here

Did you try tuning the standard 433 MHz receiver, adjusting the coil parameters for your secret frequency and don't share your frequency someone can jam your signal or listen to incoming data!

@Avon97 Is it possible to detune a standard 433MHz sender with different coils to a frequency so far away from 433MHz? The sender modules that I have don't even have  a coil on them, though I know, that many others that you can buy have (a fixed) one. I shared the frequency, because it is integral to the question. And its really security through obscurity. If someone would really want to jam my signal, he could just record your fobs signal with an SDR (for example, when we go out for work) to get the frequency. Just as I did.

447 MHz is not realy a problem to build. The little chinese 433 MHz T/R module  pairs prove that. ;-) But there are legal issues you could run into outside of a public band. Here is an example: https://www.cdt21.com/wp/wp-content/uploads/support/download/docs/DS_STD-302Z-447.pdf Search for PLL Synthesizer (Modules|Chips) for 447 MHz to find more.

Try to receive a 433 MHz device (a car key or something) on your SDR just to double check your setup.

@Wirewrap I have already done that. The 433MHz signal of my 433MHz sender modules are received exactly as expected. So I don't have any reason to not believe my frequency measurement of the fob signal

The standard 433MHz senders obviously don't work, since they have a totally different frequency.

I think "433 MHz" is used as a band name, with 433 MHz actually being at the lower limit of a band that covers approximately 40 MHz. Your garage door opener will likely be referred to as a "433 MHz garage door opener", even though it operates at 447.54 MHz.
For your experiments, you might try the HC-12 module. It's billed as a 433 MHz radio, but in fact it covers 433 MHz to 473 MHz in 100 bands with 400 kHz spacing, so it will cover your desired 447.54 MHz. The link above has some Arduino code examples that might help get you started. And of course there is much more information on this topic if you're interested.

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


text:
Arduino GSM receiving text and then storing value as a variable in code
I am using an Arduino Mega board with a SIM900 GSM.
My goal is to be able to text the GSM with a value of two digits (ex: 79) and then store that value as a variable in the code. I know how to set up the Mega and the GSM in terms of wiring and initialization of ports, but how would I write a short function to test the incoming values and save them to a variable?
I thought about testing each bit individually, storing each one as a separate variable, and then adding them for the total. For example, if the GSM received "#79" as a text I stored the value 7 as an integer variable named One and the value 9 as an integer variable named Two. Then I did
Total = (One*10)+Two.

I am posting my code below that used this method, although it has not proved to be useful. If anyone has any suggestions I would greatly appreciate it.
#include <SoftwareSerial.h>   //GSM Library

int Max_temp;
float threshold;

SoftwareSerial SIM900(18, 19);
String destinationNumber = "+17186578989";
String outMessage1 = "Please enter the maximum desired room temp";
char inchar; // Will hold the incoming character from the GSM shield when user texts it
int M_one;
int M_zero;
void GSM_SEND_MAX();
void GSM_RECEIVE_MAX();

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

//GSM setup:
  Serial1.begin(19200);  // wake up the GSM shield
  delay(20000); // give time to log on to network.
  Serial1.print("AT+CMGF=1\r"); // set SMS mode to text
  delay(100);
  Serial1.print("AT+CNMI=2,2,0,0,0\r"); // blurt out contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
}// end void set up()

void loop()
{
  GSM_SEND_MAX();
  GSM_RECEIVE_MAX();
}// end void loop ()

/////Functions
void GSM_SEND_MAX()
{
  Serial.println("sending text");
  Serial1.begin(19200);
  delay(20000); // give time to log on to network.
  Serial1.print("AT+CMGF=1\r");
  delay(1000);
  Serial1.println("AT + CMGS = \"" + destinationNumber +"\"");
  delay(1000);
  Serial1.print(outMessage1);
  delay(1000);
  Serial1.write((char)26); //ctrl+z
  delay(1000);
  Serial.println("send text");
}//end GSM_SEND_MAX funtion

void GSM_RECEIVE_MAX()
{
  //If a character comes in from the cellular module...
 while (Serial1.peek() != '#' )
   {
    inchar=Serial1.read();
    Serial.print("bad char ");
    Serial.println(inchar);
    delay(500);
   }// end while #1

 inchar=Serial1.peek();
 Serial.println("out of loop 1");
 Serial.println(inchar);

 while (Serial1.available() != 0) //While #2 reads incoming char
 {
    Serial.println("in loop 2");
    inchar=Serial1.read();

if (inchar=='#')
  {
  delay(10);
  Serial.print("got #");
  M_one=Serial1.read();

  if (M_one >= 0 )
  {
  delay(10);
  Serial.println();
  Serial.print("got M_one");
  Serial.print(M_one);
  M_zero=Serial1.read();

      if (M_zero >= 0)
      {
          Serial.println();
          Serial.print("got M_zero");
          Serial.print(M_zero);

       }//end m_zero

  }//end m_one
  Max_temp = (M_one *10) + M_zero;

  Serial.println();
  Serial.print("Max_temp=");
  Serial.print(Max_temp);

  } //end if (inchar==#)

 }// end while #2 loop
}//end GSM_RECEIVE_MAX function

There is a code formatting button in the post editor. Highlight your code and click the {} button.

The code uses a char as int without conversion. See https://electronics.stackexchange.com/questions/38845/arduino-serial-read-to-int for details on how to convert.


text:
Difference in bootloader of ATmega with 16MHz external crystal and 8MHz external crystal
I have used your bootloader for ATmega2560-16AU with 16MHz external crystal and it works like a wonder.
In my new project I have a 3V power supply. Therefore, I am planning to use a low frequency external crystal in order to operate the ATmega at a low frequency so that the voltage will be able to go as low as possible.
However, I have a number of issues/questions:

I uploaded the bootloader using an 8MHz external crystal and it went successfully but I am not able to upload a sketch.
Can I run an ATmega2560-16AU with an 8MHz crystal and will it work at 3V, without any risk?
As I do not have an ATmega2560-8AU right now, I am not able to test this. Will your bootloader work with Atmega2560-8AU and an external 8MHz crystal or, before burning bootloader, do I need to make any changes?

Sorry to ask you such a long query, but I have really spent lots of time looking at this and finally today I made a post everywhere.

We have 2 optionn.

Yes, the ATmega328 will run fine at 8MHz, at 3 volts.
The formulas for clock speed vs. volts are:

Below 1.8V - cannot operate
Below 4 MHz - use at least 1.8V
Between 4 MHz and 10 MHz you require: Volts = 1.8 + ((M - 4) * 0.15)
(Where M is Megahertz)
Between 10 MHz and 20 MHz you require: Volts = 2.7 + ((M - 10) * 0.18)
(Where M is Megahertz)
You can supply an absolute maximum of 5.5V

Plugging 8MHz into this formula: volts = 1.8+((8-4)*0.15) = 2.4 volts minimum (5.5 volts maximum). Note that, as batteries are used, their voltage goes down gradually, so the 0.6 volts difference will mean that your project will run a little longer.
Since your supply is > 2.7V, we can reverse the second formula: 3V=2.7+(M-10)*0.18); 0.3=(M-10)*0.18; 0.66=M-10, so you can run it at 10.66MHz at 3V (but it is likely to stop as soon as the battery starts to drain).
Your second question, I think, is the most relevant one - the bootloader is written for 16MHz, and some things will not work at other speeds - serial communications used for programming for example. The same, for that matter, applies to the program - if you put in a delay() instruction in your code, it will delay() for twice as long as it should.
You can get around the programming side by ditching the bootloader altogether - once your code is ready, select file->upload using programmer. This will still affect the speed your sketch runs at (anything time-related - serial communications, delay(), etc). To change this, you will need to add a custom entry to the boards.txt file. See [HOWTO:] Anatomy of the boards.txt file for custom boards.

Thank for your input.
But here I asked regarding ATMega2560 8au with 8MHZ crystal. For whom who is looking for this:
http://forum.arduino.cc/index.php?topic=51955.new#new I have not tried below on but it should work:
https://www.sparkfun.com/products/10744 Thank.

Today I just change CPU cycle to 8MHZ and baudrate to 56700 and bootloader works for ATMega2560 8AU with 8Mhz crystal. Just we need to change cpu and baudrate. Thanks.

One may be able to overcome the serial baud rate issue just by talking at half the baud rate configured in the bootloader/sketch - that's not fixing it at the source, but can be a pragmatic workaround if the setup to flash the bootloader isn't handy.  Of course, the timing functions will remain off by a factor of approximatley two as well.


text:
ESP needs a reboot after wifi OTA flash
I would like to use OTA in some of my less accessible esp's. I am using the examples/BasicOTA and BasicOTA_test. My esp is a -01 model with 1Mb of flash.
I upload the BasicOTA to my esp through the COM port, then upload the BasicOTA_test over WiFi.  Everything appears to go OK, but the test sketch doesn't run until I press reset on the esp.
If I upload BasicOTA over the com port then upload a simple blink sketch over WiFi without the OTA code, it uploads fine then runs without a reset.  But then, I can't upload over WiFi anymore.
If I have to hit reset every time I upload a new sketch that contains the OTA code, then why bother?
Tips would be appreciated.

Why bother? it's still FAR easier to power cycle an installed device than it is to wire uart to a built-out thing... fwiw, this doesn't seem to happen each time anyway; i suspect it happens most upon the first OTA.

You can add ESP.restart() in the following line to make it restart.
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
ESP.restart();
});

Now you can upload code each time without hitting reset.

the ArduinoOTA library does the reset. but who knows now what was the state of the library in 9/2017

I've done some research and this appears to be a common problem while using OTA to update the ESP8266. In fact, this bug has been reported on their GitHub and it's due to the watchdog timer resetting after the ESP8266 is flashed via OTA.
It appears the problem can be solved by manually resetting (once) after you upload it via serial BEFORE you can upload it via OTA. After that, you shouldn't have any problems.

That is a different issue, that issues is when you have to reset before upload via OTA. OTA not running the new sketch untill after manual reset as described above is another. Did you solve both?

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


text:
Powering LED strips with two power banks and they randomly change different colors when i use the second power bank
So for one of my projects i want to power LED strips with power banks but once i try use the second power bank the LEDs half way through patterns jump to random different colors and then go back to the code im using to make sure they work, I dont think its a code issue as when i plug the power into my MEGA it works fine. I would use the MEGA to power the strips but i need 3 power sources to keep my strips at maximum brightness. would this be a voltage drop issue?
When I connected it to my 3 usb port power bank it works perfectly fine so it might be different currents causing it to jump im not to sure if im correct but its definitely something to do with using another power supply is causing my LEDs to randomly change multiple different colors randomly i just cant see if its a current or voltage issue. Any help would be greatly appreciated.
block diagram link

Greg, we don't know how to answer this. It can be many things. For example the GND level could be lifted by the extra power bank causing the data to turn into noise. This website is about questions and answers. You can update your question, but please remove your answer if it is not an answer.

Schematic or other wiring diagram?

Sorry my last link wasnt working heres a block diagram of what ive wired up so far link

You should embed the image / diagram in your question. Your link is not public.

https://drive.google.com/file/d/1-EDED7WAER_BU6tCumgxvPttGHeGSt7O/view?usp=sharing here is a public link sorry i though i made it public my apologizes the P1,P2,P3,P4 are the power bank ports

you need include the drawing of your circuit in your question, not in a comment.

These are USB power-banks? You need a way to tie the grounds together somehow. Try tying all the ground lines from your LED strips together and also connecting a wire from one of the LED strips to a ground line on your Arduino.
The USB connections should connect ground between the power bank and the device it's connected to, so by tying the grounds on the LED strips together, that should connect the grounds on the power banks as well.

Duncan that was the issue making the power bank and the LEDs their separate common GNDs fixed the random lightning of LEDs thank you so much!!!

Glad I could help. You still need to add your drawing to your question though.


text:
Random number/sequence output
The program I'm trying to build is:

Type in 1st name, hit enter, type in 2nd name and then hit enter again.
Register those names from string input to char naming in student struct.
Print out the names in serial monitor.
Use those names in the main program.

The problem is I got randomize results whenever I typed in the names.
My target output:
Program Starts
Insert 2 students name:

First student: Adam     //When input -> Adam
Second student: Eve     //When input -> Eve
First student: John    //When input -> John
Second student: Amy    //When input -> Amy
//the sequences should repeat

...but what happened is the sequences of the names randomized. For example:
Program Starts
Insert 2 students name:

First student: Adam
First student: Eve
Second student: John
First student: Amy
//the sequences will keep randomizing

Can anyone point out what I've missed out?
The program:
typedef struct
    {
        char naming[20];
    }student;

    student record[]{
      {""},
      {""},
    };

    String readString;
    String str="";

    // the setup routine runs once when you press reset:
    void setup() {
      Serial.begin(9600);    // initialize serial communication at 9600 bits per second
      while (!Serial);              // wait for Serial Monitor to open
      SerialUSB.println("Program Starts \n Insert 2 students name:");  // Title of sketch
    }

    void loop() {
        namedata();
        mainprg();
    }

    void namedata()
    {
    for(uint8_t i = 0; i < sizeof(record)/sizeof(student); i++){
          while (Serial.available()) {
            char c = Serial.read();
            readString += c;
            readString.trim();
          }

          if (readString.length() >0) {
            str = readString;
            str.toCharArray(record[i].naming,20);
            if(i==0){
               Serial.print("First student: ");
            }else if(i==1){
               Serial.print("Second student: ");
            }
            Serial.println(record[i].naming);
          }
            readString="";
        }
    }

    void mainprg()
    {
      //main program using student`s name
    }

Additional infos:
1.Why use struct? Because I've more data to process/store for one "student" in my main program.
2.Currently using Arduino Yun Mini, Arduino 1.8.7
Thanks in advance!

change ++i to i++

@Juraj Nope still the same, though I also tried if(int i; i<2; i++) to no avail...

your algorithm for reading the names is based on misunderstanding how Serial input works

@Juraj I would appreciate it if you can point me to any info on the topic

The problem, that Juraj mentioned, is that you seem to think, that all the data from one name input will arrive as a big chunk, so that the while loop will only exit, when a full name has been read. That is not the case. There might be pauses between arbitrary bytes in the stream, for example introduced from the OS of the PC. The while loop will often exit, before a full name is read. You can use the something like the readline function here: https://majenko.co.uk/blog/reading-serial-arduino

@chrisl Thank you for the link. I (somewhat) understand now how Serial.read works, but I still cannot pause the loop until the second name input and register it into record[i].naming, thus the random sequences caused by random loop exits.

Why do you use SerialUSB in your setup function, but Serial in the rest of the code? I'm not sure, what happens on an Arduino with only one serial interface, when using SerialUSB, but on other boards (as I recall the Due for example) These two are complete different interfaces. Though I don't see, how you can get this randomized order due to this.

@chrisl About the SerialUSB, you are right; its the same thing as Serial.  As for the randomized order, I wonder that myself  ¯_(ツ)_/¯

Even though this is not elegant by any means, for now this is what I've came out with:
typedef struct
{
  char naming[20];
} student;

student record[] {
  {""},
  {""},
};

int a = 0;

char buf[20];

// the setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);    // initialize serial communication at 9600 bits per second
  while (!Serial);              // wait for Serial Monitor to open
  Serial.println("Program Starts \n Insert 2 students name:");  // Title of sketch
}

void loop() {
  if (readline(Serial.read(), buf, 20) > 0) {
    if (a == 0) {
      Serial.print("First student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
      a = 1;
    }
    else if ( a == 1) {
      Serial.print("Second student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
    }

  }
}

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len - 1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

Basically by using int a, the program decides the sequences of the name. Although it will not repeat the sequence after the 2nd input (ie 1st>2nd>1st>2nd), at least the sequence is not randomize anymore.
Btw thanks for the tips @chrisl!


text:
ATmega328p keeps restarting
When I was programming an arduino uno with atmel studio via usb cable, everything worked fine. Now I am trying to upload a code via usbasp programmer, it works, whereas arduino keeps restarting and L labelled pin flashes even when I have not activated it by code. After a bit searching I've found that,I should unprogram watchdog timer by adding this command:
C:\Users\Eldar>avrdude -c usbasp -p m328 -P COM5 -b 19200 -U lfuse:w:0xEF:m -U hfuse:w:0xD9:m
output of that:
 avrdude: warning: cannot set sck period. please check for usbasp firmware update. avrdude: AVR device initialized and ready to accept
    instructions Reading |
    ################################################## | 100% 0.03s avrdude: Device signature = 0x1e950f avrdude: reading input file
    "0xEF" avrdude: writing lfuse (1 bytes): Writing |
    ################################################## | 100% 0.01s avrdude: 1 bytes of lfuse written avrdude: verifying lfuse memory
    against 0xEF: avrdude: load data lfuse data from input file 0xEF:
    avrdude: input file 0xEF contains 1 bytes avrdude: reading on-chip
    lfuse data: Reading |
    ################################################## | 100% 0.01s avrdude: verifying ... avrdude: 1 bytes of lfuse verified avrdude:
    reading input file "0xD9" avrdude: writing hfuse (1 bytes): Writing
    | ################################################## | 100% 0.02s
    avrdude: 1 bytes of hfuse written avrdude: verifying hfuse memory
    against 0xD9: avrdude: load data hfuse data from input file 0xD9:
    avrdude: input file 0xD9 contains 1 bytes avrdude: reading on-chip
    hfuse data: Reading |
    ################################################## | 100% 0.02s avrdude: verifying ... avrdude: 1 bytes of hfuse verified avrdude:
    safemode: Fuses OK avrdude done.  Thank you.

I changed  0xD9 to 0xC9 but it`s still the same.Moreover,when i try to program arduino with usb cable again,avrdude gives this error:
avrdude.exe: stk500_getsync(): not in sync: resp=0x00
avrdude.exe done.  Thank you.

This is my code that I try to upload just for testing
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
    DDRD |= 0B11111111;
    DDRB |= 0B11111111;
    while(1)
    {
    PORTD |= 0B00110000;
    PORTB |= 0B00110000;
    _delay_ms(1000);
     PORTD ^= 0B00000000;
     PORTB ^= 0B00000000;
    }
}

Ive also tried unprogram watchdog timer inside the program itself,its still the same.There are attempts below.
Attempt1
#define F_CPU 16000000UL
    #include <avr/io.h>
    #include <util/delay.h>
    #include <avr/wdt.h>
     int main(void)
    {
    MCUSR = 0;
    wdt_disable( );
     while(1)
     {
        //nothing
     }
     }

Attempt2
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/wdt.h>
 int main(void)
{

    wdt_reset();
     MCUSR=0;
     WDTCSR|=_BV(WDCE) | _BV(WDE);
     WDTCSR=0;
     while(1)
     {
        //nothing
     }
     }

Also,why it does not work when i configure the chip with avrdude directly via command line either?

Could you suggest relevant code for watchdog refresh register once from the main while(1) loop,because Ive tried these(in the below comment),but its still the same


text:
Is there an alternative to strtok_r in extracting words from char?
The task, in char, I get some data that I have to parse into parts.
In this case, I use strtok_r, which finds identifiers like

"=", " ", "&"

Code:
char payload[70] = "GET /wifi?ssid=MyWiFi&pass=123456789 HTTP 11";
char *p;
char *i;

void setup() {
  Serial.begin(15200);
  Serial.println("Load");

  p = strtok_r(payload, "=", &i);
  // Get SSID
  p = strtok_r(NULL, "&", &i);
  Serial.println(p);

  p = strtok_r(NULL, "=", &i);
  // Get PASS
  p = strtok_r(NULL, " ", &i);
  Serial.println(p);
}

void loop() {}

Result:

Load MyWiFi 123456789

This works, but as soon as I add the characters strtok_r works on to the ssid = or pass = value, it stops working, outputting the cropped data.
These characters can be in the name of any WiFi network or the generated password.
Tell me, are there strtok_r analogues, where instead of a single character I can insert a whole phrase?
For example, so that he finds the beginning of ssid by the tag "ssid=", and finishes before "pass=".
Resolved.
Thank you all for your help!
I studied both options from @Majenko and @user7761803. All of them came in handy in various parts of the code.
Perhaps someone will use the Regexp library to parse such data. Here is example:
    #include <Regexp.h>

    char payload[60] = "ssid=MyWifi&pass=ukLPm&I*uwlm HTTP";
    char ssid[25], pass[25];

    void setup() {
      ms.Target(payload);
      char match_result = ms.Match("ssid=(.*)&pass=(.*) H", 0);
      if(match_result == 1) {
       // Get SSID
       ssid = ms.GetCapture(regexp_var.buffer, 0);
       // Get PASS
       pass = ms.GetCapture(regexp_var.buffer, 1);
      }
    }

    void loop() {}

If you're running on an ESP the https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WebServer library has an arg() parser for HTTP GET request strings.

@Dougie, Thank you!

The function you are looking for is strstr(), which takes two strings, and returns a pointer to where the second string appears in the first (or NULL if it doesn't appear).
You could use it something like this:
void setup() {

    Serial.begin(15200);
    Serial.println("Load");

    char *p = strstr(payload, "ssid=");
    char *q = strstr(payload, "pass=");
    char *r = strstr(payload, " HTTP");

    char *ssid = NULL;
    char *pass = NULL;

    if (p == NULL || q == NULL || r == NULL) {
        // One or other (or both) missing - what to do?
    } else {
        *r = '\0';  // Terminate the last string

        // If this really is an HTTP query string, we don't know
        // if ssid or pass will be first
        if (p < q) {    // Terminate the first string
            *(q - 1) = '\0';
        } else {
            *(p - 1) = '\0';
        }

        ssid = p + 5;
        pass = q + 5;

        Serial.println(ssid);
        Serial.println(pass);
    }
}

Note, however, that your payload string looks like an HTTP query string.
These are defined so that they are split at the & characters, and if a & needs to appear in one of the values, it should be percent encoded (where the & would appear as %26, and would need to be decoded afterwards).
However, that wasn't your question...

Thank you for the help!

The normal way of parsing such complex strings in any language is to use Regular Expressions.
Normally these are pretty heavy-weight to use, but thankfully Nick Gammon has written an Arduino implementation of regexp.

Thanks for the help! I figured out this library.


text:
Switch setting 'running' state boolean doesn't hold
I have a rotary encoder and I want to use the switch to stop the rest of my code running, essentially switching off what I have going on.
I have this
boolean running = true;

void setup() {
  pinMode(swPin, INPUT);
  digitalWrite(swPin, HIGH);;
}

void loop() {

  if(digitalRead(swPin) == LOW) {
    running = !running;
  }

  if(running) {
    ...
  }
}

When I enter the if statement catching the switch press running does become false and the rest of the code is stopped. However, once released; running is becoming true again and the rest starts again.
I guess it is because the rotary encoder isn't fixed in the LOW state but I expected the running variable to be set to false and remain since it is declared outside of the loop().
Any guidance would be much appreciated!!

You are constantly toggling it over and over again all the time you are holding the button down. Every iteration of loop() you change the variable to the opposite if you happen to still be holding the button down.

@Manjenko, that makes sense! Thanks :) I have added a switch previous state variable to check and allow the if to only run when I want it. I'll post it up as an answer.

Thanks to @Manjenko's comment I was able to see my error.
Here is my solution:
boolean running = true;
int swReading;
int swPrevious = LOW;

void setup() {
  pinMode(swPin, INPUT);
  digitalWrite(swPin, HIGH);;
}

void loop() {

  swReading = digitalRead(swPin);

  if(swReading == LOW && swPrevious == HIGH) {
    running = !running;
  }
  swPrevious = swReading;

  if(running) {
    ...
  }
}

This is still unlikely to reliably do what you want, due to contact bounce.  To protect against that, add a fraction of a second of time where you ignore the input after deciding it has changed.


text:
Communicating with I2C DAC (LTC2631)
Firstly, let me say that I'm new to using I2C devices, especially with Arduino. I have an 8-bit DAC (LTC2631) that I'm trying to control with an Arduino Uno. I thought I would be able to use the standard Wire library protocol to talk to it, but I'm not getting any response. Here's what I've tried:
#include <Wire.h>

void setup() {

    Wire.begin();
}

void loop() {
    Wire.beginTransmission(0x11); //specify device's address

    Wire.write(150); //send a test value

    Wire.endTransmission();
}

Am I missing something obvious? Or are not all I2C devices compatible with  Wire?

did you check pins with here >

Start with a i2c scanner. This one: https://playground.arduino.cc/Main/I2cScanner or the one on this page: http://www.gammon.com.au/i2c Get the pins and wiring correct so the i2c scanner detects the chip. Only if it is detected by the i2c scanner, then you can try to talk to the chip.

@Jot Thanks! That sketch was really helpful. I was admittedly a bit afraid that I had the address wrong, but it shows up exactly as I had thought. So now I just have to figure out what's wrong with how I'm trying to communicate with it.

When the i2c scanner detects the chip, then the I2C is working. Read the datasheet, you need to send three bytes (not just one). The first byte has the C1,C2,C3,C4 in the highest bits, the other two bytes have the data.

Software:  Wire should be fine.  Of course, you usually will want libraries for each device.  This particular ADC is designed for automotive use and I could not find a specific library for it so you are correct that you will need to speak with it directly.  Here is the DATASHEET
I2C Hardware:  On the Arduino Uno, SDA is A4 and SCL is A5.
One thing you almost always have to do with I2C is to provide a 10K pull-up to +5 on each pin (SDA and SCL) - I use a small breadboard whenever I use I2C, so I have power, ground, A4 and A5 available for pullups and multiple devices.
The reason for this is that the I2C bus is active-low.   It signals by pulling the pins low in sequence to communicate.
If you already had the DS3231 RTC module on the same bus, which apparently you do not or you would not be asking this question, then you do not need your own pull-ups because the RTC includes them internally.

It might be easier for you to use a different I2C ADC such as the ADS1115.
Here is a generic search that shows the module:
https://smile.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=i2c+adc
Here is a generic search which shows the software side:
https://www.google.com/search?q=arduino+ads1115+ADC+library+download

When you say talk to it directly, do you mean send it the data in the format outlined on page 22 of the datasheet, byte by byte?

Yes.    For instance, think about how you use the serial port.   Serial.begin(); then Serial.println(x);  The Serial library is handling all the byte-by-byte and bit-by-bit stuff.  I searched a lot and couldn't find an Arduino library that would make it easier for your device like that.  Back to the OP, though,  I suspect your only problem was the lack of proper pull-ups on the A4 and A5 lines - 10K to +5 on each.  Armed with the datasheet that explains how the thing communicates, byte-by-byte might not be so bad.  If you really want to make this thing work.

I agree that the first step (after adding pull-ups), is to run the IP Scanner program and make sure it responds.  When it does, then you can go from there, with confidence that you are using the correct address..

Even with the pull-ups connected, I couldn't get a response from it. :(
I think I'll just find a similar DAC that's documented with Wire. Thanks for the help though!

Darnit.    Anyway, look at my answer where I recommend the one I would use.


text:
Error 400. The request has an invalid header name ESP8266 (HTTP-POST)
I'm trying to send a http post to my server from an esp8266-Wifi (I use the ESP8266 library)
I check all my http post format, and I guess is okay... but at the response, the monitor serial answer me like this:
Requesting POST: HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Sat, 10 Jun 2017 23:12:48 GMT
Connection: close
Content-Length: 339

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

closing connection

and this is my code:
#include <ESP8266WiFi.h>
const char* ssid     = "Putostodosmenosyo";
const char* password = "CetriX.2016%Gdl";

const char* host = "187.201.44.110";

const String Cadenadatos = "info=Micanton|2017-06-09%2012:00|25" ;
//const String Tamano = String(Cadenadatos.length()) ;
const String postiu = "POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1\r\nHost:187.201.44.110:80\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length:144\r\n\r\n?info="+String(Cadenadatos)+"\n" ;
const String postam = String(postiu);

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

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  delay(2000) ;
}

void loop() {

  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host,httpPort)) {
    Serial.println("Conexion fallida");
    return;
  }

 //String data = "pst=temperature>" + String(random(0,100)) +"||humidity>" + String(random(0,100)) + "||data>text";

   Serial.print("Requesting POST: ");
   // Send request to the server:
   //client.println("POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1");
   //client.println();
   //client.println("co2kelling.hopto.org") ;
   client.println("POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1");
   client.println("Host: co2kelling.hopto.org");
   client.println("Content-Type: application/x-www-form-urlencoded");
   client.print("Content-length: ");
   client.print(postiu.length());
   client.println();
   client.print(String(Cadenadatos));
   while(client.connected())
   {
    while(client.available())
    //String line = client.readStringUntil('\r') ;
    Serial.write(client.read()) ;
   }

   /*delay(500); // Can be changed
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }*/
  Serial.println();
  Serial.println("closing connection");
  delay(5000);
}

NOTE: this is my fixed url
http://187.201.44.110/wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino?info=Micanton|2017-06-09%2012:00|25
EDIT
This is my Post format:
POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length
info=string

You are lacking the required blank line between the headers and the content. Also your content length is wrong.
Change
client.print(postiu.length());

Into
client.println(Cadenadatos.length());

"closing connection
Requesting POST:"
This is now the response.

I just spotted your content length uses the wrong value. See my updated answer.

Yeah, I solved my problem, thanks Majenko.


text:
Why do you need a second resistor when using a photoresistor/LDR?
A photoresistor is already a resistor and will limit the voltage in the circuit. Why can't this be connected to a pin and measured? Why is a second resistor needed to connect the photoresistor to ground?

why we use resister in ldr circuit

The simple answer is that voltage is very easy for the Arduino to measure, while resistance is not, and most sensors such as Photoresistor (LDR), flex sensor, thermistors and more - are actually a variable resistors.
The main reason it's hard to measure resistance changes is that the Arduino (and most IC) contain a tiny system called Analog to Digital Converter (ADC). This system translates changes in analog voltage to a series of 1's and 0's that can be in turn converted to an Integer for example.
The ADC is designed to read voltage changes, and if we want to use the Arduino's analogRead (which utilizes the ADC) to get the Photoresistor readings for example, we will need a way to convert the changes in resistance to changes in voltage - and a voltage divider is the easiest way to do it.
It is true that the sensor is already a resistor, and as such it should change the voltage across it. But you would have trouble measuring the voltage changes, since there is no reference point except for Vcc (5V) and Ground:

In contrary, when using a voltage divider, you have a well defined reference point to measure the voltage changes:

This isn't strictly an Arduino question, but I appreciate that things like photo-resistors are common early projects for Arduino users.
Resistors (and other components) don't really limit the voltage in the circuit as such. Rather, each component in a series circuit gets a proportion of the total voltage. That proportion is determined by its resistance.
If you only have one component, then the entire voltage is dropped across it no matter what resistance it has. Changing the resistance in that situation would only affect the amount of current flowing through it.
You need the second resistor as a fixed reference point. You know how much voltage it will get if both resistances are equal, and that the relationship between voltage and resistance is (hypothetically) linear. You can therefore use that to figure out what resistance the other component has, e.g. the photo-resistor.
As a side note, the second resistor can also play an important role for safety. Without it, you could potentially end up with a short-circuit if the other component's resistance goes too low.

"would only affect the amount of current" - I think this is incorrect, like the case where you use a resistor next to a LED to drop the voltage. Also, A2D are high impedance, and low resistance shouldn't cause short-circuit.

@Omer "If you only have one component...". A resistor and LED together are two components. :) You're right that a short-circuit isn't an issue for a typical A2D, but that's not the only situation where you might want to use a photo-resistor or similar.

Right, missed that :)

Accurate measurement of resistance requires a precise current source (http://www.digikey.com/product-search/en/integrated-circuits-ics/pmic-current-regulation-management/2556448?k=current%20source).
Ohm's law, V=IR or  R=V/I states that for linear components, the value of resistance in the circuit can be estimated by the ratio of the applied voltage divided by the current.  With a simple voltage divider, as the resistance of the sensor changes so does the current in the circuit.  So measuring the voltage at the junction does not necessarily provide an accurate indication of the current in the circuit.  Both the imposed voltage and current should be controlled to obtain accurate measurements.

Unlike other electric components, a photoresistor(or light-dependent resistor,LDR,or photocell) is a variable resistor. This means its resistance can depend according to light intensity.

I will go first with half of the circuit diagram to understand clearly.
The resistance of a photoresistor decreases with increasing light intensity.
Strong Light —> LDR resistance(decreases to 0ohms) So the 10k(ohm) resistor sees closer to 5V.
The resistance of a photoresistor increases with decreasing light intensity.
Dim Light —>LDR resistance(increases to infinity).
So, the 10k(ohm) resistor only gets a little voltage.
Here is the full circuit diagram that you want to ask why second resistor is needed.

The key point is Arduino board also has Vcc(5V) and ground. So, there is no current if the potential difference is zero. Therefore, firstly, Vcc(5V) will flow through the photoresistor and go to the 10k(ohm) resistor.
Then, since there is a parallel circuit, arduino will get the same voltage as the 10k(ohm) resistor. So this LDR resistor does the function of a pull-up resistor which draws the current to VCC.

also another big reason for it is if you have just in series, a power source, an LDR and say a bulb, then the bulb may come on as soon as the LDR resistance gets low enough, then it will get brighter as the resistance keeps decreasing.
If configured with more resistors in a potential divider with a transistor and the bulb at the collector side, then you can vary the resistors to define the exact amount of light that will allow approx 1.6V (?)(whatever voltage turns the base into a conductor anyway), and therefore the light at which the bulb will suddenly turn on with a constant power supply direct from the power source through a fixed resistor if needed.
So in series an LDR will vary the current with light around the circuit, in a divider and transistor it functions as a light dependant switch

I THINK NONE OF THE ABOVE ANSWERS ARE CLEARLY DEFINING THE SOLUTION. I WILL ANSWER WITH RESPECT TO THE WORKINGS OF AN LDR CIRCUIT  WITH A LIGHT BULB THAT SWITCHES ON IN THE DARK AND OFF IN LIGHT.
LETS ASSUME THAT WE HAVE AN LDR ONLY CONNECTED IN SERIES TO A LIGHT BULB. THE LDR IS ALREADY ACTING AS A VARIABLE RESISTOR AND HENCE WILL ALLOW CURRENT TO FLOW IN THE PRESENCE OF LIGHT, (LIGHT INTENSITY BEING DEPENDANT ON THE CURRENT RESISTANCE) AND WILL LIMIT THE CURRENT WHEN IT IS DARK. THIS MEANS THAT THE BULB LIGHTS UP IN LIGHT AND IS OFF WHEN IT IS DARK. THERE IS NO PRACTICAL USE FOR THIS. I WANT THE BULB TO LIGHT IN THE DARK AND SWITCH OFF IN THE PRESENCE OF LIGHT.
SO WHAT I DO IS ADD A RESISTOR IN SERIES TO THE LDR. THIS RESISTOR HAS A FIXED RESISTANCE MUCH LOWER THAN THE LDR AT ITS HIGHEST RESISTANCE BUT MUCH HIGHER THAN THE LDR AT ITS LOWEST RESISTANCE. THE BULB ELECTRIC PATH IS CONNECTED BETWEEN THE LDR AND THE RESISTOR. PLEASE NOTE THAT THE RESISTOR IS PLACED ABOVE THE LDR.
NOW LOOK AT IT IN TERMS OF CURRENT FLOW.
WHEN THERE IS LIGHT, THE LDR RESISTANCE IS LESSER THAN THE RESISTOR. HENCE THE CURRENT FLOWS FROM THE BATTERY TO THE RESISTOR AND A SIGNIFICANT PORTION OF THAT CURRENT CONTINUES TO FLOW IN SERIES THROUGH THE LDR AND BACK TOWARDS THE BATTERY. THE REMAINDER OF CURRENT IS CARRIED OVER TO THE BULB ELECTRIC PATH WHICH IS NOT SUFFICIENT TO LIGHT THE BULB. HENCE THE BULB STAYS OFF IN THE LIGHT.
WHEN ITS DARK, THE LDR RESISTANCE IS HIGHER THAN THE RESISTOR. HENCE THE CURRENT FLOWS FROM THE BATTERY TO THE RESISTOR AND INSTEAD OF CONTINUING TO THE LDR WHICH IS CONNECTED IN SERIES, IT TAKES THE PATH OF LEAST RESISTANCE TOWARDS THE BULB. THE LDR RESISTANCE HAS EFFECTIVELY BLOCKED THE CURRENT FROM FLOWING THROUGH IT AND DIRECTED IT TOWARD THE BULB. HENCE THE BULB LIGHTS UP IN THE DARK.
IN TERMS OF PRACTICAL USAGE THIS IS MOST IMPORTANT CONCEPT. ALL OTHER REASONS FOR USING A SECOND RESISTOR WITH AN LDR ARE SECONDARY.

Why are you shouting?

This is not a practical use of an LDR and a (light) bulb. Using an LDR to effectively short out the light bulb in conditions of higher ambient light is extremely inefficient. In the context of Arduino projects, it is important to be able to derive a precise measure, converted relative to a voltage, of the light falling on the LDR.

This "answer" misses the point of the question and appears to have been written by a chat bot.


text:
About Making Library
There is a tutorial in the Arduino website on how to create a library. The tutorial gives the following codes for the header:
class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

My questions are:

What is the purpose of this line: Morse(int pin);
If any, what is the name of this line?

For looking further: note that the code you have isn't a library, it's a class (which can be put into a library). There are some really good articles on classes in C++ online that will go into detail about how they are written.

Your a penguin sir. @AnnonomusPenguin I'm a big fan of Tux.

What is the purpose of this line: Morse(int pin);

It is the method that is called when you create an object of class Morse when only passing a single int:
Morse somemorse(1);

If any, what is the name of this line?

It has multiple names, depending on what aspect you care about:

It is a constructor for the class Morse.
It is a forward declaration for the method Morse::Morse(int).

Morse(int pin);

is the constructor for the class, Morse.
The name of this line, and all of the other lines between the curly braces{ and } are declarations of the members of the class Morse.
So, the line
Morse(int pin);

is the declaration of the constructor, to answer both of your questions in one line.
Constructors are required pieces of code for Object Oriented Programming. When the constructor is called, it creates an object which is an instance of the class Morse. In this constructor is where all of the initialisation of the oblject goes. In the case of Morse it just initialises pin, which is specified in the parameter pin, by setting it to be an OUTPUT.
It is declared here, as a "signpost" if you will, for other parts of the code to know that it exists and is available to be called.


text:
Program got so many errors about expected ) or ; before either
This is my first time to try program arduino, and I am clueless. I have a friend who told me about things work, and he told me the programming language is C (or similar to C) which we have learned in our class. I just program as my friend examples, but it doesn't work and return error codes about expected ; before ( or ) before ; etc.
I'm not sure why this wont work. This is the hardware (simulated) I going to make.

here's the code:
#define dw 8; //buttons down
#define ri 9; //buttons right
#define le 10; //buttons left
#define up 11; //buttons up
#define ok 12; //buttons ok
#define mn 13; //buttons menu
#include <LiquidCrystal.h>
LiquidCrystal lcd(6,5,4,3,2,1);
int i=0;
char input[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

void setup()
{
  pinMode(dw, INPUT);
  pinMode(ri, INPUT);
  pinMode(le, INPUT);
  pinMode(up, INPUT);
  pinMode(ok, INPUT);
  pinMode(mn, INPUT);
}
void intext()
{
  int c=0, lim=16;
  for(i=0;i<lim;)
  {
    lcd.setCursor(c,1);
    input[i]=97;
    if(dw=HIGH)
    {
      if(input[i]>122)
        input[i]=97;
      input[i]=input[i]+1;
      lcd.print(input[i]);
    }
    if(up=HIGH)
    {
      if(input[i]>97)
        input[i]=122;
      input[i]=input[i]-1;
      lcd.print(input[i]);
    }
    if(ri=HIGH)
    {
      c=c+1;
      lcd.setCursor(c,1);
      lcd.print(input[i]);
    }
    if(le=HIGH)
    {
      c=c-1;
      lcd.setCursor(c,1);
      lcd.print(input[i]);
    }
    if(ok=HIGH)
    {
      lim=i+1;
    }
  }
}

void loop()
{
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Masukan kata:");
  intext();
}

I have no idea why it wouldn't work. I'm sorry if I'm too stupid to understand.
Thank you!
Edit: oh yeah, the errors, here:
  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 (Windows NT (unknown)), Board: "Arduino Uno"
programyuhu.ino: In function 'void setup()':
programyuhu:14: error: expected `)' before ';' token
programyuhu:14: error: expected primary-expression before ',' token
programyuhu:14: error: expected `;' before ')' token
programyuhu:15: error: expected `)' before ';' token
programyuhu:15: error: expected primary-expression before ',' token
programyuhu:15: error: expected `;' before ')' token
programyuhu:16: error: expected `)' before ';' token
programyuhu:16: error: expected primary-expression before ',' token
programyuhu:16: error: expected `;' before ')' token
programyuhu:17: error: expected `)' before ';' token
programyuhu:17: error: expected primary-expression before ',' token
programyuhu:17: error: expected `;' before ')' token
programyuhu:18: error: expected `)' before ';' token
programyuhu:18: error: expected primary-expression before ',' token
programyuhu:18: error: expected `;' before ')' token
programyuhu:19: error: expected `)' before ';' token
programyuhu:19: error: expected primary-expression before ',' token
programyuhu:19: error: expected `;' before ')' token
programyuhu.ino: In function 'void intext()':
programyuhu:28: error: expected `)' before ';' token
programyuhu:28: error: expected primary-expression before '=' token
programyuhu:28: error: expected `;' before ')' token
programyuhu:35: error: expected `)' before ';' token
programyuhu:35: error: expected primary-expression before '=' token
programyuhu:35: error: expected `;' before ')' token
programyuhu:42: error: expected `)' before ';' token
programyuhu:42: error: expected primary-expression before '=' token
programyuhu:42: error: expected `;' before ')' token
programyuhu:48: error: expected `)' before ';' token
programyuhu:48: error: expected primary-expression before '=' token
programyuhu:48: error: expected `;' before ')' token
programyuhu:54: error: expected `)' before ';' token
programyuhu:54: error: expected primary-expression before '=' token
programyuhu:54: error: expected `;' before ')' token

In C and in C++, #define is not an instruction of the language, but a directive of the pre-processor.
What it does is define a "macro" which will be replaced everywhere it appears later on in the source file.
For instance:
#define DUMMY 152

int x = x + DUMMY;
myfunction(DUMMY);

will be changed, before compilation, into:
int x = x + 152;
myfuntion(152);

In the example above, DUMMY is replaced everywhere by what follows it in the  #define line, i.e. 152.
As pre-processor directive is not an instruction, it shall not be ended by ;. If you add ; at the end of a #define, then it will be part of the replacement:
#define DUMMY 152;

int x = x + 152;;
myfuntion(152;);

As you can see now, DUMMY is replaced by 152;, not just 152.
So the solution in you example is to remove all ; that are at the end of #define lines:
//buttons down
#define dw 8
//buttons right
#define ri 9
//buttons left
#define le 10
//buttons up
#define up 11
//buttons ok
#define ok 12
//buttons menu
#define mn 13

Note that comments should also be removed from the #define otherwise they would also appear everywhere the replacements are done.

Here's the first line of your code:

#define dw 8; //buttons down

Here's the first error line:

pinMode(dw, INPUT);

Let's put them together and see what we get:
pinMode(8; //buttons down, INPUT);

That's not valid C++. Using the output I've shown you, modify the input until it looks correct. And then keep doing it until the code compiles.

I am sorry for asking this, but did you mean
(pinMode(8; buttons down, INPUT);) ? I don't quite understand on the comment part.

Did you read the code you wrote? Did you read the parts I extracted?

Sorry again if I don't understand, I don't know about C++ at all (as I only learn about the regular C).
So I just copy your code as is?
I'm lost

Look at the first line of code in my answer. Look at the second line of code in my answer. When taken together, they result in the third line of code in my answer. Does this make sense to you?

I tried it but it's still doesn't work. I will try to redo/change my code using another way. Sorry for the trouble I have caused.
Thank you for your assistance.
You made me realize how difference C++ with C is.
Again Thank you.

This is not a C-vs.-C++ issue. You would have exactly the same problem if only C were in use.

The errors are in your #define statements.
These should not have ; as they are not executable statements


text:
Arduino as USB HID
Is it possible to build a HID device (like a keyboard) using an Arduino uno?
At the time being, I have button inputs on the Arduino giving outputs on the serial line. So, how can I transform my current firmware into something that can behave like a HID keyboard?

Shall I write a new window device driver?
Shall I create a software layer that could take my serial data and have windows read it as HID input?
Is there any better way to achieve this, if it is possible at all?

I may be wrong, but this is not really about Arduino. Its about Window's side device driver development.

First answer in google : http://mitchtech.net/arduino-usb-hid-keyboard/ ... but you did not specify which Arduino. On a Leonardo it's builtin, and the appropriate driver already exists (see http://arduino.cc/en/Reference/MouseKeyboard).

I'm using an Uno, but I'll look at what you posted because last time we considered the DFU update but we're kinda scared of bricking stuff as the components aren't as readily available and cheap in my area as in most places.

@AsheeshR Well, now you've added more information to back up your claim, but it's just a link. So why didn't you post a more ellaborate version of that comment as an answer (not to be considered a link answer) and wait for the upvotes? That would have been much more constructive than voting for closing it.

@AsheeshR This issue is on meta now: http://meta.arduino.stackexchange.com/q/102/46

Well, that's definitely possible, as the Arduino Uno features an Atmega16u2 as USB driver chip, the user can use either DFU or ICSP flashing to push on the device a firmware close to the leonardo's which will make the Arduino behave as a HID keyboard. There's no windows development involved, no driver to be built as USB/HID devices are recognized per default. i.e. that question should be reopened.

Is it possible to build a HID device (like a keyboard) using an Arduino uno?

yes it is! And there's a great tutorial on how to do that over here

At the time being, I have button inputs on the Arduino giving outputs on the
serial line. So, how can I transform my current firmware into something that
can behave like a HID keyboard?

As the tutorial shows you, you need to transform your firmware code so instead of
printing the events, you actually trigger events. What you need to do, is add to your
code:
void triggerKey(uint8_t mod, uint8_t chr) {
    uint8_t buf[8] = {mod, chr, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    // press key
    Serial.write(buf, 8);
    // emulate key press delay
    delay(10);
    buf[1] = 0x00;
    // release key
    Serial.write(buf, 8);
}

What you're doing here, is send from your main Arduino microcontroller events over
the serial line to the smaller microcontroller that handles USB communication. That
microcontroller will take those key "buffers" and transfer them as USB HID Keyboard
key presses over USB.
Beware that the key character (chr in the code here), is actually a keycode sent
over USB that gets interpreted by your USB HID driver, which then translates it into
a real character using the current layout you've setup for your keyboard.
The mod character is one of the modifier keys you have on the keyboard (shift,
control, alt...), 0x00 being no modifier.

Shall I write a new window device driver?

No, you don't need! With the DFU upgrade, your arduino will be seen as a USB keyboard
by windows.

Shall I create a software layer that could take my serial data and have windows read it as HID input?

You neither need to do that, and it's actually a very bad idea for many reasons:

your solution would not be portable, and thus you'd need to hack something for every platform you may use,
your solution would imply a lot of new code ; the more code one write, the more bugs is likely to be in your system,
your solution would be really hackish, as it would behave as a device driver (i.e. kernel land) taking input from
a user program (i.e. user land) and is likely to not work, be a hell to debug, and prone for security issues...
If that's even possible to do!

I'm using an Uno, but I'll look at what you posted because last time we considered the DFU update but we're kinda scared of bricking stuff

Finally you're having concerns, in a comment, about bricking your arduino. Please
believe me and the author of the article that you cannot brick your arduino
doing a firmware flash:
NOTE: There is no chance of ‘bricking’ the device using this method. The Arduino bootloader firmware can always be updated using the DFU protocol!
In case something gets really badly wrong, and you get a bootloader corruption in the
little AVR (atmega8u2), you still can reflash it using another arduino or an
atmel programmer using the 6 pins next to the USB plug.
In the end, know that the only way to brick an AVR, thus an Arduino as well, is
to play with the fuses and reset the programming fuses. And even then, you may use
HVSP to save your device, though it's often less trouble to just take a new chip.

Thanks for all the useful info, we ended up achieving this.

Well, the proper way to brick an AVR is with over current / over voltage. Then it will be toasted...

But then, it's not called bricking, but frying it, or as you say toasting it. Put 15amps through the MCU, and I bet you'll see it jump through the room ;-)

How to release a specific key? I want to emulate a key HOLD then release. And also in the link, the character goes to array [2] while here goes to [1]. Why?

well, as shown in my example, you do it in two steps, first you press the key, then there's the delay, then you release it. Well, then you'd need to lecture yourself on how hardware keyboard implementation works, it's kind of not natural, and each value of the array have a meaning. Pardon me for not having a link to share atm, but whenever you find something searching the web, please post a new comment ☺

Just to be clear. This ability depends on the Atmega16u2, so e.g. this is not possible with Arduino nano?


text:
How are locations in FLASH memory addressed?
There is an external FLASH memory (W25Q80DV) that I want to use with the Arduino.
This memory has 4096 pages of 256 bytes each.
I want to make multiple writes per page to use memory evenly and erase less.
Test code:
#include <SPI.h>

#define readStatusReg_1 0x05
#define readArrayReg 0x0B
#define writeEnableReg 0x06
#define pageProgramStatusReg 0x02

#define FLASH_SELECT_CHIP 33

// # Select / Unselect chip
void selectChip(bool state) {
  switch (state) {
    case true:
     digitalWrite(FLASH_SELECT_CHIP, HIGH);
     digitalWrite(FLASH_SELECT_CHIP, LOW);
      break;
    case false:
     digitalWrite(FLASH_SELECT_CHIP, HIGH);
      break;
  }
}

// # Wait flash ready state
void notBusy() {
  uint16_t whileCounter;
  selectChip(true);
  SPI.transfer(readStatusReg_1);
  while((SPI.transfer(0) & 1) && whileCounter < 45000) { whileCounter++; }
  selectChip(false);
}

// # Send command and address
void sendCommandAndAddress(const byte command, const unsigned long address) {
  SPI.transfer(command);
  SPI.transfer((address >> 16) & 0xFF);
  SPI.transfer((address >> 8) & 0xFF);
  SPI.transfer(address & 0xFF);
}

// # Write enable
void writeEnable() {
  notBusy();
  selectChip(true);
  SPI.transfer(writeEnableReg);
  selectChip(false);
}

// # Write FLASH page
bool writeFlashData(const unsigned long address, byte * data) {
  writeEnable();
  selectChip(true);
  sendCommandAndAddress(pageProgramStatusReg, address);
  uint16_t len = sizeof(data);
  for(uint16_t i = 0; i < len; i++) {
    SPI.transfer(*data++);
  }
  selectChip(false);
  notBusy();
  return true;
}

void setup() {
  // SPI
  pinMode(FLASH_SELECT_CHIP, OUTPUT);
  digitalWrite(FLASH_SELECT_CHIP, HIGH);
  SPI.begin();
  SPI.setDataMode(0);
  SPI.setBitOrder(MSBFIRST);

  // Write FLASH
  #define TESTADDRESS 0x1000
  byte msgData[] = "Hi all!";
  writeFlashData(TESTADDRESS, msgData);
}

void loop() {}

Here, the address #define TESTADDRESS 0x1000 (4096) is specified for writing data.
I'm not clear if this is the page address or the byte address from which I will start recording?
I would like to actually split one page into multiple blocks and write data for them separately.

I'm not clear if this is the page address or the byte address from which I will start recording?

That is the byte address.  As the data sheet in section 8.5.13 says:

If an entire 256 byte page is to be programmed, the last address byte (the 8 least significant address bits) should be set to 0. If the last address byte is not zero, and the number of clocks exceed the remaining page length, the addressing will wrap to the beginning of the page.

In other words: if you want to write an entire page then start at the beginning of the page. If you don't and you write more than there is room left in the page you will wrap round back to the beginning of the page again.
So if you write two bytes starting with address 0x10FF you will actually write one at 0x10FF and the second at 0x1000, not 0x1100, since you wrap at the page boundary.

thank you for the answer!

Good answer, except I don't think your example is correct. On an 8-bit device like an AVR-based arduino, a page boundary is a 256 byte page. The range 0x100F to 0x1010 is not a page boundary. The example should 0x10FF to 0x1100. On 16, 32 and 64 bit processors, there are often also word alignment considerations around even 2 byte, 4 byte, or 8 byte addresses, but those don't apply to Arduinos (at least not to AVR-based Arduinos.)

@DuncanC This has nothing to do with AVR. This is an SPI-connected Flash chip - the W25Q80DV.

@DuncanC But you're right about the boundary - that was just me getting my bytes and nibbles muddled up.

Yeah, I realized that after the post. The flash chip almost certainly has an 8 bit bus though, which would be why it uses 256 byte pages.


text:
How to tell if there is a line break from Nextion display to Arduino at Serial
Well I am trying make language page with Nextion display and Arduino Mega. If user enter the language page Nextion display is sending page name with this commend to Arduino for which is current page.

While page preinitializing moment.
print "dil"

If user choice a language and then press the Next button, Nextion sending this comment to Arduino.
if(r0.val==1)
{
  va0.txt="en"
}else if(r1.val==1)
{
  va0.txt="tr"
}else
{
  va0.txt="de"
}
print va0.txt
page 2

Everyting is normal until here. If user press back button at page 2 in a short time. Serial print not only send "tr" or "de" or "en" but also sending "dil" comment all together. Because of that Serial2.readString(); commend return such as "trdil" or "endil" or "dedil". So that program not working properly. Just I want to receive language's 2 letter short code.
There is a comment which is useful if I send data Arduino to Nextion to understand last of the commend line.
  Serial2.write(0xff);
  Serial2.write(0xff);
  Serial2.write(0xff);

How can tell the Arduino there is a line break after sending "tr" or "en" or "de".
Assume that I am using simple Serial receiver commend.
void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
}

void loop() {
  if (Serial2.available() > 0)
  {
    String Received  = Serial2.readString();
    Serial.println(Received);
  }
}

check for the newline character ... if you receive it, then it is being sent

Can you show me a tutorial

You didn't show your Arduino code

@chrisl I have added simple receiver code


text:
Arduino Uno Bluetooth connection
I'm trying to connect two Arduino Unos with Bluetooth modules (HC-06 and HC-05). Does anyone know the steps required to do that?
I still haven't figured out:

How to pair the two Bluetooth devices, and;
How to pair each Bluetooth with each Arduino.

If you have any useful tutorials, please let me know.

There is a nice example for Arduino here.
Connecting 2 Arduinos by Bluetooth using a HC-05 and a HC-06: Pair, Bind, and Link
The Uno works the same way as the board in the example.
Arduino 1

Arduino 2


text:
How many WS2811 LED strips can I control with Arduino?
Is there any limitation to connecting more strips?
I plan to create for my temple Ganpati Street Lighting LED Decoration - Full HD Ahmednagar Mh India
Watch this video and give me some ideas and suggestions.

In principle you can connect one strip per digital pin, but that looks like a huge amount of data to stream out of an Arduino. Even a Mega would likely be short of flash and RAM.

you could use a bunch of $2 pro-minis, software serial controlled by a mega.

There are three factors to consider when driving strings of these LEDs from an Arduino:

How much memory the Arduino has - each LED takes at least 3 bytes of RAM (possibly more depending on the library implementation). (An Uno could probably just manage 500 at most)
How long it takes to send the data over the wire - the more LEDs you have in a chain the longer each update takes and the slower your animations run.
How you power such a huge number of LEDs efficiently. You won't just plug them into the 5V pin of the Arduino that's for sure.

Note that the arrangement you link to most likely isn't a single small microcontroller controlling the whole lot. Instead it is much more likely each individual strip has a single controller and those controllers are all networked together (probably through RS-485 or CAN) to a master controller (probably a PC) to send instructions to them all.

I have worked with setups similar to this. Arduino is limited as mentioned by Majenko.
If you like the Arduino platform I recommend you look into the Teensy based controllers.  They are 32 bit based and have more memory and are optimized to handle LED projects like this. Best of all, it uses the Arduino IDE with numerous libraries.  The Teensy would need to be paired with a Network adapter, so you could use sACN E1.31 and use software like Jinx to create the effects you're wanting to do.

Majenko is totally right (as always).
But as an alternative solution, you could opt for SPI-based LEDstrips. They're not bound to specific timings and thus:

You can "generate"/stream colors. You can let your Arduino calculate the next color and send it directly. In this way, you'll only need RAM for one pixel at the time. For the length, you're now only limited to the time it takes to update a strip.
Sending of data in SPI is done in hardware and can thus be done by hardware, while your software focusses on the next job/pixel. (So you also don't need to calculate the whole strip at once, before sending)
Often, you can send "pixels" much faster, by simply increasing your SPI clock. I'm not sure what the limit will be here, check the ledstrip datasheets.

Also, if you're going to push the limit of Arduino, why not use better hardware? The Teensy 3.2 is often used for ledstrip projects, since it has 64K ram and 256K flash and can run at 96Mhz  (not sure about the SPI speed). Have a look at fastled and octows as well.
You should split up this project, to make it scalable. Try to make one "row" of it and start adding more rows (with individual controllers and power).
I agree with Majenko on using RS485 or CAN to connect/command/sync these different rows.

I think the SPI trick only works when you combined it with DMA.

@Gerben, you've got SPI-controlled LEDstrips, they can handle "waiting" between LED's, since you can effectively "halt" them by not toggling the clock line. Also, I believe hardware SPI has a "SPI Serial Transfer Complete" interrupt and an 8-bit shift register, so after starting the transfer, you do have some "free time" before it had been completely written, but I'm not sure if it's significant. (But if you start the next transfer a little later, it won't matter for spi-strips, since their timing isn't arbitrary but based on the spi-clock you generatie yourself)

But this question was specifically about ws2812s which don't have an SPI like interface.

You've got a point there! But I wanted to give an alternative option, choosing the right hardware/interfacing can overcome having to solve everything in software/making it more efficient. If spi-ledstrips are too expensive (or simply want to use WS2812’s, Majenko's answer is better but the options are more limited.


text:
How do powering arduino both barrel jack and lipo battery together?
I have arduino mega and Lipo batterry such this and Lipo battery charger 5V USB Boost. I am powering arduino normally from barrel Jack with an 9 Volt adaptor. But if there is power cut occur, I dont want to stop, I want powering arduino with Lipo battery. After power come back, arduino contunie to powering from barrel jack again at the same time battery start to charge. How can I succes this. Do you have any sample circuit?
After Majenko♦ comment, I've tried circuit but there is heating problem occur. More then 70 celsius. Is that normal?
Circuit

Termal Circuit

Plug the (boosted) battery into the USB socket. Job done.

;) if i try that, boost is heating much more. Is that normal

No, that's not normal. If the barrel jack power is greater than 7V then the USB power should be isolated.

Majenko, you have it backwards. That boost circuit is designed to have 5V OUT at the USB and <5V in at the other end, so you can use a 1S LiPo battery to charge a cell phone. So, the battery goes to the input, while the power can be tapped from the USB connector output to the 5V pin on the Arduino to power the Arduino with 5V. A Schottky diode should probably go from the 5V out on the boost converter to the 5V pin on the Arduino to prevent backflow as well. Charging the LiPo battery from the barrel jack is another issue. That will require a LiPo charge controller IC.

@Majenko I've edited question with your solution but termal problem seen

@GabrielStaples that's why I say the boosted battery. And the usb power circuit deals with the isolation for you. The P-FET is the diode to prevent back powering and there is a handy polyfuse for added protection too.

@mehmet, woah, that's cool! I need a thermal camera. That's super useful. Your images are very low quality/low resolution though. Can you upload higher-resolution images?

Is that a genuine Arduino Mega or a cheap Chinese knock-off? If the latter they probably skimped on the power circuitry.

@GabrielStaples thnks! this is the seek thermal compact pro. Sorry about resulution this is max resulution 320 x 240 Thermal Sensor.

As is described in this post from the arduino forum, There is a MOSFET switch in series with the USB connector +5V input line.  If the battery booster 5V output is connected to the USB input jack, then it will automatically power the UNO whenever power is disconnected from the barrel jack, and will be automatically disconnected whenever at least 7.0V is available at the barrel jack.
If you are experiencing over-heating problems, then you are probably overheating the linear regulator that steps down the barrel jack voltage to 5V.  You need about 7-7.5V at the barrel jack to overcome the 2-2.5V loss through the linear regulator, but anything higher than about 7.5V will just cause the linear regulator to get hotter.

thanks for technic answer. If so I have something on my mind, only powering from barrel jack (9v) should make heating problem has to do it but it doesn't work like that with only powering from barrel dont make any heating problem


text:
Arduino library redeclaration error
This is my first time here and I hope someone can be of help!
I'll try to keep it as concise as possible.
So I have two sensors/modules, 1 is an LCD screen from elecrow and another is the DS1307. Both are connected through analog 4 and 5. I tried hooking them up with the help of my breadboard but I've stumbled upon the following issue with the libraries (I don't even know if what I'm trying to achieve is possible but I'm trying nevertheless(and failing horribly while at it))
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

    C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:31: error: redeclaration of 'OFF'

     enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                   ^
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

    C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:457:5: note: previous declaration 'LCD_SwitchState OFF'
         OFF=0x00,

         ^
    In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

    C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:42: error: redeclaration of 'ON'

     enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                              ^
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

    C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:458:5: note: previous declaration 'LCD_SwitchState ON'

         ON=0x01

         ^

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

What I make out of this, is that the libraries are conflicting with each other on the following:

OFF = 0x00
ON = 0x80
ON= 0x01

Is there anyway to fix this? I know that I have to edit the .h libraries but I don't know what to change and to what it should be changed, here's the library code on the module itself:
// RTC based on the DS1307 chip connected via I2C and the Wire library
enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

class RTC_DS1307 {
public:
   boolean begin(void);
   static void adjust(const DateTime& dt);
   uint8_t isrunning(void);
   static DateTime now();
   static Ds1307SqwPinMode readSqwPinMode();
   static void writeSqwPinMode(Ds1307SqwPinMode mode);
   uint8_t readnvram(uint8_t address);
   void readnvram(uint8_t* buf, uint8_t size, uint8_t address);
   void writenvram(uint8_t address, uint8_t data);
   void writenvram(uint8_t address, uint8_t* buf, uint8_t size);
};

Thank you for your help!
C.C
EDIT:
I think that I might have come a bit closer. I tried implementing one of the answers and that made me get the following error:
    C:\Users\c\Documents\Arduino\libraries\RTClib\RTClib.cpp:284:1: error: 'Ds1307SqwPinMode' does not name a type

 Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() {

 ^

exit status 1
Error compiling for board Arduino/Genuino Uno.

That's a whole lot less than before. I will keep this updated!
EDIT 2:
Meanwhile, I tried something entirely else like changing the name of OFF and ON Throughout the RTClib concerning only the DS1307 module. That however gives me an entirely new line of errors such as:
error: 'enum Ds1307SqwPinMode' is not a class or a namespace

  RTC_DS1307 Ds1307SqwPinMode::readSqwPinMode() {

                                              ^

and:
error: could not convert '(Ds1307SqwPinMode)mode' from 'Ds1307SqwPinMode' to 'RTC_DS1307'

   return static_cast<Ds1307SqwPinMode>(mode);

                                            ^

These errors in particular only take place in the .cpp library
This is where I am stuck now at the moment

Hint#1: You could for instance move the enum into the context of the class (and reduce the enum name, Ds1307SqwPinMode => SqwPinMode).

@MikaelPatel as example: "DS1307PinMode" ?

Hint#2: Why are some member functions "static" and others not?

@MikaelPatel if only I knew, I haven't made this library myself, this is why it's so unnerving for me as well, especially since I'm a beginner with the Arduino. The manufacturer of the code elecrow is responsible for this, I've sent them a message that there's something wrong. Now I'm waiting for a reply.. I will try to implement your solution in the meanwhile, thanks!

Hint#3: Uppercase-only symbols are traditionally used for defines (preprocessor symbols, macros, etc) in C/C++.

FINAL EDIT WITH SOLUTION:
I finally stumbled upon the last wall of issues before getting it to work,

I redownloaded all the libraries
Went to the .h library file of RTClib
Changed the variable names from OFF to OFF and on to ONN (it's stupid I know but bear with me)
Encounter an entirely new error which seemingly occurs at board version 1.6.23

Error:

In function 'global constructors keyed to
  BME280_LCD_TIME.o':
lto1.exe: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See http://gcc.gnu.org/bugs.html for instructions.
lto-wrapper.exe: fatal error: C:\Program
  Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc
  returned 1 exit status
compilation terminated.
c:/program
  files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe:
  error: lto-wrapper failed
collect2.exe: error: ld returned 1 exit status
exit status 1 Error compiling for board Arduino/Genuino Uno.

Go to Tools > Board > Boards manager
I personally had to change "Arduino AVR Boards by Arduino version 1.6.23"  to version 1.6.21
Compile the code
And that should do the trick!

A general rule is to keep definitions such as enum's within the context of the class (library). Below is a possible refactoring:
class RTC_DS1307 {
public:
   enum SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

   ...
   static SqwPinMode readSqwPinMode();
   static void writeSqwPinMode(SqwPinMode mode);
   ...
};

Cheers!

This sure did something! Seems like I have to dig a bit in to the .cpp now! I will try to mess around a bit! Thanks!

So I tried some things such as changing the name
RTC_DS1307 Ds1307SqwPinMode::readSqwPinMode() {
but all that does is give me 'Ds1307SqwPinMode' has not been declared. I'm stuped on this one

@CCG Do not forget to accept the answer.

check my upcoming edit!