text:
Mains And Battery Monitor Using Delay on And Delay off
I am very new to Arduino. In fact I am entirely new to embedded system. I have been using other platforms for my experiments specifically PICs.
I just moved to Arduino for more easier coding but I am hooked somewhere.
Here is the constraints:
In the code I will post below;

When MAINS is present and is within usable range, both MAINS_OK & ENABLE Pins will go HIGH after 3sec delay(non-blocking).
When MAINS is BAD, MAINS_OK Pin will go LOW immediately while ENABLE Pin will wait for 3sec before going LOW.
If MAINS is recovered and is within usable range again, the sequence described in "1." must be followed an so on.

I have tried in so many ways, it is not working as expected. Only the blinking of the SYSTEM LED is working fine.
// constants won't change. Used here to
// set pin numbers:
const int enablePin     = 7;      // the number of the Function Pins
const int lvdPin        = 6;
const int sysledPin    = 5;
const int mainsokPin   = 4;

// Variables will change:
int mainsPin = A0;
int batteryPin = A2;
int MAINS;
int BATT;
int ENABLE = LOW;
int LVD = LOW;
int SYS_LED = LOW;
int MAINS_OK = LOW; // State used to set the Function Pins

long previousMillis1 = 0;
long previousMillis2 = 0;// will store last time PIN was updated
long previousMillis3 = 0;
long previousMillis4 = 0;
long previousMillis5 = 0;

long ENABLE_ON        = 3000;
long ENABLE_OFF       = 3000;
long LVD_ON           = 3000;
long LVD_OFF          = 3000;
long MAINS_DELAY_ON   = 3000;
long MAINS_DELAY_OFF  = 0;
long SYS_LED_ON       = 1000;
long SYS_LED_OFF      = 1000; //Duration of the delay time (milliseconds)

void setup()
{
  pinMode(ENABLE, OUTPUT);  // set the digital pin as output:
  pinMode(LVD, OUTPUT);     // set the digital pin as output:
  pinMode(SYS_LED, OUTPUT); // set the digital pin as output:
  pinMode(MAINS_OK, OUTPUT); // set the digital pin as output:
  pinMode(A0, INPUT); //set pin as Analog nput
  pinMode(A1, INPUT); //set pin as Analog nput
}
void loop()
{
  unsigned long currentMillis1 = millis();
  unsigned long currentMillis2 = millis();
  unsigned long currentMillis3 = millis();
  unsigned long currentMillis4 = millis();

  if ((SYS_LED == LOW) && (currentMillis1 - previousMillis1 >= SYS_LED_OFF))
  {
    SYS_LED = HIGH;  // Turn it off
    previousMillis1 = currentMillis1;  // Remember the time
    digitalWrite(sysledPin, SYS_LED);  // Update the actual SYS_LED
  }
  if ((SYS_LED == HIGH) && (currentMillis1 - previousMillis1 >= SYS_LED_ON))
  {
    SYS_LED = LOW;  // turn it on
    previousMillis1 = currentMillis1;   // Remember the time
    digitalWrite(sysledPin, SYS_LED);    // Update the actual SYS_LED
  }

  MAINS = analogRead(mainsPin);

  //========================= MAINS OK =======================================
  /* If MAINS supply is ok, the MAINS_OK and ENABLE Pins will wait for 3sec
      before going high. Both Pins will go high at the same time.
  */

  if (MAINS >= 84 && MAINS <= 177) // >=0.410V && <=0.864V >=140V && <=250V
    if ((MAINS_OK == LOW) && (currentMillis2 - previousMillis2 >= MAINS_DELAY_ON))
    {
      MAINS_OK = HIGH;  // Turn MAINS_OK on with 3sec delay
      previousMillis2 = currentMillis2;  // Remember the time
      digitalWrite(mainsokPin, MAINS_OK);  // Update the actual MAINS_OK
    }
  if (MAINS >= 84 && MAINS <= 177) // >=0.410V && <=0.864V >=140V && <=250V
    if ((ENABLE == LOW) && (currentMillis3 - previousMillis3 >= ENABLE_ON))
    {
      ENABLE = HIGH;    //Turn ENABLE ON with 3sec delay
      previousMillis3 = currentMillis3;  // Remember the time
      digitalWrite(enablePin, ENABLE);  // Update the actual MAINS_OK
    }

  //=================== MAINS NOT PRESENT or IT IS LOW/HIGH VOLTAGE ====================
  /* As soon as MAINS is lost, whether it enters low voltage or high voltage,
     the PINs MAINS_OK will go LOW imedatly without delay while ENABLE will wait for
     3sec before going LOW. Then If MAINS is restored OK, the initial delay sequence
     must be followed.
  */
  if (MAINS <= 53 || MAINS >= 258) // <= 0.260V || >=1.26V// Below <= 120V and >= 276V
    if ((MAINS_OK == HIGH) && (currentMillis2 - previousMillis2 >= MAINS_DELAY_OFF))
    {
      MAINS_OK = LOW;  // Turn MAINS_OK off after 0sec delay
      previousMillis2 = currentMillis2;  // Remember the time
      digitalWrite(mainsokPin, MAINS_OK);  // Update the actual MAINS_OK
    }
  if (MAINS <= 53 || MAINS >= 258) // <= 0.260V || >=1.26V// Below <= 120V and >= 276V
    if ((ENABLE == HIGH) && (currentMillis3 - previousMillis3 >= ENABLE_OFF))
    {
      ENABLE = LOW;    //Turn ENABLE off aftar 3sec delay
      previousMillis3 = currentMillis3;  // Remember the time
      digitalWrite(enablePin, ENABLE);  // Update the actual ENABLE
    }

  BATT = analogRead(batteryPin);

  //============================ BATTERYERY SETTINGS ==============================
  /* If Battery is below 21V LVD Pin go HIGH with 3sec delay
      When it goes high, it remains high the Batter goes up to 27.6V
      LVD will then go LOW ahter 3sec delay
  */
  if (BATT <= 391) //(1.91V) 21V         // BATTERY Low
    if ((LVD == LOW) && (currentMillis4 - previousMillis4 >= LVD_ON))
    {
      LVD = HIGH; //Turn LVD on with 3sec delay
      previousMillis4 = currentMillis4;  // Remember the time
      digitalWrite(lvdPin, LVD);  // Update the actual LVD
    }

  if (BATT >= 512) // (2.50V)  27.6V         // BATTERY low Recovery
    if ((LVD == HIGH) && (currentMillis4 - previousMillis4 >= LVD_OFF))
    {
      LVD = LOW; // turn LVD off after 3sec delay
      previousMillis4 = currentMillis4;  // Remember the time
      digitalWrite(lvdPin, LVD);  // Update the actual LVD
    }
}

Please What can I add or remove from this code for it to work properly?
Thanks.

When MAINS is OK ... i think that you would get undesired behavior with that test because it is true every time you check the value .... you probably want When MAINS becomes OK  ... that happens only once at transitions between OK and NOT-OK

When MAINS is OK means when mains is within usable range but "MAINS_OK" is a digital output pin.

you are misunderstanding my comment ... if you test for MAINS is OK then you will set the 3 second timer over and over ... you have to test for the transition between NOT-OK and OK

There are lots of problems with your code. To start, most/all of this code is wrong:
  pinMode(ENABLE, OUTPUT);  // set the digital pin as output:
  pinMode(LVD, OUTPUT);     // set the digital pin as output:
  pinMode(SYS_LED, OUTPUT); // set the digital pin as output:
  pinMode(MAINS_OK, OUTPUT); // set the digital pin as output:
  pinMode(A0, INPUT); //set pin as Analog nput
  pinMode(A1, INPUT); //set pin as Analog nput

Those lines should be setting various pins to their desired input/output state. However, you are using the variables you declared to hold their bool status, not their pin numbers.
The variables you are using are declared like this:
int ENABLE = LOW;
int LVD = LOW;
int SYS_LED = LOW;
int MAINS_OK = LOW; // State used to set the Function Pins

Those are not pin numbers, those are variables that hold boolean values.
This line, for example:
pinMode(MAINS_OK, OUTPUT); // set the digital pin as output:

Should almost certainly read
pinMode(mainsokPin, OUTPUT); // set the digital pin as output:

Instead.
Same goes for enablePin, lvdPin, and sysledPin
The two lines
pinMode(A0, INPUT); //set pin as Analog nput
pinMode(A1, INPUT); //set pin as Analog nput

Should probably read
pinMode(mainsPin, INPUT); //set pin as Analog nput
pinMode(batteryPin, INPUT); //set pin as Analog nput

Since you define the variables mainsPin and batteryPin.

Thanks Duncan! I will go now and edit the code according to you advise.


text:
Tone() conflicts with IRremote library (multiple definition of `__vector_7')
I have just started with Arduino and C++ so I apologise if my question is very basic.
I am trying to use tone() with a passive buzzer to create a sound while also using the IRremote library for a remote. However, whenever they are used together, it gives this error:

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_7'
libraries\IRremote\IRremote.cpp.o (symbol from plugin):(.text+0x0):
  first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.

This is the code required to recreate this error:
#include "IRremote.h"
#include "pitches.h"
int melody[] = {NOTE_C5, NOTE_E6};

void setup() {}

void loop() {
 for (int thisNote = 0; thisNote < 2; thisNote++) {
 tone(3, melody[thisNote], 300);
}
}

Please could you advise me on how to fix this issue and if necessary, on a different library or way to create a sound or to receive IR signals?

I think your problem is related to https://forum.arduino.cc/index.php?topic=165675.0, which is about two libraries using the same timer.

I'm looking through Tone.cpp and i think it's possible to force it to use another timer by defining USE_TIMER1 i will verify this asap.

@FilipFranik, thanks. Where do you find tone.cpp? I downloaded Arduino IDE from the Windows Store.

@MichelKeijzers The forum you linked doesn't seem to explain how to fix the issue I am facing although I do think it is the same problem.

https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Tone.cpp

@rgiller I know, that's why I just post it as a comment instead of an answer.

@FilipFranik Do you mean I should change #define USE_TIMER2 to a different number which is different to the IR remote?

Exactly as @MichelKeijzers wrote the issue is caused by "IRremote" using same timer as "Tone" and the solution to this problem is a little dirty.
Since Tone is included in ArduinoCore (and compiled) we can't easilly modify it so the only thing that worked for me is to modify boarddefs.h file of IRremote library. Since it's code is easilly available after downloading it using "Library Manager" included in ArduinoIDE.
In my tests I used ATmega328P settings.

Edit C:\Users\youruser\Documents\Arduino\libraries\IRremote\boarddefs.h and look for your processor number.
For ATmega328 the definition is #define IR_USE_TIMER2

I simply changed it to use #define IR_USE_TIMER1

And compilation was successfull.
Sketch uses 2746 bytes (8%) of program storage space. Maximum is 30720 bytes.
Global variables use 242 bytes (11%) of dynamic memory, leaving 1806 bytes for local variables. Maximum is 2048 bytes.

My code:
#include "IRremote.h"

#define NOTE_C5  523
#define NOTE_E6  1319

int melody[] = {NOTE_C5, NOTE_E6};

void setup() {}

void loop() {
  for (int thisNote = 0; thisNote < 2; thisNote++) {
    tone(3, melody[thisNote], 300);
  }
}

It is possible to change the timer used by the library by defining IR_USE_AVR_TIMER{1-5} prior to loading the library.
#define IR_USE_AVR_TIMER1

#include "IRremote.h"
#include "pitches.h"

source: Stack Exchange

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

sort: votes


text:
How long should TinyMPU6050.h calibration run for?
I just found a lightweight library for the MPU6050 gyro. Example below.
mpu.Calibrate() never seems to end. I'm keeping it very still. When I take this out, the rest of the code works fine.
https://github.com/gabriel-milan/TinyMPU6050/blob/master/examples/ArduinoIDE_All_Gets_Example/ArduinoIDE_All_Gets_Example.ino

I feel so sorry about the previous releases of TinyMPU6050. I've just released v0.5.0 that shall soon be available at the Arduino Library Manager index.
The calibration method indeed was messy, so I decided to keep it simple. I also removed dependencies of String objects and Serial stuff and it seems to work pretty fine now.
If you keep having issues with that, please let me know!
The official link to release 0.5.0 follows:
https://github.com/gabriel-milan/TinyMPU6050/releases/tag/0.5.0

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


text:
how to set buzzer on and off
I have a project that require me to use magnetic contact sensor. I will put the sensor at the door. So the idea is i want every time someone open the door, the buzzer will make a sound, but it will only stay for 3 seconds. When the door is close, buzzer will do nothing and when someone open the door again, the buzzer will make a sound for 3 seconds again. That is the loop. Here is my code. Sorry it's messy. I changed it few times and it still not working like what I want.
const int buzzer = 13;
const int sensor = 4;

int state; // 0 close - 1 open switch

void setup()
{
  pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
  state = digitalRead(sensor);

  if (state == HIGH){
    tone(buzzer,1000);
    delay(3000);
    noTone(buzzer);
  }

  else{
    noTone(buzzer);
  }

}

You have to make your requirement more clear... what after the last 3 seconds?

You could change the delays delay(1000); and delay(5000); to delay(3000);? No? Or what exactly seems to be the problem you are facing?

I'm still new here so I don't know how to write longer at my question or at least tell the detail. I'm using Magnetic contact sensor to put it at the door. So I want my buzzer to make a sound everytime someone open the door. But the sound will only stay for 3 seconds. Then when I close the door, and open back, it will make sound again.

being new here is no reason for not describing clearly what it is that you want to happen?

You have tried to cram your entire question into the subject line. That isn't all that helpful. Try reading how to ask a good question. The code is good to see, but it would also help to have you describe what happens, compared to what you expect to happen.

If you want a delay of 3 seconds, why does your code have a delay of 1000ms? That is one second. This seems to be an obvious problem to fix.

i change it multiple times to test. to save time, i change the delay so i don't have to wait. if it work, i can just change the delay.

When I have a state-machine problem such as this, I diagram it first - here's mine, based on how I understand your requirements:

Most state machines are only activated when an external event happens, so not much happens inside the state-boxes. But since your application only does this one thing, you can actually do your testing inside the states. This is the difference between between blocking- and non-blocking programming - we can afford to block (delay until something happens) because there is nothing else we have to do in the meanwhile.
And my code for the state-machine (which I haven't tested, but it compiles without error):
const int buzzer = 13;
const int sensor = 4;

int state; // 0 close - 1 open switch

void setup()
{
   pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
   // Wait for sensor HIGH
   while( digitalRead(sensor) == LOW )
      ;

   // Sensor HIGH - Alarming
   tone(buzzer, 0.52);
   delay(3000);

   // Wait for sensor LOW
   noTone(buzzer);
   while( digitalRead(sensor) == HIGH )
      ;

   // (goes to Wait for sensor HIGH)
}

“diagram it first” is really the best advice.

I'm sorry for late reply. I'm new here so i don't really understand the concept. i thought your code belong to other person, so i reply to him. I tried your code. It works but I don't want any sound when the sensor is LOW. Your code make the buzzer on for 3 seconds when the sensor is LOW and HIGH. I just want the buzzer turn on when the sensor HIGH. But your code is really helpful. Thank you.

I edit your code a bit and it's working ! Thank you.
Serial.println("sensor: " + sensor);
while ( digitalRead(sensor) == LOW );
noTone(buzzer);
// Sensor HIGH - Alarming
tone(buzzer, 400);
delay(3000);
// Wait for sensor LOW
noTone(buzzer);
while( digitalRead(sensor) == HIGH )
;
// (goes to Wait for sensor HIGH)


text:
Is there any good working MODBUS TCP master library available for Arduino?
I would like to connect with Fronius solar inverter through MODBUS TCP with Arduino to READ and WRITE register values only. I want to set the Arduino as master and the Inverter as slave. I want to use only two functions "Read Holding Registers" and "Write Single Holding Register" function code '3' and function code '6' respectively. Is there any good and working library available for these? And also an example.

Check out the library Modbus-TCP on Github. It has the facility for all the function codes as asked. It has provision for Wiznet W5100 and ENC28J60 Ethernet IC. All tested with Arduino Mega. See the well documented example code for the Wiznet module in the library.
For detailed knowledge about the library, read the index.html inside the doc folder of the library.
Here is an example code explaining a few function codes for the Arduino Mega and a W5100 module.
/*
  This is Modbus test code to demonstrate all the Modbus functions with
  with Ethernet IC WIZNET W5100

  ModbusTCP is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  ModbusTCP is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with ModbusTCP.  If not, see <http://www.gnu.org/licenses/>.

  Adopted from ModbusMaster for RTU over RS-485 by Doc Walker
  Modified by Narendra Dehury for TCP.
  copyright @ phoenixrobotix.com

*/
#define WIZNET_W5100 1

unsigned int param_value_int[7];
#include <Ethernet.h>

IPAddress ModbusDeviceIP(10, 10, 108, 211);  // Put IP Address of PLC here
IPAddress moduleIPAddress(10, 10, 108, 23);  // Assign Anything other than the PLC IP Address

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xE1 };

#include <ModbusTCP.h>

ModbusTCP node(1);                            // Unit Identifier.

void setup()
{

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);                      // To disable slave select for SD card; depricated.

  Serial.begin(9600);
  delay(1000);
  Ethernet.begin(mac, moduleIPAddress);
  node.setServerIPAddress(ModbusDeviceIP);
  delay(6000);                                // To provide sufficient time to initialize.

}

void loop()
{
  uint8_t result;

  node.setTransactionID(random(100));           // Not necessary; but good to distinguish each frame individually.
  result = node.readHoldingRegisters(1, 12);    // Read Holding Registers

  Serial.println(result, HEX);
  if(result != 0)
  {
    Serial.println("TimeOut");

    delay(6000);
  }

  int len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));// See the length of data packet received.
  for (byte j = 0; j < len; j++)
  {
    Serial.print(node.getResponseBuffer(j));       // Inspect the data.
    Serial.print(" ");
  }
  Serial.println();
  node.clearResponseBuffer();
  delay(100);

  node.writeSingleRegister(5, 3);                  // Write single register
  Serial.println(result, HEX);
  delay(500);

  for (byte i = 0; i < 5; i++)
  {
    node.setTransmitBuffer(i, (i+100));
  }
  node.writeMultipleRegisters(2, 5);               // Write multiple register
  Serial.println(result, HEX);
  delay(500);

  node.writeSingleCoil(20, 1);                     // Write Single coil
  delay(500);

  node.setTransmitBuffer(0, 0b1010101001010101);

  node.writeMultipleCoils(20, 16);                 // Write multiple coils
  delay(500);
  result = node.readCoils(20, 18);
  len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));
  Serial.println(node.getResponseBuffer(0), BIN);

  node.clearResponseBuffer();
  delay(5000);
}

Could you explain why you think it is useful, as well as giving a summary of the link? As it stands if it a link only answer. Should the link die, at some point in the future, your answer would not be very useful.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - From Review

I have updated the post. Please share your concern for downvotes. I will try to help you.

Few days back I was facing the same situation, I could not find a suitable library for Modbus TCP where Arduino will act as a client. So I decided to make one. And that link is the link to the library. You should encourage such activity rather than asking for deletion.

Your answer had been paced in the review queue on account of its brevity, and I was merely going through the reviews... you have been on SE for over a year, and as such you should know how SE works and that link only answers are frowned upon, and an additional explanation is generally required. I didn't down vote it, btw. Your expanded answer is much better, thanks (although I'm not sure about the now suit yourself, as that could be taken the wrong way) :-)

I am sorry for all the show. Thank you for the guide. :)

hello goddland_16  this code gives some error when I compile it on Arduino IDE

@Prayuktibid accept it if it is working.

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


text:
How can I receive several inputs from wifi and save them?
I'm trying to send and receive some data from one Arduino to another Arduino. I'm using an Arduino Uno and FS1000A / XY-MK-5V 433Mhz TX/RX Modules. For transmitting I use the Radiohead library.
I want to send two strings and save them as different strings. My receiver code is:
#include <RH_ASK.h>
#include <SPI.h> // Not actualy used but needed to compile

RH_ASK driver;

void setup() {
  Serial.begin(9600); // Debugging only
  if (!driver.init())
    Serial.println("init failed");
}

void loop() {
  uint8_t buf[200];
  memset(buf, '\0', 200);
  uint8_t buflen = sizeof(buf);
  if (driver.recv(buf, &buflen)) {
    // Non-blocking
    Serial.print("Message: ");
    Serial.println((char*)buf);
  }
}

First of all, why do I have to use #include <SPI.h>? To receive I use:
if (driver.recv(buf, &buflen)) {
  // Non-blocking
  Serial.print("Message: ");
  Serial.println((char*)buf);
}

This code saves the output as one output! How can I specify which input is the first one and which is the second one?

If commenting out #include <SPI.h> causes an error, then presumably it is required by RH_ASK.hor something it drags in. The buffer buffor the received messages is recreated on each loop iteration so previous messages are lost. What do you want to do with 2 consecutive messages, concatenate them together or what?

I think we'd also need to know what data you are expecting to receive - unless it's always exactly 200 bytes, you'll need a way to tell where it finishes.

I want to sent two integer ( or I can send them as characters) but I want to save them as two variables.

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


text:
I can't upload my program to Arduino Uno
I've not used my Arduino for about 2 months. Before this time it worked fine, but now when I want to upload my program I get this error:

Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

I reset immediately after uploading but it doesn't work.What else should I do?
I'm using Ubuntu and the Arduino IDE.

https://hackingmajenkoblog.wordpress.com/2016/08/24/diagnosing-arduino-problems-in-linux/

Checks:

Check if the board has power (probably it will).
Check if the board is shown at the ports in the IDE (i.e. COM3: Arduino Uno).
Check if you put the correct board in the IDE (e.g. Uno, Mega etc.).
Check if you have multiple versions of the IDE running.
Check if you have multiple IDEs installed.
Check if you don't have the RX pin used while uploading a sketch.

Try the following:

Use a different USB port on your computer
Use a different USB cable
Reinstall the Arduino IDE

Apparently, I had two versions installed and I was launching the wrong one (Arduino Genuino). Thank you

You are welcome ... you also can change the board in the IDE (I will update my answer)

I struggled with a failure to upload the Blink program, with LED between #13 pin (+) and GND lead.
My solution was found by choosing other serial ports by stepping through the Serial Port options under the Tools menu
Selecting the correct port brought my new board to life!

Hi and welcome to Stack Exchange! How does this differ from the second point in the accepted answer?

Make sure you have a current limit resistor between #13 pin and the LED, like 270 ohm to 1K, 2K, in that range.  Don't burnout your IO pin.


text:
Arduino Mega2560, Ethernet Shield & OV0706: "Camera not found"
I want to take a picture with the OV0706 and save it to an SD card. I'm using an Arduino Mega2560, Ethernet Shield (with SD slot) and an OV0706. I tried the tutorial for this camera from Adafruit, but I'm still getting a 'No camera found?' error.
I thought it had something to do with assigning the pins, but if I connect the RX from the OV0706 with A15 on the Mega (see picture), it still gives the same error.
// On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
SoftwareSerial cameraconnection = SoftwareSerial(69, 3);

The code (important part):
// This is a basic snapshot sketch using the VC0706 library.
// On start, the Arduino will find the camera and SD card and
// then snap a photo, saving it to the SD card.
// Public domain.

// If using an Arduino Mega (1280, 2560 or ADK) in conjunction
// with an SD card shield designed for conventional Arduinos
// (Uno, etc.), it's necessary to edit the library file:
//   libraries/SD/utility/Sd2Card.h
// Look for this line:
//   #define MEGA_SOFT_SPI 0
// change to:
//   #define MEGA_SOFT_SPI 1
// This is NOT required if using an SD card breakout interfaced
// directly to the SPI bus of the Mega (pins 50-53), or if using
// a non-Mega, Uno-style board.

#include <Adafruit_VC0706.h>
#include <SPI.h>
#include <SD.h>

// comment out this line if using Arduino V23 or earlier
#include <SoftwareSerial.h>

// uncomment this line if using Arduino V23 or earlier
// #include <NewSoftSerial.h>

// SD card chip select line varies among boards/shields:
// Adafruit SD shields and modules: pin 10
// Arduino Ethernet shield: pin 4
// Sparkfun SD shield: pin 8
// Arduino Mega w/hardware SPI: pin 53
// Teensy 2.0: pin 0
// Teensy++ 2.0: pin 20
#define chipSelect 4

// Pins for camera connection are configurable.
// With the Arduino Uno, etc., most pins can be used, except for
// those already in use for the SD card (10 through 13 plus
// chipSelect, if other than pin 10).
// With the Arduino Mega, the choices are a bit more involved:
// 1) You can still use SoftwareSerial and connect the camera to
//    a variety of pins...BUT the selection is limited.  The TX
//    pin from the camera (RX on the Arduino, and the first
//    argument to SoftwareSerial()) MUST be one of: 62, 63, 64,
//    65, 66, 67, 68, or 69.  If MEGA_SOFT_SPI is set (and using
//    a conventional Arduino SD shield), pins 50, 51, 52 and 53
//    are also available.  The RX pin from the camera (TX on
//    Arduino, second argument to SoftwareSerial()) can be any
//    pin, again excepting those used by the SD card.
// 2) You can use any of the additional three hardware UARTs on
//    the Mega board (labeled as RX1/TX1, RX2/TX2, RX3,TX3),
//    but must specifically use the two pins defined by that
//    UART; they are not configurable.  In this case, pass the
//    desired Serial object (rather than a SoftwareSerial
//    object) to the VC0706 constructor.

// Using SoftwareSerial (Arduino 1.0+) or NewSoftSerial (Arduino 0023 & prior):
#if ARDUINO >= 100
// On Uno: camera TX connected to pin 2, camera RX to pin 3:
//SoftwareSerial cameraconnection = SoftwareSerial(2, 3);
// On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
SoftwareSerial cameraconnection = SoftwareSerial(69, 3);
#else
NewSoftSerial cameraconnection = NewSoftSerial(2, 3);
#endif

Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);

// Using hardware serial on Mega: camera TX conn. to RX1,
// camera RX to TX1, no SoftwareSerial object is required:
//Adafruit_VC0706 cam = Adafruit_VC0706(&Serial1);

void setup() {

  // When using hardware SPI, the SS pin MUST be set to an
  // output (even if not connected or used).  If left as a
  // floating input w/SPI on, this can cause lockuppage.
#if !defined(SOFTWARE_SPI)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
#else
  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
#endif
#endif

  Serial.begin(9600);
  Serial.println("VC0706 Camera snapshot test");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }

  // Try to locate the camera
  if (cam.begin()) {
    Serial.println("Camera Found:");
  } else {
    Serial.println("No camera found?");
    return;
  }

Thanks in advance.
(Pictures: http://prntscr.com/apdvi9 )

Since at least my camera needs up to 2 seconds to initialize, I think the
if (cam.begin()) {
Serial.println("Camera Found:");
} else {
Serial.println("No camera found?");

returns immediately what it thinks No camera found
Try it with
    unsigned long timer = millis();
    Serial.println("Camera initializing:");
    while (!cam.begin()) {
    Serial.print(".");
    if (millis()-timer>3000) {
      Serial.println("No camera found?");
      break;
      }
    }


text:
How do I read data from Parallel port DB25 over my Arduino?
I am using this program. However, I am getting garbage values only.
Do revert as to how can I get proper values over my arduino.
/*****************************************************************************/
* PrinterCapturePoll.ino
* ------------------
* Monitor a parallel port printer output and capture each character. Output the
* character on the USB serial port so it can be captured in a terminal program.
*
* By............: Paul Jewell
* Date..........: 29th January 2015
* Version.......: 0.1a
*-------------------------------------------------------------------------- -     ----
* Wiring Layout
* ------------ -
*
* Parallel Port Output               Arduino Input
* --------------------               ------------ -
* Name      Dir.   Pin                Name    Pin
* ----             -- -                ----    -- -
* nSTROBE    >       1..........................2
* DATA BYTE  >     2 - 9.......................3 - 10
* nACK       <      10.........................11
* BUSY       <      11.........................12
* OutofPaper <      12................GND
* Selected   <      13.................5v
* GND        <>  18 - 25................GND
*------------------------------------------------------------------------------ -
******************************************************************************** /

int nStrobe = 2;
int Data0   = 3;
int Data1   = 4;
int Data2   = 5;
int Data3   = 6;
int Data4   = 7;
int Data5   = 8;
int Data6   = 9;
int Data7   = 10;
int nAck    = 11;
int Busy    = 12;
int led     = 13; // use as status led

void setup() {
  // Configure pins
  pinMode(nStrobe, INPUT_PULLUP);
  for (int n = Data0; n < (Data7 + 1); n++)
    pinMode(n, INPUT_PULLUP);
  pinMode(nAck, OUTPUT);
  pinMode(Busy, OUTPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  while (!Serial) {
    Serial.println("Waiting to Initialise");
  }
  //State = READY;
  delay(1000);
  Serial.println("Initialised");
  delay(1000);
}

void loop() {
  while (digitalRead(nStrobe) == HIGH) {
    digitalWrite(Busy, LOW);
    digitalWrite(nAck, HIGH);
    digitalWrite(led, HIGH);
    ProcessChar();
  }
  digitalWrite(Busy, HIGH);
  digitalWrite(led, LOW);
  digitalWrite(nAck, LOW);
  delay(5); //milliseconds. Specification minimum = 5 us
}

void ProcessChar() {
  byte Char;
  Char = digitalRead(Data0) +
         (digitalRead(Data1) << 1) +
         (digitalRead(Data2) << 2) +
         (digitalRead(Data3) << 3) +
         (digitalRead(Data4) << 4) +
         (digitalRead(Data5) << 5) +
         (digitalRead(Data6) << 6) +
         (digitalRead(Data7) << 7);
  Serial.print(char(Char));
}

The ProcessChar(); command should be before the DigitalWrite(nAck,LOW);

Thanks for this one. It is storing data. But, it is storing garbage bytes only.

When I try to print the output bits in char, they show - " " . When in int, they show: "1". And, the raw data when printed, shows like: 'ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ}}xa44=wwwwwÿÿÿÿÿÿÿÿÿÿÿ' . I have set the Baud Rate: 9600, Parity: None, Data Bits: 8, Stop Bits: 1 and Hardware Control: None

Do the hard-coded messages (Waiting to Initialise and Initialised) appearing correctly?

Yes. They appear properly. And after that when I switch on my DPU, it starts giving me : ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ...  And, when I print something from it to the Printer, over the DB25 port, it shows varied symbols like }}xa44=wwwww or i#%"%0#"`iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiggggggggggf*iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiâ+¾ioig8$iig ' etc

Try changing the 'byte Char' to 'char Char'. I can see that you have done the type conversion but Serial print just spits out the ASCII value of whatever is stored as a byte which is why you maybe seeing junk values. Also try using Serial.write instead of Serial.print.

What is the data rate of your parallel port? Your Arduino will not send more than 960 bytes/s. Also, I would connect the data lines to pins A8..A15, which allows the simplification void ProcessChar() { Serial.write(PORTK); }

I meant PINK.

I think I can see the problem - although I have no way to test it.
According to Wikipedia:

When the data was ready, the host pulled the STROBE pin low, to 0 V. The printer responded by pulling the BUSY line high, printing the character, and then returning BUSY to low again.

That's not what you're doing - you are repeatedly reading while the strobe is HIGH.
Here's my attempt at your loop() which I hope will at least get you started:
void loop()
{
    // Wait for strobe to go LOW, indicating a character is ready
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };

    // Strobe is now LOW - a character is ready.
    // Pull BUSY to high
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, HIGH);
    digitalWrite(led, LOW);
    digitalWrite(nAck,LOW);

    // Print the character
    ProcessChar();

    // Return BUSY to low again
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, LOW);
    digitalWrite(led, HIGH);
    digitalWrite(nAck,HIGH);

    // Wait for the strobe to go HIGH again
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };
}

You should also probably consider setting the initial values of your outputs (BUSY and nAck) rather than relying on them defaulting to some particular state.  I don't know what (n)Ack is for in this case -- Wikipedia doesn't mention it.

Do you know the printer is working properly?
You are trying to fix more than one thing at once and that's never a good idea.  What I suggest you do is get a breadboard and make your own printer simulator.  You need to connect and LED up to every output pin and a button to every input pin.
Then you can simulate data from the printer, i.e. just pressing the button for pin 3 and you should see 1 coming out on the serial monitor.  OK I agree this "simulator" is rubbish, but you probably have the bits to knock it up now.
If you are still seeing 'junk' values then have a look and see if there is a pattern to the data.  This would be helped by printing the values in hex.
Of course if the Arduino side works then the issue is that the printer is sending data that you are not expecting.  It might help stick LEDs on every pin, both directions, it will help you see what is being sent.
Its possible that you are expecting 1 to indicate the bit is set and the printer is using 0.


text:
Arduino Mega failing to connect to XAMPP database/php server to send HTTP requests
I have developed an application with a SunFounder Mega2560 with a W5100 Ethernet shield that acts as a server and successfully parses TCP message packets from a client sending in updates. I am now trying to add HTTP GETs into the mix by sending off my data to update an XAMPP server, which I am treating as a client in my code.
For some reason, I can't seem to connect to the XAMPP's Apache service on my machine for it to receive the HTTP message to update the MariaDB table through a PHP script I created. The Apache service seems to be listening on port 80, which I am attempting to initiate the connection on.
You can mostly just pay attention to the postData() command below, but I'm including everything for completeness.
#include <stdlib.h>
#include <string.h>
#include <SPI.h>
#include <Ethernet.h>

#define MAX_CLIENTS 1
#define MAX_LINE_LEN 100
char inputs[MAX_CLIENTS][MAX_LINE_LEN] = {0}; // Instantiate 2D array of client/received data
int msg_array[] = {0,0,0,0};

EthernetServer server(1174);                  // Create server object on port of server, which will be used to respond to commands
EthernetClient *client = NULL;                // Create client objects limited to size of MAX_CLIENTS
EthernetClient db;                            // Create a client object just for posting HTTP commands to the database

byte mac[] = {0x24,0x0A,0xC4,0xAC,0xC1,0x78}; // Arduino's physical MAC
byte ip[] = {192,168,1,23};                   // IP of this controller
byte gateway[] = {192,168,1,77};              // Router address (internet)
byte myDns[] = {192,168,1,77};                // Router dns
byte subnet[] = {255,255,0,0};                // Subnet mask
byte dbserver[] = {192,168,1,77};             // IP address of SQL server

unsigned long wd_Dside, wd_Cside;             // Gather current Arduino pgm ms timestamp
unsigned long wd_Delap, wd_Celap = 0;         // Create an elapsed time counter
int dside_prev, cside_prev = 0;       // Create a previous state for each AV to determine code execution
char rId[3] = {0};
int avSide = 0;

// --------------------------------------------------------------------------------------------------------

void setup(){

// initialize the ethernet device
//  Ethernet.begin(mac, ip, myDns, gateway, subnet);
  Ethernet.begin(mac, ip);

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
  ; // wait for serial port to connect. Needed for native USB port only
  }

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware.");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
        }
  }

  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  pinMode(22, OUTPUT);                          // pin selected to control AV D SIDE
  pinMode(23, OUTPUT);                          // pin selected to control AV C SIDE

  // wait 5 seconds for connection:

  delay(5000);
  server.begin();                                // Start server
  Serial.print("Server started on ");
  Serial.println(Ethernet.localIP());
  delay(1000);

  wd_Dside, wd_Cside = millis();

}

// --------------------------------------------------------------------------------------------------------

void loop() {

  delay(100);
  int i=0;

  EthernetClient newClient = server.available();
  if (newClient) {
    if (client==NULL){
    client = new EthernetClient(newClient);
  }
  }

  if (client != NULL && client->available()){                     // If the data isn't garbage and the data is available..
    Serial.print("Client's IP address: ");
    Serial.println(client->remoteIP());
    Serial.print("Client sent: ");
    char newChar = client->read();                                // Read the data
    Serial.println(newChar);

    if (newChar == '\0') {                                        // Check for a termination character for separation
      Serial.println("Client terminated message.");
      char delimiters[] = ",";                                    // Use a string parser in order to get command parameterization
      char* valIndex;
      valIndex = strtok(inputs[i], delimiters);
      for (int j=0; j<4; j++){                                    // Expand later to largest anticipated character count
        msg_array[j] = atoi(valIndex);
        //Serial.print(msg_array[j]);
        valIndex = strtok(NULL, delimiters);
      }

      switch(msg_array[0]) {                                      // Determine type of message received via Ethernet (Character 0 parsed as Message Type)

        case 3:                                                   // Examine string for instructions to turn AVs on or off.

        char cstr[16];
        strcat(rId, itoa(msg_array[2],cstr,10));              // Build rId string prior to any potential HTTP post (which refs rId)
        strcat(rId, itoa(msg_array[3],cstr,10));
        Serial.print("R ID: ");
        Serial.println(rId);

        if(msg_array[1] == 1)                                     // Msg type 3, Instruction 1: Turn D side AV ON
          {
            avSide = 0;
            if (dside_prev != msg_array[1]){
              Serial.println("Dside AV is OPEN.");
              digitalWrite(22, HIGH);                             // Set pin 4 low
              postData();                                         // Call the HTTP POST function
            }

            dside_prev = msg_array[1];
            wd_Delap = 0;                                         // Reset elapsed time watchdog time value for D side.
            wd_Dside = millis();                                  // Last good heartbeat received from client device on D side.
          }
        if(msg_array[1] == 2)                                     // Msg type 3, Instruction 2: Turn Dside AV OFF
          {
            avSide = 0;
            if (dside_prev != msg_array[1]){
              Serial.println("Dside AV is CLOSED.");
              digitalWrite(22, LOW);                              // Set pin 4 low
              //postData();                                         // Call the HTTP POST function
            }

            dside_prev = msg_array[1];
            wd_Delap = 0;                                         // Reset elapsed time watchdog time value for D side.
            wd_Dside = millis();                                  // Last good heartbeat received from client device on D side.
          }
        if(msg_array[1] == 3)                                     // Msg type 3, Instruction 3: Turn Cside AV ON
          {
            avSide = 1;
            if (cside_prev != msg_array[1]){
              Serial.println("Cside AV is OPEN.");
              digitalWrite(23, HIGH);                             // Set pin 5 high
              //postData();                                         // Call the HTTP POST function
            }

            cside_prev = msg_array[1];
            wd_Celap = 0;                                         // Reset elapsed time watchdog time value for C side.
            wd_Cside = millis();                                  // Last good heartbeat received from client device on C side.
          }
        if(msg_array[1] == 4)                                     // Msg type 3, Instruction 4: Turn Cside AV OFF
          {
            avSide = 1;
            if (cside_prev != msg_array[1]){
              Serial.println("Cside AV is CLOSED.");
              digitalWrite(23, LOW);                              // Set pin 5 high
              //postData();                                         // Call the HTTP POST function
            }

            cside_prev = msg_array[1];
            wd_Celap = 0;                                         // Reset elapsed time watchdog time value for C side.
            wd_Cside = millis();                                  // Last good heartbeat received from client device on C side.
          }

        rId[0]='\0';                                          // Clear the array
        break;

        case 6:
                                                                  // Examine string for EA status messages
        break;

        default:
          Serial.println("Default break encountered. Received gibberish.");
        break;

      }

    inputs[0][0] = '\0';                                      // Clear out this array element for the next message
    //client->stop();                                         // By default, kill the client session and just wait for a new TCP open
    //delete client;                                          // Remove client element's data
    //client = NULL;                                          // Reset to NULL
    Serial.println(inputs[0]);

    }

    else {

       if (strlen(inputs[i]) > MAX_LINE_LEN) {                     // Append it to the message content string, but first check for size compliance
        Serial.println("Max line length exceeded from client.");
        inputs[0][0] = '\0';                                       // Clear out this array element for the next message
       }
       else {
        size_t l = strlen(inputs[0]);
        inputs[0][l] = newChar;
        inputs[0][l + 1] = 0;
        // strcat(inputs[i], newChar);                             // Add character to the received string
       }

      Serial.print("inputs[0]: ");
      Serial.println(inputs[0]);

    }
  }

/* Update watchdog timers

wd_Delap = (millis()-wd_Dside);
wd_Celap = (millis()-wd_Cside);

if (wd_Delap>=60000)
      {
        Serial.print("Elapsed time on watchdog, D side: ");
        Serial.println(wd_Delap);
        Serial.print("Last message recieved: ");
        Serial.println(wd_Dside);
        digitalWrite(4, LOW);    // set pin 4 low
        Serial.println("Dside AV didn't hear from anyone in 60s; defaulting to OFF.");
      }

if (wd_Celap>=60000)
      {
        Serial.print("Elapsed time on watchdog, C side: ");
        Serial.println(wd_Celap);
        Serial.print("Last message recieved: ");
        Serial.println(wd_Cside);
        digitalWrite(5, LOW);    // set pin 5 low
        Serial.println("Cside AV didn't hear from anyone in 60s; defaulting to OFF.");
      }
  */
}

// Section to update database via HTTP
void postData() {
  Serial.println("Hit postData");
  client->stop();

  delay(250);
  Serial.println("Stopping and reconnecting.");

  if (db.connect(dbserver, 80)) {
    Serial.println("Connected to DB host machine.");
    db.print("GET /write_data.php?");

    db.print("RID=");
    db.print(rId);
    db.print("&");

    db.print("side=");
    db.print(avSide);
    db.print("&");

    db.print("state=");
    db.print("1");

    db.println(" HTTP/1.1");
    db.println("Host: localhost");
    db.println("User-Agent: Arduino/1.0");
    db.println("Connection: close");
    db.println();
    db.println();
    db.stop();

  }
  else {
  Serial.println("Connection failed to DB host machine.");
  }

  delay(5000);
}

This is the output:
Client's IP address: 192.168.1.77
Client sent: ,
inputs[0]: ,
Client's IP address: 192.168.1.77
Client sent: 3
inputs[0]: ,3
Client's IP address: 192.168.1.77
Client sent: ,
inputs[0]: ,3,
Client's IP address: 192.168.1.77
Client sent: 1
inputs[0]: ,3,1
Client's IP address: 192.168.1.77
Client sent: ,
inputs[0]: ,3,1,
Client's IP address: 192.168.1.77
Client sent: 3
inputs[0]: ,3,1,3
Client's IP address: 192.168.1.77
Client sent: ,
inputs[0]: ,3,1,3,
Client's IP address: 192.168.1.77
Client sent: 7
inputs[0]: ,3,1,3,7
Client's IP address: 192.168.1.77
Client sent:
Client terminated message.
R ID: 37
Dside AV is OPEN.
Hit postData
Connecting...
Connection failed to DB host machine.

Am I maybe initializing something incorrectly, or am I becoming a victim to one of the commonly references issues with the Ethernet library not being able to handle multiple connections on the Arduino?
Thanks!
EDIT:
Well with some troubleshooting of the HTTP methods and formats to address the URI, I didn't turn up much; But I did by chance notice that changing my semicolons to ampersands for the value fields are what did the trick! I have achieved communication to my MariaDB! The issue I'm having now is that the client disconnects after dumping the information to the database, and does not re-enter the normal loop to wait on another message.
My postData() routine above has been edited to show what I am doing. The main loop is looping, but does not show that the server() receives anything like it would previously.

Ethernet.begin(mac, ip); for IP 192.168.1.77 assumes gateway and DNS at 192.168.1.1. use "Host: 192.168.1.77". Is the port 80 open on firewall of the PC?

Can you reach port 80/send a POST from another machine on your network?

db.print("R ID="); there is a space inside your url. Urls shouldn't contain spaces.

@Juraj Are you referring to a specific function that the Ethernet() library implements? I don't see a Host parameter.

@MarkusDeibel you and Juraj's suggestions are good ones, as I couldn't access the web page without adding a rule for all port 80, 443 and 3306 traffic; however, the code is now stepping in and attempting to connect but locks up and restarts everything.

Host header in the request

Got the DB working! See edit above. My issue now is that the original server connection I have running to check for messages will no longer pick anything up after postData() is called!


text:
Problem with multi-client ASCII text parser (TCP)
I have been having a heck of a time getting my Arduino Uno Rev2 application to work as intended, which is to parse commands from multiple clients sending in ASCII-based commands over WiFi in order to control and read remote I/O from various I/O->ethernet servers.
The code compiles and runs, but it seems to be distributing my incoming client->read() character pulls across my full 2D array that I am calling inputs[][], which was intended to store the full contiguous message from a single client in one row of the array.
#include <stdlib.h>
#include <SPI.h>
#include <WiFiNINA.h>

char ssid[] = "***";                // House -- Network SSID (name)
char pass[] = "***";              // House -- SSID password (WPA2-PSK)

#define MAX_CLIENTS 5
#define MAX_LINE_LEN 50
char inputs[MAX_CLIENTS][MAX_LINE_LEN] = {0}; // Instantiate 2D array of
client/received data
int msg_array[] = {0,0};
int net_status = WL_IDLE_STATUS;              // The Wifi radio's status
WiFiServer server(80);           // Create server object on port of WiFi
                                 // server, which will be used to
                                 // respond to commands

WiFiClient *clients[MAX_CLIENTS] = {NULL};    // Create client objects
                                              // limited to size of
                                              // MAX_CLIENTS

byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xED}; // Arduino's physical MAC
byte ip[] = {192,168,9,25};              // IP of this controller
byte gateway[] = {192,168,0,1};          // Router address (internet)
byte subnet[] = {255,255,0,0};           // Subnet mask

unsigned long wd_Dside, wd_Cside = millis();   // Gather current tstamp
unsigned long wd_Delap, wd_Celap = 0;          // Create an elapsed time
                                               //counter

void setup(){

   pinMode(4, OUTPUT);                 // pin selected to control D SIDE
   pinMode(5, OUTPUT);                 // pin selected to control C SIDE

   //enable serial data print
   Serial.begin(9600);
   while (!Serial){
       Serial.println("No serial.");
   }

      Serial.println("Serial.begin was initiated.");

   if (WiFi.status() == WL_NO_SHIELD) {  // check for the WiFi module:
      Serial.println("Wi-Fi: Communication with NINA has failed!");
      // do nothing here
      while (true);
   }

   String fv = WiFi.firmwareVersion();
   if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
      Serial.println("Please upgrade the firmware");
   }

   while (net_status != WL_CONNECTED) {
      Serial.print("Attempting to connect to WPA SSID: ");
      Serial.println(ssid);

      // Connect to WPA/WPA2 network:
      net_status = WiFi.begin(ssid, pass); // Attempt to join this SSID

      // wait 5 seconds for connection:
      delay(5000);

      listNetworks();

      server.begin();                      // Start Wi-Fi server
      Serial.print("Server started on ");
      Serial.println(WiFi.localIP());
    }
}

void loop() {

    delay(5);

    WiFiClient newClient = server.available(); // Begin listening for
                                               // client messages
    if (newClient) {
        Serial.println("New client discovered."); // Could use this as
                                                  // an ACK/handshake on
                                                  // client-side host
        for (int i=0; i<MAX_CLIENTS; i++) {
          if (clients[i] == NULL) {
            clients[i] = new WiFiClient(newClient);
            break;
      }
   }
}

    for (int i=0; i<MAX_CLIENTS; i++){    // Check client for data
      if (clients[i] != NULL && clients[i]->available()){
              // If the data isn't garbage and the data is available..
        char newChar = clients[i]->read();         // Read the data

        if (newChar == '\0') {  // Check for termination char for separation
          char delimiters[] = ",";   // Parse to get command parameterization
          char* valIndex;
          valIndex = strtok(inputs[i], delimiters);
          for (int j=0; j < 2; j++){
            // Expand later to largest anticipated character count
            msg_array[j] = atoi(valIndex);
            Serial.print(msg_array[j]);
            valIndex = strtok(NULL, delimiters);
          }

          switch(msg_array[0]) {
          // Determine type of message received (Character 0 parsed as
          // Message Type)

            case '3':
            // Examine string for client cmds to turn sides on or off.
            if(msg_array[1] == '1')
            // Msg type 3, Instruction 1: Turn D side ON
              {
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '2')
            // Msg type 3, Instruction 2: Turn D side OFF
              {
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '3')
                // Msg type 3, Instruction 3: Turn C side ON
              {
                // Last good heartbeat from client device on C side.
              }
            if(msg_array[1] == '4')
                // Msg type 3, Instruction 4: Turn C side OFF
              {
                // Last good heartbeat from client device on C side.
              }
            break;

            case '6':

                // Examine string for another message type TBD
            break;

            default:
              Serial.println("Default break. Received crap.");
            break;

          }

        for (int m=0; m<2; m++){
        Serial.print("Characters detected as: ");
        Serial.print(msg_array[m]);
        }
        Serial.println();
        inputs[i][0] = '\0';
        // Clear out this array element for the next message
        // clients[i]->stop();
        // By default, kill client session, just wait for new TCP open
        // delete clients[i];
        // Remove client element's data
        // clients[i] = NULL;
        // Reset to NULL

        }

        else {

           if (strlen(inputs[i]) > MAX_LINE_LEN) {
                // First check for size compliance
           Serial.println("Max line length exceeded from client.");
           inputs[i][0] = '0';
                // Clear out this array element for the next message
           }
           else {
           size_t l = strlen(inputs[i]);
           inputs[i][l] = newChar;
           inputs[i][l + 1] = 0;
                // Add character to the received string
           }

          Serial.print("inputs[i]:");
          Serial.println(inputs[i]);
        }
      }
   }
}

I usually end up with the following output. This is from just one single device submitting the text ",3,2\0" over TCP. I try to tokenize the ",3,2" portion using strtok and then detect "\0" to signal the system to begin parsing the tokens. My apologies for utilizing the code box, but the quote box was not displaying it how I'd prefer:
Serial.begin was initiated.
Please upgrade the firmware
Attempting to connect to WPA SSID: ATT7YLd4JE
Server started on 192.168.1.98
** Scan Networks **
number of available networks:6
0) ATT7YLd4JE   Signal: -61 dBm Encryption: WPA2
1) DIRECT-F8-HP OfficeJet 4650  Signal: -62 dBm Encryption: WPA2
2) mocha        Signal: -87 dBm Encryption: WPA2
3) Scott        Signal: -92 dBm Encryption: WPA2
4) a5231978     Signal: -92 dBm Encryption: WPA2
5) LReusserWifi_EXT     Signal: -94 dBm Encryption: WPA2
New client discovered.
Client: 0
Triggered NULL client
inputs[i]:,
New client discovered.
Client: 0
Client: 1
Triggered NULL client
inputs[i]:,3
inputs[i]:,
New client discovered.
Client: 0
Client: 1
Client: 2
Triggered NULL client
inputs[i]:,32
00Default break encountered. Received gibberish.
Characters detected as: 0Characters detected as: 0
inputs[i]:,32,
inputs[i]:3
inputs[i]:,
New client discovered.
Client: 0
Client: 1
Client: 2
Client: 3
Triggered NULL client
inputs[i]:,32,2
30Default break encountered. Received gibberish.
Characters detected as: 3Characters detected as: 0
inputs[i]:,
New client discovered.
Client: 0
Client: 1
Client: 2
Client: 3
Client: 4
Triggered NULL client
inputs[i]:,32,23
inputs[i]:,
inputs[i]:,2
00Default break encountered. Received gibberish.
Characters detected as: 0Characters detected as: 0
New client discovered.
Client: 0
Client: 1
Client: 2
Client: 3
Client: 4
inputs[i]:,32,23,
inputs[i]:,3
inputs[i]:,2,
inputs[i]:2
00Default break encountered. Received gibberish.
Characters detected as: 0Characters detected as: 0

..and so forth. Is there a graceful way to confine all the data to one row of the array so I can proceed with parsing it as it should look? I feel like I'll need to store additional information coming from my targets, such as their MAC, so I know how to append each character to the appropriate row.
Thanks,
Hopeless

I am afraid server.available always returns the first client in 'connected' state. test it with WiFiChatServer example. Ethernet library has server.accept presented in AdvancedChatServer example.

If I could control the devices sending data, perhaps starting n number of servers across unique ports would resolve the issue?

does it always return the same first client? (I can't test it right now)


text:
How to fetch the com port or any id I can use to upload specific program to a specific arduino? e.g. "a.ino" to arduino micro
My project is a head mouse for which I am using two arduino boards . I want to upload a specific program to a specific arduino. How can I do it? And if I need to use a pid or com port id about which the official arduino forum people suggested, how can I retrieve this id? I'm using an Arduino micro and a pro micro if it helps any.
I need some suggestion on how to load the sketch to arduino through code without actually opening the arduino ide directly.Because it's a client project. And how can I make a specific program upload to the specific arduino one at a time. e.g. "a.ino" to arduino micro and "b.ino" to arduino pro micro. How should I identify the arduino boards through code.As for the OS, I am using Windows 10 64 bit.

What OS are you using?

I am using windows @majekno. And yes, I need some suggestion on how to load the sketch to arduino through code without actually opening the arduino ide directly.Because it's a client project. And how can I make a specific program upload to the specific arduino one at a time. e.g. "a.ino" to arduino micro and "b.ino" to arduino pro micro. Hpw should I identify the arduino boards through code.

done @jsotola. Please, help me solve it.


text:
Half-duplex for Atmel SAMD21
I'm using an Arduino MKR GSM 1400. I know this board uses the Atmel SAMD21 and the SAMD21 supports half-duplex (USART with full-duplex and single-wire half-duplex configuration). My question is, how can I configure one of the SERCOMs to use it as half-duplex (use one pin for rx and tx)?

what problem do you try to solve?

@Juraj So what is http://asf.atmel.com/docs/latest/sam0.applications.samba_bootloader.samc21_xplained_pro/html/asfdoc_sam0_sercom_usart_mux_settings.html ?

@Juraj "When TX and RX are connected to the same pin, the USART will operate in half-duplex mode if both one transmitter and several receivers are enabled."

so try it. the Arduino wrapper classes don't have clock pin configuration so you can't configure USART only UART.  so you must use registers or some other framework then Arduino

Up to six Serial Communication Interfaces (SERCOM), each configurable
to operate as either:

USART with full-duplex and single-wire half-duplex configuration
I2C up to 3.4 MHz
SPI
LIN slave

It is an error in the overview of the SAM D21 features in the datasheet. The SERCOM is half-duplex for I2C. USART can't be configured half-duplex.
see Application Note about SERCOM configuration

1 Introduction to Serial Communication Interfaces (USART, I2C, and
SPI)
... The exchange of data can be half-duplex or fullduplex depending on
the serial module specification. ...
1.1 USART
... It is full-duplex in operation. ...
1.2 I2C
... It is half-duplex in communication. ...

Is there anyway to configure USART as half-duplex?

Is there any library like https://github.com/nickstedman/SoftwareSerialWithHalfDuplex for SAMD21?

as I write in the answer. no

You can use USART in half duplex mode.
SERCOMx.PAD0 or SERCOMx.PAD2 are available for this. Refer to document "AT03256: SAM D/R/L/C Serial USART (SERCOM USART) Driver" section "10. SERCOM USART MUX Settings".
Below is a piece of code for ATXMEGA32E5, SERCOM0, PAD0. I am tested - it works:
Pull-up will help keep the line at 1 when the device’s transmitter is turned off and there is no other transmitter on the line, or it has not turned on yet. In the GPIO setup procedure:
// PA08 - SERCOM0/PAD[0]
PORT->Group[0].PINCFG[8].bit.PULLEN=1;    // Pull Enable
PORT->Group[0].PINCFG[8].bit.PMUXEN=1;    // Peripheral Multiplexer Enable
PORT->Group[0].PMUX  [4].bit.PMUXE=0x02;  // PMUX function C - SERCOM0/PAD[0]

In the SERCOM setup procedure, configure TX and RX on one pad:
while(SERCOM0->USART.SYNCBUSY.reg & 0x07) { ; }
SERCOM0->USART.CTRLA.bit.TXPO = 0x00;   // SERCOM PAD[0] Transmit Data Pinout
while(SERCOM0->USART.SYNCBUSY.reg & 0x07) { ; }
SERCOM0->USART.CTRLA.bit.RXPO = 0x00;   // SERCOM PAD[0] is used for data reception

If at the time of your transmission both the receiver and the transmitter are turned on at the same time, you will hear your echo.
When you get up for reception, do not forget to turn off your transmitter so that it does not interfere with reception:
SERCOM0->USART.CTRLB.bit.TXEN=0x00; while(SERCOM0->USART.SYNCBUSY.bit.CTRLB ) { ; }
SERCOM0->USART.CTRLB.bit.RXEN=0x01; while(SERCOM0->USART.SYNCBUSY.bit.CTRLB ) { ; }

Before transmitting, do not forget to turn on the transmitter:
SERCOM0->USART.CTRLB.bit.TXEN=0x01; while(SERCOM0->USART.SYNCBUSY.bit.CTRLB ) { ; }
SERCOM0->USART.CTRLB.bit.RXEN=0x00; while(SERCOM0->USART.SYNCBUSY.bit.CTRLB ) { ; } // If you don't want to receive your own transmission

Hope it helps.


text:
How to read CPU temperature into Arduino?
I'm not sure about this and if it is possible. I need to read CPU (normal computer) into an Arduino. This could be possible (at least I think) by connecting some kind of sensor that can be placed between the heatsink and the CPU, where the thermal paste is placed. Or, the second option is to read values from the system somehow, or from the motherboard. I hope I'm not talking about stupid things. I need some advice about this.

Your CPU almost certainly already has a temperature sensor built-in. You only have to find out how your OS makes this information available (and that is not an Arduino-related question). Adding an extra temperature sensor between the CPU and the heatsink is bound to degrade the efficiency of the heatsink.

As @EdgarBonet said, to place a sensor will affect your performance and still will not give you trustful readings. I believe the best way to monitor this parameter using Arduino is to access the temperature by running a script in your computer and pass it to Arduino via serial. Temperature reading is a BIOS feature and usually computers have it, but you may not have it also. You can take a look at this link to get some information about how to read temperature from your processor

you can safely place a sensor on the heatsink, as close to the contact area as practical.

Here is a simple way to send CPU temperature reading data via serial port, under Windows.
As answered in the question Batch-file get CPU temperature in °C and set as variable, it is possible to build batch file (*.BAT) to get the readings and output to console. I took following option and built the BAT file.
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature

Now, to redirect the console to serial port, use > symbol. Try following and receive it in your Arduino or use serial port monitor to check (in my case it works):
mybatfile.bat > COM1

Alternatively, you can use
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM1

inside your BAT file.
Next, we have to specify the serial configuration, make it EXE file so it can run under Administrative account. I used Advanced BAT to EXE converter. In the tool, specify the commands:
@echo off
mode COM1 BAUD=38400 PARITY=n DATA=8
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM1

Convert it to EXE using File->Build EXE...

And finally, you can create Scheduled Task to run your newly built EXE application periodically.
BTW, WMI is a powerful interface, it is possible to retrieve many other metrics and configuration data.


text:
Is an Arduino Uno made in the USA compatible with SunFounder shields?
I bought an Arduino Uno from Radio Shack. I was under the impression it was the authentic model made in Italy. I read on Arduino.cc that the USA version is licensed and essentially the same. I then went to Amazon and ordered an RBG shield, and what I thought was the starter kit that is used with the examples on the IDE. I received the package and it is from SunFounder. Will this work with the IDE on the website and the Arduino I have from Radio Shack?

Generally if the boards are individually functional and the two mechanically fit together, they will probably work.  The exception might be some 3.3v non-ATmega boards.   Mechanical issues can include different version of the shield interface with fewer or more pins, special function pin assignments that differ between a normal Arduino vs. a Mega, and the full-size USB connector on official-style boards shorting against the underside of some shields.

Use the latest official Arduino IDE : Arduino IDE
Every Arduino Uno and all the clones are compatible. Some clones have the CH340G usb-serial chip and require an extra driver. If you look very hard, you might find an Arduino Uno board that is not version 'R3' and does not have SDA and SCL near the USB connector, or does not have the polyfuse for USB 5V, or uses an ATmega328 instead of a ATmega328P. There is a chance of maybe 1 in 10,000 that you find a wrong Uno board, and in most cases those are still compatible.
Do you mean the SunFounder RGB Matrix Driver Shield? That should be no problem.

Yes the RGB Matrix Driver Shield, and thanks for the response.


text:
How do I sense that the serial monitor is started?
When starting the serial monitor in IDE I want to save important data to EEPROM before the Arduino Uno restarts. I do not have physical access to the Arduino so a "press button" solution does not work here.

You can't. There is no way of detecting if the serial monitor is open or not.
However, you can disable the automatic reset and provide some functionality in your code for saving data to EEPROM when prompted through a command entered on the serial monitor (if you now need to even save the data).

you did it again.  That is a very cool trick.  Thank you for teaching me that one.  I don't understand how the 120 Ohm value was figured out, but this is something I will put in my mental toolbox for sure.  Kudos.  Upvote.

What you really want to do is to store the data before the computer shuts down.
Here is what I did.
 I am running a Mega in a car and using it for a lot of things.  The Mega receives its power from the ignition switch.  When the ignition switch it turned on, the Mega boots up.  In the "setup" section of the program, I set a digital output HIGH.  The digital output is tied to the coil of a relay.  One side of the relay is tied directly to the battery.  Once the relay is energized, the relay supplies power to the Mega.  I have a digital input tied to the power coming from the ignition switch through a resistor and a zener diode to clamp the voltage at 5 volts.  In the main program I monitor the input power digital input.  When I see the power go down,(ignition switch is turned off), I run a Shutdown program that stores all of the data I need stored to the EEProm.  Once that is done, I set the digital output LOW.  This de-energizes the relay and removes the power from the Mega.  If you push the reset button, that is a hardware reset and you lose your data.  If I want to reset the computer, I simply run the "Shutdown" routine. I can do that using a remote switch that drives a digital input.

authors: Сергей Мясников

authors: حقائق واسرار

authors: مروان عبدالله


text:
ESP8266 Send data to Firebase using Arduino Uno error
Good day everyone! I have a project, in which the data from a button (number of clicks) will be sent to a real-time Firebase database. Every time the button is clicked the counter increases and will be updated in the firebase database.
Wifi Module:
Esp8266 Esp-01 + Esp-01 Adapter

In my understanding, there are 2 ways to use this wifi module.

Upload the code to the Arduino Uno and use AT commands in the module to send data to the web.
Upload the code inside the WiFi Module itself and after that it can be a standalone SOC and does not need the Arduino anymore after the code has been uploaded.

I have tried the second way, but I got confused and stuck. So far I have successfully plugged the adapter in a breadboard and tested some AT commands.
Since I will be using the second way I won't be using these. So I tried this code:
 #include <ESP8266WiFi.h>
 #include <FirebaseArduino.h>

 #define FIREBASE_HOST "https://duck-917ba.firebaseio.com/"
 #define FIREBASE_AUTH "r3jNQCsxN2Y2dcfawimRlzjLjdBSXLjstwGeyB0oMK"

 #define WIFI_SSID "mywifi"
 #define WIFI_PASSWORD "621533515"

const int  buttonPin = 8;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.setInt("clicks",0);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
      Firebase.setInt("clicks", buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(100);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;
}

So I have plugged my 4-pin adapter to the following:

ARD(TX)-ADAPTER(TX)
ARD(RX)-ADAPTER(RX)
ARD(5V)-ADAPTER(VCC)
ARD(GND)-ADAPTER(GND)

I have set the Generic ESP8266 Module Board.
Problems Encountered:
I am supposed to select the port of the ESP8266 but I only see the Arduino UNO port in the port list. When I compile the code I get this error:

I am now confused on what the error is all about. I thought since I am using an adapter I can use the PROGRAMMING MODE of the module easily. But it seems like my adapter is not doing its job. According to some of my research I have to use  TTL or FTDI USB-to-serial dedicated module / Ground some wires while compiling which is very confusing for a beginner like me.
So here are my final thoughts:

Can I input/flash code in my module using my Arduino and adapter?
Since the button is plugged in the Arduino's pin 8, does that mean that the code in the module will be successfully inserted? I will still need the Arduino to be plugged in the buttons?
What could be the reason why the module won't appear in the Port List and generates the errors?

I know this is quite a long and boring topic but I know a lot of aspiring IOT developers out there are having the same issues about this wifi module. I hope we can solve it together. Thanks!

You will get all info at below link.. try it.. https://www.diyhobi.com/flash-program-esp-01-using-usb-serial-adapter/

1.) Can I input/flash code in my module using my arduino and adapter?

Yes

2.) Since the button is plugged in the pin 8 of arduino. Does that mean If the code in the module will be successfully inserted. I will still need the arduino to be plugged in the buttons?

The ESP8266 cannot magically know about the Arduino and the Arduino cannot magically know about the buttons. If you have buttons connected to the Arduino then the Arduino needs telling about them. If the Arduino and ESP8266 need to work together then they both need programming to work together. If, and only if, you connect the buttons to the ESP8266 and not the Arduino do you not need the Arduino.

3.) What could be the reason why the module won't appear in the Port List and generates the errors?

The Arduino is getting in the way. Connect Arduino RESET to Arduino GND to disable the ATMega328p chip which is also trying to use TX and RX and conflicting with the ESP8266. Or better still get a cheap USB to UART cable (just a couple of dollars on eBay) and connect the adaptor direct to your PC without the Arduino.

Thank you for the response. Like you said I tried to put the RESET to GND in the arduino. I tried to tweak my adapter so that the connection would go like this and enter programming mode: ARD(TXD)-TXD, ARD(RXD)-RXD, CH-PD&VCC TO 3.3V, RESET&GND&GPIO0 TO GND, GPIO2 unplugged. But unfortunately when I try to upload the Arduino UNO/ COM12 still appears on the port list and it seems like my module cannot be read in the arduino port list for some reasons.

It sounds like you are expecting your module to appear separately on the computer. It's not the module that is connected to the computer, it is the Arduino that is connected to the computer. It is the Arduino that you will always see.

I see. I ordered an USB to UART cable online and would arrive in a couple of days. So in my understanding I will have to plug my module+adapter in the uart device and plug it in my computer so I can start programming directly inside the module without the need of arduino? Incase I successfully uploaded my code in the module I can use it in boot mode and use it with the arduino? To sum it up plug in UART(programming mode), plug in Arduino(Boot Mode)? Thank you for helping me

Sure. As long as both the Arduino and the ESP8266 have been programmed in such a way that they will work together. And that doesn't mean using AT commands since the ESP8266 would no longer understand them.

Connect GP00 to ground
This is required to flash ESP8266


text:
Use Arduino Uno digital pins instead of ESP8266
I would like to know if this is possible.
I am using an ESP8266-ESP01, which only has 2 digital pins. I have a project that needs 3 digital pins so I have planned to use my Arduino, so I can use more digital pins. My plan is instead of plugging the sensor in the GPIO1 of the ESP8266, I could somehow plug it in the Arduino digital pins and the data would just be transferred to the ESP8266 and be uploaded to an online cloud.
I can read the sensor data in the Arduino but I don't know how to transfer the data to the ESP8266 so the wifi module would just receive it and send it to the online cloud.
If anyone can help me to get some idea specifically on sending the data from Arduino to the ESP and receiving the data from the Arduino.
Thank you.

There are numerous tutorials on how to use an Arduino with an ESP8266. What did you try and how it didn't work?

In order to attract the most useful answers it is best to lay out your solution, what you have tried (including code) and the pose a specific, clear question about where you got stuck, related to Arduino.  Feel free to edit this question to include that and then we'll see what happens.

I did made a recent question with all what I did and codes and all but my question just got ignored so maybe if I make a simpler question people will answer. anyway this is what i have tried https://arduino.stackexchange.com/questions/44608/dht11-data-in-arduino-uno-to-firebase-through-esp8266

DDA's answer is perfectly correct.
Like he says you need to check the voltage and use a logic level shifter.
However looking at it from another angle there are a whole range of ESP that have an increasing number of digital pins.  You could look at using an ESP-5, or an ESP-12E, these have different forms and increasing number of digital pins.
You could also look at the Wemos range, I believe there is an UNO form board and there is the Wemos D1-Mini, which has 10 digital and 1 analog.
Running on two boards is usually more of an issue than running on one board, god help you if you have synchronisation issues!

Use the ESP's two digital pins to talk to the Arduino using SoftwareSerial. Be careful however: your Arduino (possibly, probably) runs on 5V, the ESP on 3.3V. I have an Arduino clone that can be switched between 3.3V and 5V, which makes things easier.
After that all you need is to send the sensor readings to the ESP via SoftwareSerial.

I could somehow plug it in the Arduino digital pins and the data would just be transferred to the ESP8266

Easy:

Program the Arduino as a master (I2C, or UART + interrupt) and the ESP as a slave. Connect the sensors to it. Once the data is read on the Arduino, it is sent to the ESP.
Put an I2C IO expander IC on the ESP and you don't have to deal with the Arduino at all.

Using I2C is a good idea but on an ESP-01 because there are only two lines there is a possibility that an I2C device may put the ESP into "flash mode". If you are using an I2C device that write to the microprocessor then there is a higher chance of this happening.  HOWEVER there is only a small chance of it happening, it will depend on you hardware and devices, etc (i.e. it probably won't happen, but...)


text:
Receiving incomplete HTTP request
I have an Arduino project that needs to receive data from ThingSpeak. This is the data that I'm supposed to get.
When the data is "true" it must turn the LED on. I tried this code in hope of getting "true".
void loop() {
  Serial.println();
  Serial.println("Receiving Trigger Data...");
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    client.println("GET /channels/344468/fields/3/last?key=XXXXXXX HTTP/1.1");
    client.println("Host: api.thingspeak.com");
    client.println("Connection: close");
    client.println();
}
while (client.available()) {
  reply = client.read();
  content.concat(reply);
}
delay(3000);
Serial.println(content);
if(content.indexOf("Content-Length: 4") > 0) {
  digitalWrite(ledPin, HIGH);
}

The Serial Monitor gives this reply. I don't see the word "true" being returned at all and I don't also see the content length. I tried putting delays but still I don't receive the "true" or even just the content length. Please help.

available() is non blocking. network is not so fast. at the first gap you stop reading

I think you can to use client.connected() to determine whether there is still data coming in (since you are sending the Connection: close header).

Thank you very much. I changed available() to connected() and it worked properly now.


text:
Servo motor and the servotimer2
I posted this a few days ago
Servomotor and music shield
and now I moving my servo motor and my musicshield (seeduino musicshield v2.0) together with and Arduino uno, in my other post they told me to put the library ServoTimer2 because I was having a conflict with the two libraries(the servo.h library and the musicshield library).
And I'm having a lot of trouble with the servotimer2 library, at first didn't work,  it gives me always this error:
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:117:14: error: conflicting declaration 'typedef bool boolean'
typedef bool boolean;
but I read that if I erase the //typedef uint8_t boolean; in the ServoTimer2.h It will be working. So I did it, and it works somehow.
Now, the musicshield is playing the songs and the servomotor is moving, but is not moving "properly" I mean it moves so little like 10° and moving back and so on, the servo motor is not moving the 90° or stopping the time I want it to stop.
I don't know if it's the code, I search and the servo.h and the servotimer2 library change only in the way you define your servo and pin.
So I tried this without the musicshield and it didn't work either, in this case the servomotor make some noise like a clock like tic, tic, tic, but don't move
#include <ServoTimer2.h>

ServoTimer2 servoNine;

int val;//for the servo

void setup() {
  servoNine.attach( 9 );

 }
void loop() {
val = 0  ;// start point
servoNine.write(val);
delay(100);

val = 90 ;//
servoNine.write(val);
delay(100);//

}

so, I think the problem is the code. The servomotor is not broken I tested that, with the normal servo.h and the same code and it's moving properly
#include <Servo.h>
Servo myservo;
int val;

void setup() {
  myservo.attach( 9 );
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
val = 0;//
myservo.write(val);
delay(100);

val = 90;//
myservo.write(val);
delay(100);
}

it moved! I runned the  example program and my servomotor it's behaving properly now,is an adaptation from the three servos example
the code I'm using is this
#include <ServoTimer2.h>  // the servo library

// define the pins for the servos
#define rollPin  9

ServoTimer2 servoRoll;    // declare variables for up to eight servos

void setup() {
  servoRoll.attach(rollPin);     // attach a pin to the servos and they will start pulsing

}

// this function just increments a value until it reaches a maximum
int incPulse(int val, int inc){
   if( val + inc  > 2000 )
      return 1000 ;
   else
       return val + inc;
}

void loop()
{
 int val;

   val = incPulse( servoRoll.read(), 1);
   servoRoll.write(val);

   delay(10);
}


text:
Servomotor and music shield
I’m trying to make an art sculpture, with an Arduino-uno, a servomotor and a seeduino musicshield v2.0.
I’m making the servo motor moving a stick with the attached fans of the servo, and I want to  synchronize the servo motor with the music shield  and when the motor is stopped(about one minute), the music(about one minute of music) will play and when de motor is moving the music will be stopped.
I'm super noobie with the code. I tried something like this
but, is not moving at all, neither my servo or my musicshield  when I write this:
#include <SD.h>
#include <SPI.h>
#include <arduino.h>
#include <MusicPlayer.h>

#include <Servo.h>
Servo myservo;

int val;//for the servo

void setup() {
  //setup for the music shield
  Serial.begin(9600);
  player.begin();  //will initialize the hardware and set default mode to be normal.
  player.addToPlaylist("a.mp3");
  //setup for the servo
   myservo.attach( 9 );
}
void loop() {
  mover();
  if ( val == 90) {
    music();
  }
}

void mover () {
  val = 0;// start point
  myservo.write(val);
  delay(800);

  val = 90;
  myservo.write(val);
  delay(60000);//wait for 1 min
}

void music () {

  player.play();
}

when I write this my servo moves, but obviously my music wouldn't play
#include <SD.h>
#include <SPI.h>
#include <arduino.h>
#include <MusicPlayer.h>

#include <Servo.h>
Servo myservo;

int val;//for the servo

void setup() {
  //setup for the music shield
 Serial.begin(9600);
  player.begin();  //will initialize the hardware and set default mode to be normal.
  player.addToPlaylist("a.mp3");
  //setup for the servo
   myservo.attach( 9 );
 }

void loop() {
mover();

 }

 void mover () {
val = 0;// start point
myservo.write(val);
delay(800);

val = 90;//
myservo.write(val);
delay(60000);//wait for 1 min
}

void music () {

  player.play();  //do some leisurely job
}

And the music will play when I write this, obviously the servomotor don't move, so I'm  think I have a problem mixing my servomotor and the musicshield(seeeduino music shield v2.0, and I want the music start when my servo motor is in this point of val=90 delay(60000)
 #include <SD.h>
    #include <SPI.h>
    #include <arduino.h>
    #include <MusicPlayer.h>

    #include <Servo.h>
    Servo myservo;

    int val;//for the servo

    void setup() {
      //setup for the music shield
     Serial.begin(9600);
      player.begin();  //will initialize the hardware and set default mode to be normal.
      player.addToPlaylist("a.mp3");
      //setup for the servo
       myservo.attach( 9 );
      }

    void loop() {

   player.play();
     }

    void mover () {
    val = 0;// start point
    myservo.write(val);
    delay(800);

    val = 90;//
    myservo.write(val);
    delay(60000);//wait for 1 min
    }

with is not working I mean is not moving at all, neither my servo or the music, but when I compile I don't have any mistakes messages

Break the problem down into pieces. First get the servo working without the distraction of the music. Then get the music working without the distraction of the servo. Then combine them. Does the servo work when you write a simple program to move it?

yes, the servo is moving without the musicshield, and the musicshield is working without the servo, I'm having trouble combining both of them

That is very useful information. Could you edit it into your question please?

yes, of course, thank you for helping me, I'm noobie at making questions too

If you use two shields (libraries and such) and each single one is working and together they are not, the most common problem is, that they share something (usually some pin for shields or interrupt for libraries) and do fight over that.

so, I have to search for that something that they're sharing and change it? or is more like they are not going to work together and I need to find another way?(and thank you it was very useful information)

When you say the music wouldn't play in the first case, you did wait the full 1 minute for it to start right?

Is this the MusicPlayer.h that you have?  https://github.com/Seeed-Studio/Music_Shield
From the description it says:

The music player reads data from SD card and then feed into the VS1053 chip via SPI bus. This is done in TIMER1's ISR with a interval of 2ms. This job has a high priority and uses the cpu exclusively. In the spare cpu time, player does some process control, like play/pause.

That's the same timer that Servo.h uses.  So the two libraries are not compatible.  You could try using ServoTimer2 library or rewriting this library to get the 2ms timer with Timer 2.

thank you, yes that's my musicshield, I think I will try the ServoTimer2


text:
Send JSON via POST on SIM900 shield with AT commands
I'm trying to send a JSON POST in SIM900 shield with AT commands. After I call the  AT+HTTPACTION=1 command, it returns a 601 error: +HTTPACTION:1,601,0.
I saw here that the error was 601 Network Error. Could someone help me? Following is my code.
void connectInternet() {
  if(digitalRead(9 != LOW)) {
    Serial.print("\r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print(" CONNECT ON INTERNET \r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print("\r\n");
    Serial.println("Connecting...\r");
    cmdAT("AT");
    cmdAT("AT+CIPSHUT");
    cmdAT("AT+CIPMUX=1");
    cmdAT("AT+CSTT=\"zap.vivo.com.br\",\"vivo\",\"vivo\"");
    cmdAT("AT+CIICR");
    cmdAT("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
    Serial.print("IP Device: ");
    cmdAT("AT+CIFSR");
  }
}

void send2Api() {
  Serial.print("\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print(" SEND TO API\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print("\r\n");
  cmdAT("AT+CSQ");
  cmdAT("AT+CGATT?");
  cmdAT("AT+SAPBR=2,1");
  // Query if the connection is setup properly, if we get back a IP address then we can proceed
  cmdAT("AT+HTTPPARA=\"CID\",1");
  // Set the HTTP session.
  cmdAT("AT+HTTPPARA=\"URL\",\"http://api.com.br/endpoint\"");
  // set endPoint
  cmdAT("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  // set content json
  cmdAT("AT+HTTPDATA=100,5000");
  // POST session start
  // JSON payload
  cmdAT("{\"timestamp\":\"2016-03-08T19:36:45.000Z\",\"latitude\":\"-24.9458581\",\"longitude\":\"-53.4968357\"}");
  delay(100);
  cmdAT("AT+HTTPACTION=1");
  // POST session start
  cmdAT("AT+HTTPREAD");
  // Read the data of HTTP server
  cmdAT("AT+HTTPTERM");
  // terminate http
  ShowSerialData();

Check out this. Hope it helps:)

The PDP context setup is missing from your code. I.e. you have to set up a connection to the GPRS APN what your GSM network provider gives to use as a gateway to the Internet.

Ok @Gee Bee. So, I don't need call my function connectInternet().
Should I define the PDP in send2Api() function ? Thanks

The PDP context setup is missing from your code. Many years ago I figured out that this initialization sequence works (i.e. extend your connectToInternet):
        //--if autobauding was enabled, send a blank AT
        command:='AT';
        send_gprs;

        //--switch to minimal mode - this is required to reset the SIM card
        command:='AT+CFUN=0';
        send_gprs;

        //--set dce speed
        command:='AT+IPR=57600';
        send_gprs;

        //--turn off command echo
        command:='ATE0';
        send_gprs;

        //--turn off command echo again - sometimes the first command is ignored
        command:='ATE0';
        send_gprs;

        //--turn on extended error messages
        command:='AT+CMEE=1';
        send_gprs;

        //--set module to full function
        command:='AT+CFUN=1';
        send_gprs;

Then it is very important to unlock your SIM card. The simplest solution is to disable PIN request (put your SIM to a real phone, and use the phone to set up this.) Verify if the module can proceed on SIM authorization:
        //--check pin
        command:='AT+CPIN?';
        send_gprs;
        //--right answer is +CPIN: READY
        //--wrong answer is +CME ERROR: 772

Then set up the APN. This will actually initiate an asynchronous APN request, and you shall not proceed until the AT+CSTT returns OK:
    repeat
        //--reset connection
        command:='AT+CIPSHUT';
        send_gprs;

        //--set GPRS APN
        command:='AT+CSTT="internet.vodafone.net"';
        send_gprs;
    until is_ok=1;

And finally, open a GPRS connection:
    repeat
        //--Open gprs connection
        command:='AT+CIICR';
        send_gprs;

        //--Get local address - for some reason this is required
        command:='AT+CIFSR';
        send_gprs;

        //--Suppress "SEND OK" after at+cipsend
        command:='AT+CIPSPRT=2';
        send_gprs;

    until is_ok=1;

(Ok sorry, this code is pascal and not especially golden, but you got the point about the sequence of the commands.)
Two very important things:

any command can fail - it is a good idea to send back the response to an AT command to your console window
AT+CIFSR is evil. If you don't use AT+CIFSR at the right sequence, the communication simply does not work. I was using SIM900D modules. Although you might feel it is optional to get your IP, actually it is not optional at all for some reason.

I was using AT+CIPSEND for the actual data communication. HTTP is so easy, and it is better to be in control.