text:
String matching serial input (was Code for voice recognition for arduino uno)
#include <SoftwareSerial.h>// import the serial library

SoftwareSerial Genotronex(10, 11); // RX, TX
int ledpin=13; // led on D13 will show blink on / off
int BluetoothData; // the data given from Computer

void setup() {
  // put your setup code here, to run once:
  Genotronex.begin(9600);
  Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
   if (Genotronex.available()){
BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
   digitalWrite(ledpin,1);
   Genotronex.println("LED  On D13 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
  digitalWrite(ledpin,0);
   Genotronex.println("LED  On D13 Off ! ");
   }
}
delay(100);// prepare for next data ...
}

can anyone help me how to write the sketch for voice recognition of the    above code.
I'm using AMR/BT voice control app`for voice recognition.

Third time asking? Third new user? We don't have a clue what this "AMR/BT" thing is you're on about (or I certainly don't, and neither does Google, so there's no hope for anyone else).

Its an app. Voice recognition app. So i want to add speech recognition to my above code. And also I'm using bluetooth HC-05

How does the app work? What does it do? How does it interface with an Arduino?

Its there in the Google play store.. search for BT voice  control

No, I won't. You tell us, by enhancing your question, what it is, what it does, how you use it, and how you expect to use it.

It's a voice recognition app which we speak to the microphone. And then it will convert the voice into text and send it to arduino through bluetooth. so i want to above sketch to be controlled by voice.

So you want the arduino to be controlled by some unspecified stream of serial data? (that just happens to be generated on an app and delivered via bluetooth....)  What would the stream look like?  "Ari on"  "Ari off" ?

Yeah may be like Lights On , Lights off

... As far as the arduino would care, it sounds like it would all be serial dat, and the voice recognition is irrelevant.  What's the question? And what's with the "press 0 or 1..." do you mean "say 'zero' or 'one'..." ?

Inplace of pressing 1 0r 0 i want speech to text...which means i will give a command lights on or light off

If you tell us what your mystery app sends to the Arduino we can help you craft the code to interpret that data. Until you tell us that simple basic bit of information we cannot help you.

Alright...the app is like google tap/ google voice search

Put https://www.arduino.cc/en/Tutorial/SoftwareSerialExample on your arduino, hook up your bluetooth, talk to your app, and watch what it prints in the serial monitor.

Does http://arduino.stackexchange.com/a/3978/6628 help?

Forget it - an Arduino is neither capable of performing voice recognition itself, nor  a reasonable choice for collecting audio data on behalf of some remote compute service which is.

Please stop creating new accounts to ask the same question.

Your question is not very specific.
But, I think your talking about the AMR_Voice application for Android, and your trying to use the HC-05 BT to connect to your cell. I hope I'm right in my guess, and funny enough, someone over at Instructables did exactly the same thing.
Arduino Voice recognition Via Bluetooth HC-05 - http://www.instructables.com/id/Arduino-Voice-recognition-Via-Bluetooth-HC-05/
Hope this helps!


text:
int not declared in this scope
This posting contains 2 sketches. the analogmux1 compiles successfully. Concerning analogmuvvolts sketch an error stating updateMux1 was not declared in this scope results. The int Mux1_State [8] = 0: is defined exactly the same in both however the error results.
I'm learning Arduino programming so there are other errors in the sketch. What I'm trying to accomplish is to display the actual voltage of each channel, not numbers which appear in the analogMux.
It would be appreciated if the community could provide me with some guidance.
Analogmux:
int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};

void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  //pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
  updateMux1();
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
    }
  }
}

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}

And  analogmuxvolts
int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};
//float Mux1_State[i] =0;
int RawValue=0;
float Voltage = 0;
void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
  Serial.print("Raw  Value = " );
  Serial.print(RawValue);
}

Is updateMux1() not in the second sketch?

The error is updateMux1' was not declared in this scope and indeed that function is not in the second sketch.

Declare the updateMux() function by copying it from your first sketch into your second sketch:
void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}

And do the conversions on the stored Mux1_State[] values during printing like:
  for(int i = 0; i < 8; i ++) {
    Serial.println(Mux1_State[i]*5.0/1024.0);
    if(i == 7) {
       Serial.println();
    } else {
       Serial.print(",");
    }
  }

I appreciate your help Dave.    Tom

source: Stack Exchange

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

sort: votes


text:
Efficient workflow/tools for converting color images to hex arrays
I would like to display 65k color animated gifs on my oled. I'm using the adafruit library for https://learn.adafruit.com/096-mini-color-oled
Now I need to convert a significant number of images to hex arrays. I found a couple of tools that can deal with monochrome images and I found this: https://www.digole.com/tools/PicturetoC_Hex_converter.php which might work for individual images, but is impractical for batch processing. I also found this, but it appears to also be intended for individual images and doesn't simply work in wine. So isn't there some linux commandline magic to do that?

You could have a look at ImageMagick. I think you want to export the image as RGB565 format. This will give you raw bytes. So you can use, for example, xxd to convert this to hex. Not sure what you mean with hex array.

your question is not about the arduino, so it does not belong here .... it may be a better fit at https://softwarerecs.stackexchange.com/

@jsotola "Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino." - my question is about how to convert graphics to an arduino compatible format to use in programming it. IMO it's covered under questions regarding "software that is compatible with Arduino". WIth that being said, I already got my answer.

I found this plugin to be satisfactory: https://khalim19.github.io/gimp-plugin-export-layers/
It's not a single elegant command, but is quite fast and maybe can be optimized with some scripting.

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


text:
Arduino / BitVoicer Sending IR code on loop
I was designing a voice automated kitchen lighting system. I have led strips under the cabinets which are remote controlled by an IR remote, so I captured the IR codes and got an IR led to turn them on. Now I introduced BitVoicer so that I could use voice commands to control the LED. I have ran into the issue that the IR led keeps turning the lights on and off, but my IR codes worked prior to using BitVoicer.
Here is my arduino code:
#include <BitVoicer11.h>

int IRledPin = 13;

BitVoicerSerial bvSerial = BitVoicerSerial();

void setup()
{
 Serial.begin(9600);
 pinMode(IRledPin, OUTPUT);
}

void loop()
{
  bvSerial.getData();

  if(bvSerial.strData == "")
  {
    return;
  }

  if(bvSerial.strData == "wake")
  {
   LightOnCode();
  }
}

  void pulseIR(long microsecs)
   {
     cli();

     while (microsecs > 0)
      {
        digitalWrite(IRledPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(IRledPin, LOW);
        delayMicroseconds(10);

        microsecs -= 26;
      }
     sei();
    }
   void LightOnCode()
{
  pulseIR(8940);
  delayMicroseconds(4380);
  pulseIR(520);
  delayMicroseconds(600);
  pulseIR(520);
  delayMicroseconds(560);
  pulseIR(560);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(560);
  pulseIR(540);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(580);
  pulseIR(540);
        delayMicroseconds(1660);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1660);
  pulseIR(540);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(500);
  delayMicroseconds(1680);
  pulseIR(540);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1660);
  pulseIR(540);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(560);
  pulseIR(560);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(600);
  pulseIR(500);
  delayMicroseconds(580);
  pulseIR(540);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(540);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(540);
  delayMicroseconds(1660);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1640);
  pulseIR(580);
  delayMicroseconds(1660);
  pulseIR(520);
  delayMicroseconds(1660);
  pulseIR(560);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(520);

}

If anyone could answer my question as to why the led keeps sending extra signals I would appreciate it! If you have any questions don't hesitate to ask!

Taking a quick look at the Documentation on page 22, it looks like you need to use your bvSerial.strData calls within a function called void serialEvent() rather than inside of your loop.  I would recommend trying out their tutorial on that page just to make sure you get BitVoicer to work properly before scaling it for your application.
Hope that helps!

Sorry for the late reply, but thank you very much! I will try and mess around with it more tonight and post an update on the progress!

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


text:
I would like to retrieve data from a MySQL database using PHP using HTTP requests, on my Arduino
Please help me find a way to do it.
I have looked at the following for sending data Arduino to MySql
But can't seem to find visa-versa.

What actions have you taken yet? What does/doesn't work?
Is the connection between arduino/php website working or is the problem at php<-mysql

Sure, why not. If interested let us know a time frame, any of us here would deliver you the way, and quote you accordingly.

Point is that i forgot to check the date of the question, :D replied to a 2yr old question.

You could develop a REST based service, to make Arduino consume web service using the aRest library.
Following is a tutorial of how to use the aRest API with Arduino: A REST API for Arduino & the CC3000 WiFi Chip.

There are two things you have to set up for this:
1. Retrieving/parsing websites from your Arduino.
2. Making a dynamic website using PHP (and MySql).

Try to set up your Arduino as a WebClient, check if you can retrieve a website like google.com or a minimalistic website.
Try to get your arduino to interpret a string or retrieve values from that website. (I.E: retrieve the day/time from the HTTP message)

IF your arduino can retrieve webpages, you're halfway there (somewhat). And your project is running out of the scope of this arduino.stackexchange.
Now you're going to have to create a dynamic website. You can let PHP reach for values from your MySql database (you should just use a text file first) and display them on your site (in HTML).
Your Arduino can now poll your website, to get the HTML content and parse it to the values.


text:
HC-05 Bluetooth Module - INQ-Command doesn't work
For a project I need to connect a Bluetooth Remote control with an Arduino Nano.
The Problem
I am trying to setup a connection to said Bluetooth remote Control. This device is visible! (I have confirmed it with a smartphone)
Here are the steps that I am trying to do with the Arduino and HC05 module:
AT <-- confirms, that Command Mode is running successfully
OK

AT+ROLE? <-- 1 For Bluetooth Master Mode
+ROLE:1
OK

AT+CMODE? <-- 1 allows connecting to any BT address
+CMOD:1
OK

AT+INQM? <-- Show Inquiry access values
+INQM:1,1,48
OK

AT+INQ <-- Inquiry Bluetooth Device

After ~60 seconds, it just says "OK", but according to this tutorial  or according to this youtube video it should display all Bluetooth-devices, that are ready to connect.
The BT device is definately visible. (I tried multiple BT devices like smartphones and peripheral devices).
Why is the inquiry not working? What is wrong here?
The circuit is exactly like in this picture:

For setting up the Bluetooth-connection I wire the EN-Pin to +3,3V, which successfully activates AT-Command-Mode
According to this site, you can do it like that.
Here is my code, that I use, to communicate with the module. - It works good!
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
//

char c = ' ';
int buf[64]; //buffer to store AT commands
int len = 0; //stores the length of the commands

void setup()
{
    Serial.begin(9600);
    Serial.println("Arduino is ready");
    delay(500);
    mySerial.begin(9600);
    Serial.println("BlueTooth is ready");
}

void loop()
{

  if(Serial.available())
  {
    len = Serial.available(); //store number of bytes to read
    for(int i = 0; i<len; i++) //store all bytes into the buffer
    {
      buf[i] = Serial.read();
    }
    for(int i = 0; i<len; i++)
    {
      mySerial.write(buf[i]);
      Serial.write(buf[i]);
    }
  }

  if(mySerial.available())
  {
    len = mySerial.available();
    for(int i = 0; i<len; i++)
    {
      buf[i] = mySerial.read();
    }
    for(int i = 0; i<len; i++)
    {
      Serial.write(buf[i]);
    }
  }

}

Here is a related question but the answer doesn't help.

I did a factory reset of the device. That resolved the issue
AT+ORGL
AT+RESET

Another thing that is very important: The KEY-Pin (EV-Pin on some boards) must be HIGH (3Volts), during the INQ-command. If this PIN is not High, the inq-command will not work.
If you put 3V to this PIN and release it, you indeed are in AT-Command mode. But not all AT-commands work (e.g. the said at+inq command). If you want to enable all AT-commands the PIN must remain high.

Try this example from the datasheet:
AT+INIT
AT+INQM=1,9,48  // max of 9 devices, timeout of 61 seconds
AT+INQ

And use this in your loop() instead:
void loop() {
  while (Serial.available())
    mySerial.write(Serial.read());
  while (mySerial.available())
    Serial.write(mySerial.read());
}

Tried it, but this does not work, either. This command only changes the maximum devices, that can be found by the module. but since not a single one is found it doesn't help.


text:
Using a Hot Wheels Radar Gun with FreqPeriod library
I want to make a clone of those radar enforcement signs that look like this:

I bought a Hot Wheels Radar gun that can send an analog signal to determine speed.  See this thread:  http://forum.arduino.cc/index.php?topic=145063.msg1889312#msg1889312
From FreqPeriod's documentation, it has the following comment in the code:
connect pin 5,6,7 to input circuit
Question is -- how do I wire up the radar gun analog signal wire to the arduino to successfully use FreqPeriod?

What makes you think that the FreqPeriod library has anything whatsoever to do with this...?!  5 seconds reading that thread and the link to the project within it and I already know that FreqPeriod is NOT what you want to be using. Go do some more reading.

The post below the one I linked to included a working sketch, rigged up the the guts of the hot wheels radar gun. There are a few in the forums that have used that sketch to get speed using FreqPeriod.  I just need help figuring out how to wire it up.

Ignore the forum, most of that is talking gibberish. Instead read the project page. The code linked to by the forum thread is for something entirely different. For the hotwheels it gives an analog signal that you just read with analogRead(). FreqPeriod is used if you are building your own doppler circuit and doing the work in the Atmel. The hotwheels one does the work in external hardware and just gives you an analog voltage. Or that's what the project page says.


text:
Why won't processing not communicate with Arduino uno?
I downloaded the Processing language and ran the "Hello World" program to test it. The message appears in the Serial console but not on the Processing console. It prints "null" only. I am using the code supplied by Sparkfun. Other people have had this problem. I am looking for clear explanation and solution.

What code? What sketch? What what?!

I apologize for presenting a vague question. I was unable to successfully run the simple code to learn "serial communication" presented by Sparkfun on: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing.
Step 1. Run Arduino to produce "Hello, World" on the Serial Port.
Step 2. Run Progressing 3.0.1 to produce "Hello, World" on its console.
The code from the website are copied and pasted onto my iMac running El Capitan. I received an error message for Step 2 stating the "port is busy."
Once I closed the Arduino (Step 1) and compiled and ran Step 2, it worked!
Several other people found different solutions. My solution is simple. Run one program at a time.

You had both the serial monitor and the processing application running at once? No wonder it didn't work - the serial monitor was using the serial port so the processing application couldn't get at it. Only one thing can read from the serial at a time - you choose which: the serial monitor or the processing application.


text:
Gesture sensing TV coffee table - what sensors would you use?
A 32 inch flat screen was embedded in a coffee table and covered by a protective layer of glass. Sensors around the edge of the glass surface need to be able to detect the precise location of an object on the glass so that a mouse cursor can be controlled with a stylus.
What sensors would you use to ensure accuracy of stylus location above the screen?

"precise" doesn't mean much - you should be more specific and define the desired spatial resolution: what is the minimum distance you need to discriminate?

Perhaps I didn't state a level of accuracy because I wanted to encourage a wider range of replies @igorStoppa. Unfortunately this also encourages your not very helpful reply. A minor side effect.

The helpfulness of the replies you receive is correlated to the precision of the questions you ask. If you are open to a wide range of options, you should say so, instead of intentionally asking vague questions, hoping that they will bring a variety of solutions. My previous reply was meant to show you how to ask better question.

It sounds like you want a glass capacitive touch screen like on a tablet.  While you can get them this large, you usually have to buy the monitor already integrated with the capacitive touch screen.  I have never seen it were people add the capacitive touch screen afterwards.

Perhaps if you drop the monitor an inch or 2 away from the glass you can use a Frustrated Total Internal Reflection (FTIR) IR scheme.  But at that shallow angle it will be tricky and may require several cameras around the edges.

added later...
Should mention the parallax problem given there is a gap of an inch or more between the monitor and the touch screen.  FTIR is better when you project the image onto the touch screen.
If you don't mind lower resolution, I believe the micro dose dispenser soda machines use a capacitive touch wire mess embedded in the transparent plastic front panel.  Although micro dose dispensers appear to only need to emulate about 100 to 200 buttons.  Not enough to control a mouse with any accuracy.  But enough to control a GUI designed with such constraints.
Loose high resolution capacitive touch screens can be bought with out a monitor.  However they tend to be much smaller then 32 inches.


text:
Writing not permitted on genuino 101 Built in Bluetooth LE (phonegap)
I have a Genuino 101 which has a built in Bluetooth LE module. I have been trying to connect this to my phone using phonegap. I have been using cordova-plugin-bluetootle and with it I have been able to receive data from the arduino and display that data on the phone.
I tired adapting it so that I could send data from the phone to the arduino. I noticed in the CurieBle examples there was a project called "Callback LED" but when I connected to the Arduino from the Phone gap app I noticed in the debug message about characteristics it said "properties":{"notify": true, "read": true} but nothing about write. I tried writing "Hello world" (converted into bytes then encoded string) I got an error similar to (I couldn't copy it exactly as it was an alert on the phone): "error": "write", "message": "Error Domain=CBATTErrorDomain Code = 3 \"Writing is not permitted.\" ..."...There is more detail to the error message that is not at all relevant and is slightly repetitive.
Here is the arduino code (which is almost straight from the example):
#include <CurieBle.h>

const int ledPin = 13; // set ledPin to use on-board LED
BLEPeripheral blePeripheral; // create peripheral instance

BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // create service

// create switch characteristic and allow remote device to read and write
BLECharCharacteristic switchChar("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); // use the LED on pin 13 as an output
  digitalWrite(ledPin, HIGH);
  while(!Serial);
  digitalWrite(ledPin, LOW);
  // set the local name peripheral advertises
  blePeripheral.setLocalName("LEDCB");
  // set the UUID for the service this peripheral advertises
  blePeripheral.setAdvertisedServiceUuid(ledService.uuid());

  // add service and characteristic
  blePeripheral.addAttribute(ledService);
  blePeripheral.addAttribute(switchChar);

  // assign event handlers for connected, disconnected to peripheral
  blePeripheral.setEventHandler(BLEConnected, blePeripheralConnectHandler);
  blePeripheral.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);

  // assign event handlers for characteristic
  switchChar.setEventHandler(BLEWritten, switchCharacteristicWritten);
// set an initial value for the characteristic
  switchChar.setValue(0);

  // advertise the service
  blePeripheral.begin();
  Serial.println(("Bluetooth device active, waiting for connections..."));
}

void loop() {
  // poll peripheral
  blePeripheral.poll();
}

void blePeripheralConnectHandler(BLECentral& central) {
  // central connected event handler
  Serial.print("Connected event, central: ");
  Serial.println(central.address());
}

void blePeripheralDisconnectHandler(BLECentral& central) {
  // central disconnected event handler
  Serial.print("Disconnected event, central: ");
  Serial.println(central.address());
}

void switchCharacteristicWritten(BLECentral& central, BLECharacteristic& characteristic) {
  // central wrote new value to characteristic, update LED
  Serial.print("Characteristic event, written: ");

  if (switchChar.value()) {
    Serial.println("LED on");
    digitalWrite(ledPin, HIGH);
  } else {
    Serial.println("LED off");
    digitalWrite(ledPin, LOW);
  }
}

Here is the write function (phonegap) which is where the error is being produced from :
var string = "Hello World";
var bytes = bluetoothle.stringToBytes(string);
var encodedString = _arrayBufferToBase64(bytes);
alert("Service : " + connection.service + "  char : " + connection.char + " Address: " + address);
var params = {"value":encodedString,"service":connection.service,"characteristic":connection.char,"address":address};
alert("params : " + JSON.stringify(params));
bluetoothle.write(function(res) {
alert("Success writing : " + JSON.stringify(res));
}, function(err) {
alert("Error writing: " + JSON.stringify(err));
}, params);

I think the error lies in the fact that the Arduino appears not to be advertising the "write" characteristic.
BTW the phone tells me that the service was 180d and the characteristic was 2a37.

I finally figured it out thanks to finding this GitHub issue. It turns out to be an error with CurieBLE which manifests in a way that means that on IOS it reads the original characteristics and services so when I tried to write it was still thought that the characteristic was read-only. I had to restart my phone and it is working now.
There was another thing which is that I needed to send a shorter message, I think it was 20 bytes max per message although I'm not sure, but I sent "h" and the Arduino received it.

I can't for another two days :-( but I will...

Yes, iOS seems to cache a lot of things by peripheral hardware address and not notice that they have changed for quite some time.  If you change addresses it will think you are something new, or else you have to get iOS to flush its cache.


text:
Send events to Azure IoT Hub combined with deep sleep mode
I use a Node MCU ESP8266. I have a working C app sending temperature and humidity sensor data to Azure IoT Hub continuously. I see events/messages coming in at Azure.
Now I'd like the app to only send data every minute or so. So I implemented a deep sleep scenario. The problem is my messages are queued but not sent.
My suspicion is that the IoTHubClient_LL_DoWork() does not send the data immediately before the device is going into deep sleep. But I don't know enough about C or the AzureIoT SDK. Here is my code:
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <WiFiUdp.h>

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>

#include <AzureIoTHub.h>
#include <AzureIoTProtocol_MQTT.h>

#include <ArduinoJson.h>

#define IOT_CONFIG_CONNECTION_STRING "CONNSTRING"

#define DEVICE_ID "NodeMcu"

#define WIFI_SSID "SSID"
#define WIFI_PW "PW"

#define MESSAGE_MAX_LEN 256

static bool messagePending = false;
static bool messageSending = true;

static int messageCount = 1;

static IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;

void setup()
{
    delay(1000);

    Serial.begin(115200);

    connect();
    initTime();

    iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(IOT_CONFIG_CONNECTION_STRING, MQTT_Protocol);
    if (iotHubClientHandle == NULL)
    {
        Serial.println("Failed on IoTHubClient_CreateFromConnectionString.");
        while (1);
    }

    //IoTHubClient_LL_SetOption(iotHubClientHandle, "product_info", "HappyPath_AdafruitFeatherHuzzah-C");
    //IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, receiveMessageCallback, NULL);
    //IoTHubClient_LL_SetDeviceMethodCallback(iotHubClientHandle, deviceMethodCallback, NULL);
    //IoTHubClient_LL_SetDeviceTwinCallback(iotHubClientHandle, twinCallback, NULL);
}

void loop()
{
    if (!messagePending && messageSending)
    {
        char messagePayload[MESSAGE_MAX_LEN];
        readMessage(messageCount, messagePayload);
        sendMessage(iotHubClientHandle, messagePayload);
        messageCount++;
        delay(5000);
    }

    IoTHubClient_LL_DoWork(iotHubClientHandle);
    delay(10);
}

void connect()
{
    delay(10);

    if (WiFi.status() == WL_CONNECTED)
    {
        Serial.println("Already connected...");
        return;
    }

    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(WIFI_SSID);

    WiFi.begin(WIFI_SSID, WIFI_PW);

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

void initTime() {
    time_t epochTime;

    configTime(0, 0, "pool.ntp.org", "time.nist.gov");

    while (true) {
        epochTime = time(NULL);

        if (epochTime == 0) {
            Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry.");
            delay(2000);
        } else {
            Serial.print("Fetched NTP epoch time is: ");
            Serial.println(epochTime);
            break;
        }
    }
}

void readMessage(int messageId, char *payload)
{
    float temperature = readTemperature();
    float humidity = readHumidity();
    StaticJsonBuffer<MESSAGE_MAX_LEN> jsonBuffer;
    JsonObject &root = jsonBuffer.createObject();
    root["deviceId"] = DEVICE_ID;
    root["messageId"] = messageId;

    // NAN is not the valid json, change it to NULL
    if (std::isnan(temperature))
    {
        root["temperature"] = NULL;
    }
    else
    {
        root["temperature"] = temperature;
    }

    if (std::isnan(humidity))
    {
        root["humidity"] = NULL;
    }
    else
    {
        root["humidity"] = humidity;
    }

    root.printTo(payload, MESSAGE_MAX_LEN);
}

float readTemperature()
{
    return random(20, 30);
}

float readHumidity()
{
    return random(30, 40);
}

static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, char *buffer)
{
    IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char *)buffer, strlen(buffer));
    if (messageHandle == NULL)
    {
        Serial.println("Unable to create a new IoTHubMessage.");
    }
    else
    {
        //MAP_HANDLE properties = IoTHubMessage_Properties(messageHandle);
        //Map_Add(properties, "temperatureAlert", temperatureAlert ? "true" : "false");
        Serial.printf("Sending message: %s.\r\n", buffer);
        if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, NULL) != IOTHUB_CLIENT_OK)
        {
            Serial.println("Failed to hand over the message to IoTHubClient.");
        }
        else
        {
            messagePending = true;
            Serial.println("IoTHubClient accepted the message for delivery.");
        }

        IoTHubMessage_Destroy(messageHandle);
    }
}

static void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *userContextCallback)
{
    if (IOTHUB_CLIENT_CONFIRMATION_OK == result)
    {
        Serial.println("Message sent to Azure IoT Hub");
    }
    else
    {
        Serial.println("Failed to send message to Azure IoT Hub");
    }
    messagePending = false;
}

You need to call IoTHubClient_LL_DoWork until all messages are processed and only after that you can go to sleep.
Check the following code:
void IoTHubFullSendReceive()
{
  IOTHUB_CLIENT_STATUS Status;

  while ((IoTHubClient_LL_GetSendStatus(IoTHubClientHandle, &Status) == IOTHUB_CLIENT_OK) && (Status == IOTHUB_CLIENT_SEND_STATUS_BUSY))
  {
      IoTHubClient_LL_DoWork(IoTHubClientHandle);
      ThreadAPI_Sleep(50);
  }
}


text:
How do I learn C? (was Computer project)
Can you help me writing a code for this question guys??
You have an Arduino Uno with 8 LEDs connected to digital pins 2 to 9.
Create an array of 8 elements. Fill it with random numbers between 2 and 9 (all inclusive)
Write a program which determines the greatest number among them. Save this number in a variable named max. Print this number on serial monitor. Blink the LED connected to this number. Let the delay time be 0.5 second.
Note that the random function may result in duplicate numbers generated. For example, the generated array may be {3,4, 4, 7,6, 2,5,7}
The maximum number will be 7.Since it occurred twice in the array, then you should blink it twice ^_^
It the maximum number occured 3 times in the array, then you should blink it 3 times, and so for any number of occurrences
I have written this so far but I'm sure it's all wrong
int pins[8]={2, 3, 4, 5, 6, 7, 8,9};

void setup()
{
   pinMode(pins[8], OUTPUT);
}

void loop()
{
    x=random(0, 8);
    digitalWrite(pins[x], HIGH);
    delay(1000)
    digitalWrite(pins[x], LOW);
    delay(1000)
}

That's poorly stated homework since they only give one delay but expect patterned blinking.  Anyway, approach this by imagining you are a robot being shown the numbers one at a time.  What very efficient notes could you take on a re-writable scratchpad (ie, a minimal number of variables)  It will help in finding the best solution if you assume the list of numbers could be arbitrarily long...

@JRobert I'm stuck in the if statement and arrays I really can't understand them also there's supposed to be a for loop

How would you simulate this on paper/physically?  For example, using N head-tail coins as LEDs.....

Well for one improvement, pins[8] is undefined, since C indices start with 0, so there are only pins[0]...pins[7] defined in your code.  Maybe you could use your for(;;) loop there? Also, try compiling your code--if the compiler detects and reports errors, it might help you refine your logic.

This answer is for C, which is pretty similar to Arduino. Please read it carefully, it teach about arrays: http://www.dummies.com/how-to/content/how-to-use-arrays-in-c-programming.html

Frankly there is no sound reason to put the pins in an array at all, since their range is continuous.  The only array needed is the input data.  And only two local variables plus the iterator variable are required to solve the problem.  Basically, writing code is premature.  Figure out the algorithm.

@Chris Stratton.  Yes Yes.  Figuring out an algorithm before coding would be best. But since the OP was already has code without an algorithm, I figured I'd point them to step two of the edit-compile-test cycle.  Maybe the syntax errors would provide enough clues.

I'm sorry, but a question "How do I learn C" is a bit broad for this site. For one thing you might ask on Stack Overflow which is a programming site. But even there they will probably tell you to read a book or do a tutorial. Stack Exchange is designed to answer specific questions not "teach C" (or learn how to fly, or learn how to cook, for that matter). I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

First hint: pinMode() only applies to one pin at a time. You'll need to execute it 8 times to intialize 8 I/O pins' modes.
Second hint: As @ChrisStratton tried to suggest, generate the random number set first; then "figure out" (set some variables in memory that will tell you) what do with the terminal output and the digital I/Os; then do each of those things. It helps to partition a larger problem into smaller ones.
Update: Considering your updated title, How do I learn C?, and since the question reads like a homework assignment, aren't you already taking a class in C or C++? If so, how do you find it lacking, i.e., what additional resources or direction would be most helpful to you? There are a number of good books on the C language, and one of those would be a good place to start. If you don't already have a favorite one, you can't go wrong with The C Programming Language, by Brian Kernighan & Dennis Ritchie, the authors/designers of the C language and its early compilers. It is book on the C language, not on programming per-se, so if you are new to programming as well, a programming tutorial would be an excellent additional choice (sorry I don't have one to recommend).
Secondly, beat up on the example programs that come with the ArduinoIDE: click the "Open" button [uparrow icon on the IDE toolbar; not the File | Open menu] and you'll see a menu of your current sketches and, below the break, categories of example programs. Pick one of the examples, read it and try to understand what it does and why it is written the way it is. Then tweak the ###p out of it - both to understand how make it behave differently, and to break it. You'll learn a lot by a) interpreting error messages from the compiler, and b) finding and fixing your mistakes. If you're not breaking your programs at least twice as often as you're succeeding, you're not trying hard enough!


text:
Arduino: pins still active after entering sleep mode
I'm writing an Arduino sketch to control a display with my Arduino Nano. I have wired it up as explained here, but used pin 3-7 instead of pin 2-6 listed in the example. The reason I did so is that I also added a push-button on interrupt 0 (= digital pin 2). I'm calling the sleep mode with a method, as explained in the section "Example" here. The Arduino seems to sleep, turning off all LEDs but the on/off one. The problem I have now is that the LCD display is sometimes still enabled (but only sometimes, not always). Why is it behaving like this? And how can I switch off everything possible to save as much energy as possible?
Here is my code piece:
int buttonPin = 2;

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

void loop() {
  ...
  if(counter == 100) {
    enterSleep();            // Enter sleep method!
  }
  delay(1000);
}

void enterSleep()
{
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  attachInterrupt(digitalPinToInterrupt(2), wakeUpNow, LOW);
  sleep_mode();

  /* The program will continue from here. */
  /* First thing to do is disable sleep. */
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(2));
}

void wakeUpNow() {
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

I see nothing related to an LCD there at all. Maybe you forgot that bit?

The LCD is the main part of my question. I need to know why it won't be switched off when arduino is going to sleep

The LCD might be in your question, but it's not in the code. Are we supposed to just guess what you're doing with it?  http://snippets-r-us.com/

Simply put: how are you turning off the LCD?

I don't do anything special to turn the LCD off. After making some lcd.setCursor(x, y) and lcd.write("message") I'm calling the enterSleep method. I thought that the commands inside this method switch off all output to the pins.

Nope. It stops the CPU, nothing more. It is up to you to place pins into states that you want them to be in.  If you are using PWM to set the back light brightness then it'll be random as to whether the pin is HIGH or LOW at the moment you sleep.

Ah yes, thank you, then this is the solution for me! I thought that all outputs are also "cancelled" if the sleep mode is entered! So I can easily set all pins to LOW in the enterSleep method before calling sleep mode command?

Nope. CPU core is stalled, and most peripherals are also disabled - mainly because the clock ceases to tick.  Nothing is actively changed in the configuration of anything.

Is the button bouncing? Would explain the 'sometimeness`.

The problem is that you are not specifically doing anything to "turn off" the LCD (that is, switch off the back light - note that the LCD module will still be consuming power while you sleep).
When you sleep the MCU it does just that - it goes to sleep. Its clock stops ticking. Not a lot more than that really.  So if you are using PWM to control the backlight of the LCD, when the clock stops ticking the PWM will stop happening, and the I/O pin will remain stuck in whatever state it happened to be in at that moment - leaving you with random on or off at sleep time.
The solution? Manually turn off the backlight just before you sleep.
digitalWrite(9, LOW);

To save more power you might want to consider adding a high-side switch to the power of the LCD module. With that you can physically disconnect the power to the LCD to stop it consuming any power at all during sleep mode. Of course, after re-enabling it you will need to fully reinitialize the module.
The same goes for any other external hardware that takes a power supply.
A high side switch can be built from a P-channel MOSFET being controlled by an N-channel MOSFET. There's plenty of examples on the web.


text:
Where can I find a hardware manual (or documentation) for Arduino Uno & ATMega328P?
Where can I find a hardware manual (documentation or a book) for Arduino board?
As far as I know, all hardware details are dispersed (or scatter) in different tutorials.

The Arduino Uno is little more than an ATmega328P microcontroller. In
most cases you will be interested by the documentation of the
microcontroller itself. Anyway, here are both:

The Arduino Uno product page contains the most basic specs, as well as links to

the board schematic
the pin mapping, but see below for a nicer alternative

the ATmega328P product page links to

the ATmega328P family datasheet, a 650 page authoritative document
the ATmega328P Automotive - Complete Datasheet, specific to the Uno's chip.
the AVR instruction set manual, for those who want to play with assembly
many application notes discussing specific uses of some peripherals

Alberto (aka PighiXXX) has published nicer versions of the Arduino Uno
pinout:

I've added the "Arduino specific" guides/help from Arduino.cc, since it's not a completely new answer. Feedback is appreciated, I can revert it/create my own answer if neccesary.

@Paul: The question is about the hardware of the Arduino Uno, and the OP specifically wrote he is looking for reference material (manual, documentation or book) rather than tutorials. The links you added are very general. They are not specific to the Uno hardware, and they tend to cover the software more than the hardware.

Oops! I have reverted my adjustments, it didn't add value to this specific question.

For the hardware part, you can refer to the schematic. It shows all the components so you can find their datasheets for detailed study.
UNO schematic
But to me, if you're just using the board but not designing your own board or writing libraries for the board, I don't think this is necessary. Stick to application level or IO-level and only really dig into the hardware when you're blocked when doing things like using all timers, low-power mode, interrupt with Serial...

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


text:
How to digital read and send the data through serial to PC with speed around 2 MHz?
I would like to read analog data with frequency sampling around 2 MHz and send it to PC to be processed with python for digital oscilloscope. I use Arduino Nano. I have found ADC (AD9057, PDF) that can handle up to 40 MSPS into 8 bits parallel, but I still face some problems

How could I read digital pin data quickly around 2-4 MHz? I read that it is possible using direct port manipulation.

How could I send the data to PC with that sampling rate? I know that the maximum baud rate of arduino is around 2.000.000 or let say 2 MegaBytes/s, so for 2 MHz sampling, i could only send one character per micro second, could it be more faster?

Thank you

ad 2. With asynchronous serial interface it's actually 2Mega bits, not mega bytes. In synchronous it's possible.

Read this and this. Actually you might just want to write assembly code to read a specific PORT (e.g. PORTD) and push it into the UART registers. If that is not sufficient, get a better, faster microcontroller (ESP8266 / ESP32). Also this might interesting.

Do you want do read analog values (using the ADC) vor digital data using the PIN registers directly? This is a huge difference and write both is your question.

@MaximilianGerhardt thanks mate, i'll read it

@KIIV what is it means with synchronous serial?

@chrisl i would like to read the incoming digital signal from external ADC

Then how do you have connected the external ADC to the Nano? What external ADC do you use? Please provide a link to a datasheet

For USART / UART read http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf Chapter 24. With USART you have to send an additional clock signal, but can achieve a much higher speed.

@chrisl edited, the datasheet added

In short? You can't.
To have a 2MHz transmission you need 2*Nbit MHz of serial clock to send it to the PC, where Nbit is the number of bits per sample. Since the minimum is 8, englecting the synchronization or additional bits the serial clock has to be at least 16MHz. Which is the system clock of the nano. So no way.
Now, with the alternatives. First question: what is your ADC's interface? I found the LTC2204. It is a parallel ADC, so you need something to convert it to anything readable by the PC.
I'm not sure about the feasibility of this, but a nano is not enough. I'd use an STM32 (because I have their Nucleo boards, but you can search for other 32-bit boards) and a high speed serial interface. Since even SPI can be slow, maybe ethernet needs to be used. I was not able to search for boards with native ethernet interface; anyway the STM32F4 microcontrollers should (see this article) have an ethernet interface and you will "only" need the PHY. I think that this is the only applicable way to follow..


text:
Hardware Interrupts Issues
My program has a hardware interrupt to digital pin 2,  it is an IR obstacle detection sensor which gives “open collector” signal.  My program is executing an array — “for” loop.   At some point it has to wait for the input from the IR sensor, so I am using a “while” loop to pause and wait for the input.
When the program gets the signal from the sensor at which point the interrupt occurs, the program collects the data (millis) and goes on for another round.  Everything works fine, but I would like to limit the time that the program is waiting for the interrupt signal, let’s say to 5 or 10 seconds. I do not want it to just sit there forever if the signal is not coming for some reason.   So what I am trying to do is to trigger the same interrupt pin (2) by another digital pin.  I  set this pin (7) on OUTPUT wrote a little “if-then” statement  so it will go HIGH when the time is up and connected this pin (7) to pin 2.
The scheme works partially.  When the pins are connected and the time limit is reached the pin 2 gets signal and gets triggered.   But the IR signal seems to be disabled and not functioning while it is waiting for the time limit.  I tried to connect pull-up and pull-down resistors to no avail.  It seems that when the pins are linked the IR signal disappears.  I do not even get any voltage readings on that wire. If I disconnect the pins the IR signal works again and I get voltage readings on the wire.
Can anyone tell me what is going on and how can I make it work.  Is even possible?  Or what I have concocted is just plain silly?
Thank you!

To be honest, how you are working around your interrupt problem is confusing.  There may be a better way.  Regardless, how to OR together open collector outputs is an interesting problem to solve.

I hope you see that by "working around" your first problem, you created another problem. Why don't you just break out of your while when it is holding on too long? Fixing software issues in hardware is just not the path to go.

Thanks everybody for the help, and God Bless this forum and its members.  I do not know what I could have done without it…
Software solution is exactly what I needed, but because my knowledge of Arduino and programming is so meager I just did not know how to get out of the “while” loop properly.  The “break” was exactly what I needed All works great!
I was so caught up in trying to trigger the interrupt pin I could not see the forest for the trees.
Here is the link to the video of the prototype I am working on.
https://www.youtube.com/watch?v=--y6LWQXjzw
Thanks again!
Vladimir.

It is likely that the Arduino's digital output is of a totem poll type.  That is, it is both actively being driven high and low.  And when high, is probably over powering the IR sensor's signal.  You should not use this setup!! As it could possibly short out both your processor and IR sensor.
Instead you could emulate an open collector Arduino output.  By switching the second pin from a digital input to a digital output sending 0 then back to a digital input. (Never set this pin to digital output and send a 1 as this could short to ground through the IR open collector.)
I am assuming that the IR sensor, when activated, is momentarily pulling a pull up resistor low through the open collector to ground.  Let us know if this is incorrect as the above description would then not apply.

Thanks everybody for the help, and God Bless this forum and its members.  I do not know what I could have done without it…
Software solution is exactly what I needed, but because my knowledge of Arduino and programming is so meager I just did not know how to get out of the “while” loop properly.  The “break” was exactly what I needed All works great!
I was so caught up in trying to trigger the interrupt pin I could not see the forest for the trees.
Here is the link to the video of the prototype I am working on.
https://www.youtube.com/watch?v=--y6LWQXjzw
Thanks again!
Vladimir.

Wouldn't it be easier just to have the interrupt call a function, that you also call after 5 seconds are up? This sounds a round-about way of doing it.
If you must do this, setting your other pin to output is not correct, because then the IR sensor and your other pin (7) are fighting each other. You should set the pin to input, and when you want it to do something briefly make it OUTPUT, and send HIGH. Then send LOW, and go back to INPUT.
However this might still make the output pin "fight" the IR sensor pin.

But the IR signal seems to be disabled and not functioning while it is waiting for the time limit.

Naturally, as your output pin is holding the line low.

If the sensor just uses a pull-down resistor (and not actively drive the line low) then my scheme should work.

However a simpler scheme is just to set a flag in the ISR, (which you test for in the main loop) and if the flag isn't set within your timeout period, do whatever you want to do if it times out. Then you don't need to try to trigger the interrupt yourself.

Thanks everybody for the help, and God Bless this forum and its members.  I do not know what I could have done without it…
Software solution is exactly what I needed, but because my knowledge of Arduino and programming is so meager I just did not know how to get out of the “while” loop properly.  The “break” was exactly what I needed All works great!
I was so caught up in trying to trigger the interrupt pin I could not see the forest for the trees.
Here is the link to the video of the prototype I am working on.
https://www.youtube.com/watch?v=--y6LWQXjzw
Thanks again!
Vladimir.


text:
How to detect the pulse width from microphone as Input?
I'm working on a project that detects the pulse width of an audio signal, which uses a microphone as an input. The user gives 2 different types of sounds one last less 0.3 seconds and other lasting less than 0.7 seconds. I've attached the audio visualisation of the signal pic in the attachment.
All want to detect is their pulse widths.
I tried Pulsein() - but as you can see that it has a variable until 0.3 or 0.7 seconds it only detect the first and most peak and returns the value which is almost zero.
But all I need is the total time taken for the pulse to rise from 0 and to variate and then become 0 this total time period is what I require.
would duty cycle help ? or any other functions available to detect two different sounds in arduino ?

pulse width

@Egar Bonet I even tied setting up an threshold upto which the unwanted signals are removed but after that would it possible to recover the pulse width of it !

It is better to include the images in the question rather than a link to some offsite drive. I've done one for you, the other I can't open (which is why you should do it yourself in the first place).

If you are just detecting Morse code (which it looks a bit like you are from the file name you used (ditandddat.jpg)) then a simple on/off test should do it.

You will need some sort of interface circuit between your mic and your
Arduino. Best would probably be to have some kind of external peak
detection. This way the Arduino reads instantaneous wave amplitude. The
other option is to only shift and scale the signal so that it fits the
Arduino ADC, acquire the signal at a high enough sampling rate, and
compute the instantaneous amplitude in software.
I suggest you take a look at this sound-meter program. You could use
it as a basis for your own processing.
Then you just have to define a threshold and time how long the amplitude
remains above that threshold.


text:
Soil moisture sensor problem
I'm having a problem trying to run a bunch of code, using an "if" state which uses a variable which should get a value from a soil moisture sensor.
I'm using the sensor digitally, so it should just sense a value between the 2 discrete "0" and "1". However, even if I think my code is ok, it simply doesn't work, as the value is always "0"(default value is 0 for the global variable "sms" i use). The code I'm posting below is without an "else" state that is following the first "if". But my problem is inside the first "if" state. Please note that jumper wires are ok and also I've tried 3 different soil moisture sensors, two of which were brand new. Any ideas on what's wrong?
//Start of program

char auth[] = "**************";
char ssid[] = "88888";
char pass[] = "99999999";

int Relay1 = D1;
int Relay2 = D2;
int val2;
float val3;
int sensor_pin = D7;
int pinValue;
SimpleTimer timer;
elapsedMillis timeElapsed;
DHT dht(DHTPIN, DHTTYPE);
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE2);

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  Blynk.begin(auth, ssid, pass);
  pinMode(Relay1, OUTPUT); //Setup Relay pin as output pin
  pinMode(Relay2, OUTPUT); //Setup Relay pin as output pin
  pinMode(sensor_pin, INPUT);
  digitalWrite(Relay1, LOW);
  digitalWrite(Relay2, LOW);
  digitalWrite(Relay1, HIGH);
  digitalWrite(Relay2, HIGH);
}

BLYNK_READ(V8)
{
  Blynk.virtualWrite(8, level);
}

BLYNK_WRITE(V1) {
  pinValue = param.asInt();
}

void loop()
{
  Blynk.run();
  timer.run();
  if (pinValue == 0)
  {
    some code here
    sms=digitalRead(sensor_pin);
    if ( sms == 0)
    {
      if (val2 <= 14)
      {
        code here          }
      else
      {
        digitalWrite(Relay2, LOW); // Pump2 ON
        delay(500);

      }
    }
    else //(sms == 1)
    {
      some code here
    }
  }

Do you mean the sensor_pin sensor is the issue? What sensor is it?  Does it need a pull-up resistor?  If you wire a logic HIGH to sensor_pin instead of the sensor, will it the code's logic work as expected?   I'd add a couple more Serial.println() statements to tell you some debug info.

@Dave X https://images-na.ssl-images-amazon.com/images/I/51YJV7u7mYL.SL1000.jpg

@Dave X Also i when i formated the paste of code, i forgot the int sms=0; global variable.

Serial.println() lines were added. But sms value remains == 0.

jumper wires are ok ... what jumper wires?

reduce the code to the smallest code necessary to demonstrate the problem.

I mean physical wires which were used to connect sensor to arduino.

Code was reduced.

int sms=0;   This variable can NEVER EVER have any value between 0 and 1.  If you try to give it any value between the two it will end up with a 0.  Read up on what types of numbers an int can hold if you don't understand why.

There isn’t a sms=... anywhere in your code. Where would sms get any different value than the initial?

My mistake. I just erased it in order to reduce code. Now you can see where sms gets a value.

Obviously, since code is reduced....

What voltage does the sensor put out?  If you measure the D7 pin with a meter, is it ever above the 3 volt logic HIGH threshold to be interpreted as a 1?

I would put the sensor in sum very wet soil and have some code like this loop(){Serial.println(digitalRead(sensor_pin));delay(500);} and see what it says.  It might be that you have to tweak the pot on the board to set the sensitivity and it only goes high when it passes a certain value.


text:
Load cell and hx711 with arduino
I wanted to connect the load cell with hx711 to Arduino to check the presence of load. If there is load on the load cell then an LED can light up and when there is no load the LED will be off. I tried several codes but I'm not getting the result I need. If anyone of you can help with this as this is for my graduation project I will be grateful.
EDIT:
Here is my code, I'm a beginner in Arduino so I don't know much about how it works but this is what I managed to write. PS. the hashtaq before include makes the the text in bold so I excluded it here.
include < HX711_ADC.h >

HX711_ADC scale (2,3); //DT pin2 , SCK pin3
int load1 =0;

void setup() {
   pinMode (3,INPUT); // SCK pin
   pinMode (13,OUTPUT); //LED pin
   Serial.begin(9600); }

void loop() {
   load1= digitalRead(3); // read signal from SCK pin

   if(load1==HIGH) // if there is load on load cell
        {
        digitalWrite(13,HIGH); // turn on the LED
        delay(5000);
   } else {
       digitalWrite(13,LOW); // turn off the LED
       delay(5000);
   }
}

Can you show us the code you have written so far?

This isn't a forum. Don't respond to questions with an "answer". Amend your question.

@bummi - Whoops sorry for the rejection, didn't realise that the edit was from the answer. My bad.

look at the line starting with void setup() ... everything after the ; // all way to end of line is a comment .... it is not code that executes .... same goes for the two lines after that .... please correct the code listing

You are not using the https://github.com/bogde/HX711 library properly.  Instead of load1=digitalRead(3); try something like load1 = scale.get_units(); (and initlialize the scale with a scale.begin() in setup and maybe a scale.tare() )


text:
MKR GSM 1400 Works only when connected to computer
My MKR GSM 1400 works fine when connected to a computer (powered USB) and after opening a serial connection to it.  It does not when I plug it into a power supply. My power supply is a 5V 3A with a USB adapter.
void setup() {
  // put your setup code here, to run once:
  //...
  while (!Serial);
  //...
}

void loop() {
  // put your main code here, to run repeatedly:
  //...
}

What means that it does not work? What does actually happen? Also show us your code and your circuit. Currently you don't give us enough information to help you.

@chrisl The sketch doesn't run = It does not work. Is my power supply sufficient? Is it ok to power it through the USB connection or do I need to power it somewhere else? I don't think my code is the issue.

do you have while (!Serial); in the sketch?

How do you see, that it doesn't run? As asked: please say, what actually happens instead of what doesn't happen.

I’ll upload a minimal sketch later. I have an Xbee connected. The sketch makes an http request. If it were running I’d see data in the database. If I connect to the computer, it runs. I do use Serial to let me know what’s going on while connected to the computer.

It was the while(!serial)

I've posted a question with more details since I am having the same issue at: https://arduino.stackexchange.com/questions/77324/arduino-mkr-gsm-1400-fails-to-start-up-without-serial-monitor

If your sketch on an Arduino with native USB doesn't run if not connected to USB, always first check if you didn't forget to disable a dependence on Serial.  A common error is a while (!Serial) {} endless loop in setup().


text:
Getting wrong value from Serial.read()
I have an RGB LED, connected to my UNO R3 and would like to turn on the written color in the serial by following a table (1 for red, 2 for blue, 3 for green...) and I also want to make that if this LED is already turnt ON, I want it to turn OFF. The problem I have is that when I use Serial.read() it always returns a -1 value. Why is that?
I leave you the code here and in case you see something wrong please tell me. Thank you very much.
#define RED 7
#define GREEN 4
#define BLUE 2
  String ledcolour[] = {"RED", "BLUE", "GREEN", "YELLOW", "PURPLE", "WHITE"}; //array to match the number typed to the LED colour
  char ledstatus[] = {0, 0, 0, 0, 0, 0}; //0 if the LED is OFF and 1 if it's ON
  String ledvaluefix[] = {"HIGH", "LOW"}; //if the ledstatus[] value is 0 it will write HIGH and if it's already ON it will write LOW
  char ledstatusfix[] = {1,0}; //to update in ledstatus[] if the LED is ON or OFF
  int led = Serial.read();
void setup() {
  pinMode(RED,OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE,OUTPUT);
  Serial.begin(9600);
  Serial.println("Type the LED's colour you want to turn on following this table:");
  Serial.println("RED=1");
  Serial.println("BLUE=2");
  Serial.println("GREEN=3");
  Serial.println("YELLOW=4");
  Serial.println("PURPLE=5");
  Serial.println("WHITE=6");
}

void loop() {
  if (Serial.available()){
    Serial.println(led);
    loop();
   if (led <= 6 && led >=1){ //Checks if value is within 0-6
    if (led <=3){ //Classifies in primary or mixed colours (understand primary as just having to turn ON one single LED)
      if (ledstatus[led-1] == 0){//checks if the LED was OFF
        digitalWrite(led-1,HIGH);//turns the typed LED to HIGH
        char ledstatus[led-1] = {1};//updates the array to set the LED is now ON
        confirmer();//sends a serial confirmation message
      }else{//if it was already ON
        digitalWrite(led-1,LOW);//turns the typed LED to LOW
        char ledstatus[led-1] = {0};//updates the array to set the LED is now OFF
      }
    }else{//if it's not a primary colour
      Serial.println("YOU CHOSE " + ledcolour[led-1] + ", WHICH IS A MIXED COLOUR");
    }
    }else{//if the value is not valid (not between 0 and 6)
      Serial.println("SORRY, THE INTRODUCED VALUE IS NOT VALID");
      Serial.println("PLEASE, TRY AGAIN");
    }
  }
}
 int confirmer(){
    Serial.println("YOU CHOSE THE " + ledcolour[led-1] + " LED");//sends the serial message confirming it's been turned ON
   }

Why on earth are you calling loop from loop? That's nasty and leads to infinite recursion and crashing.


text:
How to write array of functions in arduino library?
I've nine functions each of type void as follow:
void zero();
void one();
void two();
void three();
void four();
void five();
void six();
void seven();
void eight();
void nine();

I've put all these functions into an array pointer as follow (without any error):
typedef void (*num_func) ();
num_func functions[] = { zero, one, two, three, four, five, six, seven, eight, nine};

Now I'm writing an arduino library and wanting to achieve the same, but after hours of thinking I'm not able to achieve. Please help me how can I accomplish this in a library?
Thanks in advance.

@Mikael
Sorry Mikael, I'm not able to comment at your answer (because stackexchange demands me to have 50 points before I can comment). Here is the error I'm getting from your implementation. storage class specified for 'functions'

What is your setup? I do not get that error. Obviously there must be some implementation of the functions and there must be a sketch that uses the library.

Yup, I've the implementation of the functions in .cpp file (for all of these zero() etc. functions).
And also, I'm getting this error when I compile a sketch using that library.

Which line does to the compiler indicate? You have added some extra character or added extern also in the implementation.

It is pointing at:      extern num_func functions[];
And I've NOT added extern in the implementation.

What compiler/IDE version are you using? You have not answered the question about the setup. You must provide more information.

I'm using Arduino IDE latest uptodate.
And I can provide more information of course. What do you mean by "What is your setup?"

Let us continue this discussion in chat.

Ah, one thing that might be of worth noting is I've declared the functions zero() etc. as members of the class.

I've tried the implementation of the function as you've in your edited answer, but as a member of the class I'm talking about. And my implementation in the loop() is as follow:     myClassNamet::functions1;
Now I'm getting additional error "invalid use of non-static data member 'myClassName::functions'

I have migrated your answer to be comments under your question. You can always edit the question itself and add additional notes in response to answers.

You must define the member function as static. But then it cannot access member data as there is no this reference. Please mark this question as answered or at least update your original question with with is not yet answered.

This was a bit fiddly to get right. I got inspiration from How do I create and use an array of pointer-to-member-function?
Based on my post about Function pointers / function callbacks / function variables I modified it to work with class functions:
class foo {

  public:

   void doAction0 ()
    {
      Serial.println (0);
    }

    void doAction1 ()
    {
      Serial.println (1);
    }

    void doAction2 ()
    {
      Serial.println (2);
    }

    void doAction3 ()
    {
      Serial.println (3);
    }

    void doAction4 ()
    {
      Serial.println (4);
    }

   // typedef for class function
   typedef void (foo::*GeneralFunction) ();

   // array of function pointers
    GeneralFunction doActionsArray [5] =
    {
      &foo::doAction0,
      &foo::doAction1,
      &foo::doAction2,
      &foo::doAction3,
      &foo::doAction4,
    };

};  // end of class foo

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting"));

  // test instance of foo
  foo bar;

  for (int i = 0; i < 5; i++)
    {
    // get member function pointer from array
    foo::GeneralFunction f = bar.foo::doActionsArray [i];
    // call the function
    (bar.*f) ();
    }  // end of for loop

}  // end of setup

void loop () { }

This compiles OK and prints:
Starting
0
1
2
3
4

Amended answer
I was wondering why you needed to specify bar in this line above:
    foo::GeneralFunction f = bar.foo::doActionsArray [i];

The reason is that the code above had the array as non-static, and thus a copy belonged to each instance of the class. This doesn't make a huge amount of sense, so the modified code below makes the array static and const. That is, the array should be the same for every instance of foo and also never change.
Modified code below:
class foo {

  public:

   void doAction0 ()
    {
      Serial.println (0);
    }

    void doAction1 ()
    {
      Serial.println (1);
    }

    void doAction2 ()
    {
      Serial.println (2);
    }

    void doAction3 ()
    {
      Serial.println (3);
    }

    void doAction4 ()
    {
      Serial.println (4);
    }

   // typedef for class function
   typedef void (foo::*GeneralFunction) ();

   static const GeneralFunction doActionsArray [5];

};  // end of class foo

 // array of function pointers
const foo::GeneralFunction foo::doActionsArray [5] =
  {
    &foo::doAction0,
    &foo::doAction1,
    &foo::doAction2,
    &foo::doAction3,
    &foo::doAction4,
  };

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting"));

  // test instance of foo
  foo bar;

  for (int i = 0; i < 5; i++)
    {
    // get member function pointer from array
    foo::GeneralFunction f = foo::doActionsArray [i];
    // call the function
    (bar.*f) ();
    }

}  // end of setup

void loop () { }

This will also save RAM, as the array of function pointers only exists once, not once per instance of the class.

See amended answer. The second method is a bit simpler and uses less RAM.

First you need a header file - let's say lib.h:
#ifndef LIB_H
#define LIB_H

typedef void (*num_func) ();
extern num_func functions[];

#endif

And then the implementation, lib.cpp:
#include "lib.h"

void zero();
void one();
void two();
void three();
void four();
void five();
void six();
void seven();
void eight();
void nine();

num_func functions[] = { zero, one, two, three, four, five, six, seven, eight, nine};

The functions could be declared as static (if you want to hide them) and they do need implementation. They are only forward declarations above. Below is a snippet of a sketch using the library (assuming that it is within the sketch folder).
#include "lib.h"

void setup()
{
  ...
}
void loop()
{
  ...
  // Call to the one() function
  functions[1]();
  ...
}

Cheers!


text:
What's the difference between #define and const int when declaring a pin?
Over the course of my Arduino usage and learning, I've noticed that in some sketches people use the #define command to declare pins, while some others simply use const int for the same.
My question is, what's the difference between the two, and which one should be preferred for use?

I guess that you mean #define instead of #include. The more professional way to declare pins is const int myPin = ... This helps the compiler understand that it is a constant value and storage is not required. This is slightly better than #define as it gives the compile information about the data type.

@MikaelPatel exactly... so basically the int method is better right?

Yes. Please update the title and remove "include". That is something totally different and not related :)

I usually prefer to use enum for integer or character constants rather than either #define or const int.  See accepted answer to  Is it better to use #define or const int for constants?,

"#define" is a preprocessor directive. It defines a lable and a value, that will be positioned in the preprocessed-source-code at the same place of each occurence of the label. No type is defined, so it is a basic and dumb substitution of strings before compilation. It can then lead to errors or misunderstandings during compilation.
"const int xxx" defines a type, and locks the value of that instance. It's safer to use this method. The compiler can check for type errors and throw messages (or break compilation) if you made a mistake.
Example:
#define A 5
int dummy_integer = A

... will be preprocessed as...
int dummy_integer = 5

... and the compiler will read this statement.
However, if I remember good, you can always overwrite a preprocessor directive as follows:
#define A 5
int dummy_integer = A
//some code here
#undef A
#define A "my_string"
std::cout << A

That's not good. By using the "const" modifier, instead, you can't change the value (nor the type) of a variable (and so it's defined "constant").


text:
Using a state machine
I'm trying to get a strip of Neopixels to circle through its length, one LED at a time, I want it to do it faster as the value received from the sensor increases
#include <FastLED.h>
#define NUM_LEDS    34
#define DATA_PIN    6
#define SENSOR_PIN  A0

int airPressure,
    barometricToRGB,
    frequency       = 0,
    high            = 0,
    low             = 600,
    interval        = 50;

long previousMillis = 0;

CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(115200);
  pinMode(SENSOR_PIN,INPUT);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  airPressure = analogRead(SENSOR_PIN);
  autoTune();

  unsigned long currentMillis = millis();
  Serial.print("frequency ");
  Serial.println(frequency);
  Serial.print("Time to beat ");
  Serial.println(frequency*interval);
  Serial.print("Last Called ");
  Serial.println(currentMillis - previousMillis);

  if(currentMillis - previousMillis > (frequency/interval)) {
    previousMillis = currentMillis;

    for (int i=0; i<NUM_LEDS; i++) {
          leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB);
          FastLED.show();
        }
  }
}

void autoTune() {
  if (airPressure < low) {
    low = airPressure;
  }
  if (airPressure > high) {
    high = airPressure;
  }
  barometricToRGB = map(airPressure, low, high, 1, 255);
  barometricToRGB = constrain(barometricToRGB, 1, 255);
  frequency = map(airPressure, low, high, 1, 100);
  frequency = constrain(frequency, 1, 100);

}

While I had managed to cause the color to change based on the sensor, I can't seem to understand how to control how fast it will go, every how long.

Can you copy and paste the code into the question please? It isn't long.

Ok, if I understood what you meant, you want that a single led in the ring is on and the refresh rate is dependent on the pressure, right?
If so, you did not write any "select this led" code, so it can't work.
I fixed a couple of things in your code. Mainly:

added the circularity to the ring (with variable currentlyOnLed)
fixed some types (use the byte unless you need a bigger type)
removed some constrains, which were reduntant
frequency*interval instead of frequency/interval (I guess it was a typo)
I prefer summing the step instead of setting previousMillis to currentMillis, so you will not add error with time passing
moved FastLED.show() outside the loop: I'm not sure about this, but I think that you don't need to call it every loop. I can't test it, anyway.

So, here is the fixed code. Let us know if it works for you
#include <FastLED.h>
#define NUM_LEDS    34
#define DATA_PIN    6
#define SENSOR_PIN  A0

int airPressure;
int high  = 0;
int low   = 600;
byte barometricToRGB;
int frequency = 0;
byte interval = 50;
byte currentlyOnLed;

long previousMillis = 0;

CRGB leds[NUM_LEDS];

void setup() {
    Serial.begin(115200);
    pinMode(SENSOR_PIN,INPUT);
    FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
    currentlyOnLed = 0;
}

void loop() {
    airPressure = analogRead(SENSOR_PIN);
    autoTune();

    unsigned long currentMillis = millis();
    Serial.print("frequency ");
    Serial.println(frequency);
    Serial.print("Time to beat ");
    Serial.println(frequency*interval);
    Serial.print("Last Called ");
    Serial.println(currentMillis - previousMillis);

    if(currentMillis - previousMillis > (frequency*interval)) {
        previousMillis += (frequency*interval);

        //Set next on led
        if (currentlyOnLed >= NUM_LEDS - 1)
            currentlyOnLed = 0;
        else
            currentlyOnLed++;

        for (byte i=0; i<NUM_LEDS; i++) {
            if (i == currentlyOnLed)
                leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB);
            else
                leds[i] = CRGB::Black;
        }
        FastLED.show();
    }
}

void autoTune() {
    airPressure = constrain(airPressure, low, high);
    barometricToRGB = map(airPressure, low, high, 1, 255);
    frequency = map(airPressure, low, high, 1, 100);
}

That's amazing! This is very thorough, and thoughtful. Thank you so much

You are welcome ;) and... I don't know if it is you or someone else who needs to accept the edits in the original post. I just added the code (so it was cleaner and, moreover, links can break)

Are these reversed?
high            = 0,
low             = 600,

It looks like high and low both get set to airPressure on the first pass through autoTune(). If the pressure drops after this, for example, low will track airPressure and high will stay the same.
Also, with frequency 1 to 100 and interval 50 the largest time difference is 2 milliseconds and the smallest is 0.  Your loop could be taking 2 ms without the if statement.


text:
Resetting 16U2 Processor on Uno (R3)
This question got me thinking, the OP was wondering about how to "bring back" Leonardo boards connected to a Raspberry Pi via USB. The Leonardos would occasionally drop off line and could not be brought back by resetting the board.
So I got curious and hooked a Uno up to a Pi via USB and started poking around. I had the idea that perhaps resetting the 16U2 would do the trick. It does not. After resetting the 16U2 (by grounding the reset pin in the ICSP connector). This is what I see in the kernel log on the Pi:
[ 6277.570058] usb 1-1.3: USB disconnect, device number 11
[ 6278.576503] usb 1-1.3: new full-speed USB device number 12 using dwc_otg
[ 6278.684793] usb 1-1.3: New USB device found, idVendor=03eb, idProduct=2fef
[ 6278.684823] usb 1-1.3: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 6278.684841] usb 1-1.3: Product: ATmega16U2 DFU

As opposed to this:
[ 6325.960510] usb 1-1.3: USB disconnect, device number 12
[ 6329.267003] usb 1-1.3: new full-speed USB device number 13 using dwc_otg
[ 6329.382675] usb 1-1.3: New USB device found, idVendor=2a03, idProduct=0043
[ 6329.382703] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 6329.382720] usb 1-1.3: Product: Arduino Uno
[ 6329.382736] usb 1-1.3: Manufacturer: Arduino Srl
[ 6329.382753] usb 1-1.3: SerialNumber: 75431343334351F061E2
[ 6329.384088] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device

Which is what I see if I unplug and replug the USB cable.
I'd like to know what happens differently during a 16U2 reset vs. an unplug/replug cycle.
I'd also like to know if there is a way to simulate unplugging and replugging the USB cable. The 16U2 reset comes close (the Pi notices that something happened), but it would be nice if there were a way that either code on the Uno or on the Pi could "wake up" a down USB link.

What I think is happening here is that the HWBE fuse is set (hardware boot enable).
From the datasheet:

The Hardware Boot Enable Fuse (HWBE) can be programmed so that upon
  special hardware conditions under reset, the bootloader execution is forced after reset.

What this means is that under normal booting (power-on reset) the bootloader is not entered, and the device immediately identifies as a TTY device (ttyACM0) as you saw:
[ 6329.384088] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device

However if you manually reset it, it enters DFU mode with its bootloader, so you can reprogram the main code. Thus it identifies differently:
[ 6278.684841] usb 1-1.3: Product: ATmega16U2 DFU

Thus, a forced reset via the Reset pin acts differently to a power-on rest. By design.

If you search for uno enter dfu mode you will get quite a few hits. People use that technique to reprogram their ATmega16U2 (eg. to act as a MIDI interface).

FWIW, this is true on the R3 in particular because the HWB (PD7) pin is pulled low, which is checked on reset (aka. warm boot). In previous revisions you had to do that manually via a jumper on the reverse side of the board.
On the other hand, a fresh ATmega16U2 from the factory will boot to DFU mode on cold boot (eg. the cable replug scenario described by the OP) either because the default application code jumps to it (ref. chapter 23.6.1) or (my guess) because the BOOTRST fuse is programmed that way (ref. chapter 23.6.2).


text:
Protocol options for data exchange between Arduino and ESP8266
I have a device built with an Arduino uno:

Arduino software installed on an Arduino uno
can be controlled via serial commands
can be controlled via physical buttons and sensors
on any button/sensor state change it writes the current state to serial
if no message has been sent within 5 seconds, it sends a no-change serial message

What is needed:

Use an ESP8266 to provide a bridge between current Arduino software and MQTT / web
I can program the ESP8266 as a web server, MQTT client, etc with the Arduino IDE or Lua (but I prefer the Arduino IDE since I can reuse parts of the code to generate / interpret communication).
the ESP8266 will handle everything that is required for wifi / web / MQTT; without the MQTT module the Arduino part will work stand-alone, only the remote control will be missing.
I would like to make minimal changes to the Arduino code (or none, if possible). Any changes would involve extensive re-testing, which I try to avoid.
the ESP8266 can be missing in some installs.

What options I found:

Serial

ESP8266 can read the serial output and be a bridge between web/MQTT and serial, will store the current state in memory to be sent when requested to avoid polling the device every time.
One of the benefits is no code changes / testing required for the Arduino part.

I2C

Make the Arduino the I2C master and the ESP8266 the slave (or the other way around) and implement bi-directional communication. Got the idea by reading this thread.

Some other information about the serial commands:
A data packet (command or state description) consists of 1 to 20 characters, with a possible peak of 20 packets in 5 seconds, and an average of one packet every 3 seconds. If needed, I can make this send 5 unsigned integers instead of alphanumeric characters.
If more than the I2C / serial pins are needed I can upgrade to an Arduino Mega (so the number of free pins is not an issue).
Are there any other options for this? (protocols, pre-made libraries for serial communication, etc). I'm trying not to reinvent the wheel..
Thank you for your time!

Firmata (https://github.com/firmata/protocol/blob/master/protocol.md) is one such existing communication protocol. However it's not clear what you want - you have already defined and built the serial protocol and you say you would rather not change that code... If that's the case just code your ESP to grab the serial data, parse it and send it to the web/MQTT server.

Using I2C (which i recommend over serial), you may not use a NodeMCU ESP8266 as a slave.  It can only function as master.  An Arduino, on the other hand, may be either.  Therefore, the Arduino will always be passive and the NodeMCU will be the master.
What you can do, is implement a semaphore (as described by Majenko here), where the Arduino signals that it has something to "say" to the master, causing the master to request from the Arduino.  It could, under these circumstances, be labeled an "obliging master" (neologism).
NEVER print to serial from inside requestEvent or receiveEvent.


text:
How to setup Uno + xbee shield 1.1 + wee wifi chip?
I am an absolute beginner with electronics and Arduino.
I have this hardware:

arduino uno
xbee shield 1.1
wee wifi chip

I've tried to make them work (to connect my Uno to the Internet) but I can't find the right tutorial.
Are there good resources I should look at, or do you know how set this up?

As far as the Wi-Fi and Uno is concerned, it's not too difficult. You should download its library for Arduino, which is available on Github and then try its example named Wifi Client.
In this example, change your SSID and password, and run serial terminal. It will show you that your Arduino is connected to Wi-Fi and it will also display your IP Address.
Now enter this IP address in your browser and it's like you are pinging your Wi-Fi shield.  Soon it will display your analog values. Just make sure your computer and your Wi-Fi chip are connected to the same Wi-Fi connections.

Thank you for your help. I try to make it work but I am such a noob that I would need a step by step tutorial.

I'd suggest taking this in small hunks. If you haven't done it already, your first step should be to get your development environment together. Use it to create and upload a simple test. The Blink sketch is a common place to start. There are excellent tutorials at the Adafruit site, the have a whole series for getting started with the Arduino.
After you've gotten far enough with the basics to start feeling confident. Try searching for a tutorial for your project. You can often find them by searching on Google – try something like "arduino xbee shield tutorial" – look for descriptions that sound like what you want to do and try reading them. Another good place to look for tutorials is on sites that sell the hardware you're interested in using. For example Adafruit has this tutorial on getting started with the Xbee.
As you work through the tutorials, come back with more questions. As you get more experience it will be easier to ask specific questions and those are easier to answer :-)


text:
Generating a 38 KHz signal without timers
I am currently trying to generate a 38 KHz signal for my TSOP4838 (http://www.vishay.com/docs/82459/tsop48.pdf) with an ATtiny84A.
I know the real thing would be to utilize a timer but the ATtiny only has 2 Timers (T0 and T1). Timer1 can not be used because it is already used by other features.
I don't want to transmit actual data to the TSOP4838. I only want to use it as a light barrier (Iknow there are better ICs for that but I am stuck with the ones I already have).
So what I have tried so far is setting up timer0 for my PWM stuff and everything worked IR LED-wise. The delay functions (micros(), millis() etc.) stopped working and prevented me from using my serial communication. I tried to change the code in wiring.c to use a prescaler of 1 instead of 64 by changing the defines but that didn't work out.
I am now stuck with two options I guess:
A: somehow modify timer0 to generate my 38 KHz signal and still provide correct functionality for the timing functions.
B: let timer0 be initialized the way the Arduino wants it and utilize the delay functions to blink the IR LED.
I would prefer A but Google didn't give me a solution. Maybe some of the gurus around here could help?
If A is not possible can somebody give me a hint how to "bit bang" the IR LED with delay? (I guess that is a silly question but I can't figure it out at the moment :()

Sorry, but.... are you really using a microcontroller to generate a 38khz square wave and nothing more?

A 38kHz square wave at 50% duty cycle would be a transition running at 38x2=76kHz.  That is 1/76,000 = 0.000013158s, or 13.158µs.  That's quite a high accuracy to try and achieve with delays on a small chip like the 84A.
I assume you are running it at 8Mhz (internal calibrated RC oscillator) - that means each clock tick is 1/8000000=125ns long. so 13156ns would equate to 105.248 clock cycles. That can't happen, so the closest you would get is 105 clock cycles, which would be 13125ns, or 76.190kHz, or an end frequency of 38.095kHz.  So fairly close.
So now you need to create a tight loop that is exactly 105 clock cycles long including the toggling of the IO pin and the comparisons and branches for the loop.  For that you need to do some careful instruction cycle counting and work in assembly language.  Page 268 of the data sheet details the clock cycles used for each instruction.
The simplest (though most long winded) loop would be an OUT or SBR (depending on port) instruction (1 clock) to set the IO pin HIGH, then 104 NOPs (1 clock each), then an OUT or CBR to set it LOW (1 clock), then 102 NOPs (1 clock each), then an RJMP to go back to the start (2 clocks).  That is then a grand total of 210 clock cycles, or 1/(210*0.000000125) = 38.095kHz.
You could compress all the NOP instructions down into a tight loop themselves by setting a register to a pre-defined loop count value, decrement it each pass - repeat if it's not 0. That means even more careful instruction counting to get that loop to equal the 104 or 102 clock cycles needed for the precise timing.
However all that is pretty much academic, because the loop will keep being interrupted by your timer 0 interrupt and cause jitter in your output as the interrupt routine is being run instead of your IO pin driving loop.
If you don't need absolutely reliable timing anyway it might be easier (though far less accurate) to use the micros() function to find when 13µs have elapsed and do it all in C instead of assembly.  You will still need high speed direct port access rather than using digitalWrite() since digitalWrite() adds way too much overhead to be able to do that kind of timing reliably.  Something like:
uint32_t start = micros();
while(1) {
    if (micros() - start >= 13) {
        start = micros();
        PORTB ^= 1<<4; // toggle B4
    }
}

Note the use of while (1) there rather than relying on the loop() function repeating itself.  There is quite a large overhead in using the auto-repeating of loop() that can be avoided by looping within it with a while (1) like that.  Of course, anything else you want to happen repeatedly would have to be inside that while loop, and most likely would impact your output timing somewhat.
So a much better solution would be to use a timer, since that is what they are there for.  But fidding with timers breaks things like millis() and delay().  So the answer to that is don't use millis() and delay().  Instead create your own timing functions that are controlled by your own interrupt that does the pin IO - instead of relying on a system provided tick you create your own.  If your interrupt is firing every 13µs then add 13 to a global counter - that counter is then the number of microseconds that have passed.  When that count exceeds 1000 you subtract 1000 (don't zero it) and add 1 to a millisecond counter.  Now you have the equivalent to millis() in a global (remember to make it volatile) variable that you can use instead of millis().

Thanks for the detailed answer ! I am using amtel studio with a cire that i compiled myself and therefore i am already not using loop or setup methods like i a arduino environment. I guess i'll try again to get the timer to do what i want. The bad thing is that i need to alter the TinyDebugSerial Class too because it seems to use the arduino milli functions...

I am using an arduino nano as frequence generator and it generated me a stable frequency with an error less than 0,1kHz. But the TSOP382 stops receiving after 200ms.  I have disabled all interrupts and made the on and off sequence equal.

It would be much easier to use a dedicated IC such as a 555 or a 556. I built such a system based on these circuits IR Bream Break Detector

The R/C combination used there yields 41 kHz. Better suitable would be 22 nF / 860 Ω (38.054 kHz) or 47 nF / 400 Ω (38.297 kHz).

Edit: As two resistors are necessary for the astable version, use Ra = 1.2 kΩ, Rb = 12 kΩ and C = 1.5 nF, yielding 38.095 kHz. Ra/Rb/C see NE555 Data Sheet.

Several approaches are possible, some of which, but far from all, have been listed in previous answers.  In following, I assume that by “use it as a light barrier” you mean that the TSOP4838 will be part of an object-intrusion detection system, rather than for transmitting data.  As a consequence, some jitter and/or inaccuracy is acceptable.  Note, all of the following methods assume that Arduino core code has set up timer 0 to support ordinary micros() and millis() calls.
Approach 1:  Compute or calibrate a simple loop:  In setup(), run a series of tests that find a value k to minimize error, via C code equivalent to the following Python:
for k in plausibleRange():
  err = genBurst19(k)
  if err < bestErr:
    bestErr = err
    bestK = k

where genBurst19() is like the following:
def genBurst19(k):
  t1=micros()
  for i in range(38):
    setPortBit(i&1)
    for j in range(k):
      nop
  t2=micros()
  return abs(t2-t1-500)

In other words, genBurst19() sends a burst of 19 cycles, which at 38 KHz should take 500 microseconds.  It returns a measure of error to the caller.
After finding bestK, you can subsequently use it as a limit for other delay loops, or could just use repeated calls to genBurst19(bestK) whenever you want to generate some "38KHz".
Note, you might wish to try some minor variations, such as adding a second or third nop in the inner delay loop, or generating some higher multiple of 19 cycles.  While a delay loop containing a single nop (or no nop at all, just an empty loop) has finer resolution than a loop with multiple nops, it may happen (depending on loop code) that a smaller error occurs with more.  [But also see Approach 3 regarding fine tuning.]
Summary:  This method is easy to use, has low jitter, but is limited in the accuracy it can attain.
Approach 2:  Use a method analogous to Bresenham's to produce a signal with high-accuracy period, on the average, but with more jitter than Approach 1.  Bresenham's algorithm tries to draw a straight line, on an x-y grid of pixels; you are trying to draw a straight line, on a time-vs-cycles grid.
In this method, you keep track of how many microseconds total should have elapsed, and when you fall too far behind, issue a delay with k-1 instead of k, to catch up; or if too far ahead, with k+1, to drop back.  See my answer to stackoverflow 8113883 for a little more re Bresenham's method, in the line drawing context.
Summary:  By applying Bresenham's method, you can get the average frequency as close as you like (when averaged over a few milliseconds).
Approach 3:  This is more of a fillip than a whole approach.  It modifies Approach 1 by adding the following C code before the for j in range(k): nop loop.  It also needs a second parameter, l.
switch (l) {
  case 9: nop;
  case 8: nop;
  case 7: nop;
  case 6: nop;
  case 5: nop;
  case 4: nop;
  case 3: nop;
  case 2: nop;
  case 1: nop;
  case 0: ;
}

To use this approach, first find the best k using a series of calls like err = genBurst19(k,5).  Then find the best l via err = genBurst19(bestK,l) for l from 0 to 9.  [Note, a number smaller than 9 can be used in the above, if the for j in range(k): nop loop uses fewer cycles.]
Summary: This fillip can tune genBurst19() closer to single-nop accuracy.

I just built an NE555 based circuit for 38 kHz. Sender is a 950 nm IR diode, receiver is said TSOP4838. According to the NE555 Data Sheet, the frequency in astable mode is approximately
f ≈ 1.44 / (C (RA + 2 RB) )

Using values of RA = 1.8 kΩ, RB = 18 kΩ, C = 1 nF, the NE555 should generate a frequency of 38.095 kHz. Using these values, my circuit generated 34 kHz with some small changes of a few 100 Hz when using different resistors/capacitors (due to tolerance), but it came nowhere close to 38 kHz. This is probably because the frequency formula is an approximation. The easiest fix is probably to put a variable capacitor in parallel to C and use it for fine tuning, or a variable resistor to RB.
This may not be necessary in every case as the TSOP48xx uses a band pass filter, and 34 kHz are still recognized, only at lower responsivity. Note that this IR receiver (as well as others) have some limitations on pulse length, so you cannot constantly send 38 kHz but only for up to 70/f, which is around 1.8 ms. After that, the TSOP output switches off again, probably because the internal threshold is raised.

Measurements
Some measurements from a logic analyzer (PulseView). This is from the above NE555 circuit which should yield 38 kHz.

I used an AND IC (74HCT08) to modulate a signal, generated by an Arduino, on top of the 38 kHz carrier. Sampling rate is 12 MHz. The probes measure:

D0: TSOP4838 output signal
D1: IR signal (carrier AND signal)
D2: Arduino signal
D3: 38 kHz carrier from NE555


text:
GSM GPRS module not getting any output from Rx , Tx
I am using a SIM800 GSM/GPRS module. I connected it using 4 wires: Vcc 3.7 volt (2 amp supply), RX and TX and GND.  Whenever I try to send a command it shows me nothing. Here is my code.
//Serial Relay - Arduino will patch a
//serial link between the computer and the GPRS Shield
//at 19200 bps 8-N-1
//Computer is connected to Hardware UART
//GPRS Shield is connected to the Software UART

#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);

unsigned char buffer[64];  // buffer array for data receive over serial port
int count=0;               // counter for buffer array

void setup() {
  GPRS.begin(19200);
  Serial.begin(19200);
}

void loop() {
  if (GPRS.available()) {
    while(GPRS.available()) {
      buffer[count++]=GPRS.read();
      if(count == 64)break;
    }
    Serial.write(buffer,count);
    clearBufferArray();
    count = 0;
  }
  if (Serial.available())
    GPRS.write(Serial.read());
}

void clearBufferArray() {
  for (int i=0; i<count;i++) {
    buffer[i]=NULL;
  }
}

It is an independent module. I've already read the hardware manual and AT command manual. I did everything according to the manual.

Are you sure the baud rate is correct? You could try 115200 and 57600. Is the serial monitor set to "Carriage Return" or "Both NL & CR"? If this isnt set, the modem won't respond to your commands since it requires a '\r' to terminate every command. Is there any indication that the modem is powered (like the net LED blinking)? Your code looks alright but, to be sure everything's okay, use this test program to interact with the modem using the serial monitor; just change your loop() to this:
    void loop(){
        while (Serial.available())
            GPRS.write(Serial.read());
        while (GPRS.available())
            Serial.write(GPRS.read());
    }

This way, everything you type in the monitor will be relayed to the modem and everything from the modem will be relayed to the PC, all via the arduino.

There doesn't seem to be anything wrong with your code.  I'm going to assume you have got the right VCC and the right Serial speed.
Do you have a way of connecting the device directly to your PC and then using a terminal emulator to see if the device is talking?
Is there a library that you could use?  Maybe there is some setting that you need that isn't documented.