text:
Reducing noise and finding sampling rate
I have Arduino Due R3 (84MHz) and I am trying to find the mean of value from AnalogRead. I have to set the sampling rate of 8000 samples/second with 4 channels. I tried using for loop for this purpose.
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int i = 0;
int sensorPin = A0;
int sensorValue = 0;
int highest=0;
int lowest=0;
float mean=0;

void setup()
{
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  lcd.print("Hello");

}

void loop()
{

  for(;;)
  {
    mean=0;
    for(i=0;i<8000;i++)
    {
       sensorValue = analogRead(sensorPin);
     highest=max(highest,sensorValue);
     lowest=min(lowest,sensorValue);
     mean = mean + (highest-lowest);
    }
    mean = mean/8000;
    delay(10);
    lcd.setCursor(0, 1);
    lcd.print(mean);
  }

Will this set sampling rate to 8000 samples/sec ?
Also I was receiving  a lot of noise at A0 which often led to the lowest value to be 0. In the image : The  red wave is a constant dc voltage of 2.7 V from power supply.

How do I overcome this noise so that mean value is accurate and precise ?

Just to as a complement to Majenko's answer (which I second), there are
a couple of flaws in your program that may be related to your problem:

lowest is always zero, as it is initialized to 0 and cannot increase
your computation of the mean is incorrect: the mean is the sum of the
readings divided by their number
you fail to reset lowest and highest between consecutive runs of
8000 samples
there is no point in putting all of loop() inside an infinite loop.

Assuming you really intend to print summary statistics on runs of
8000 samples, as your code suggests, I would write it like this:
const int SENSOR_PIN = A0;
const int SAMPLE_COUNT = 8000;
const uint32_t SAMPLE_PERIOD = 125;  // 125 us

void loop()
{
    long sum = 0;
    int lowest = INT_MAX, highest = 0;

    uint32_t lastTime = micros();
    for (int i = 0; i < SAMPLE_COUNT; i++) {

        // Wait until it's time.
        while (micros() - lastTime < SAMPLE_PERIOD) ;
        lastTime += SAMPLE_PERIOD;

        // Take and process the sample.
        int sensorValue = analogRead(SENSOR_PIN);
        sum += sensorValue;
        highest = max(highest, sensorValue);
        lowest = min(lowest, sensorValue);
    }
    float mean = (float) sum / SAMPLE_COUNT;
    Serial.print("mean: "); Serial.print(mean);
    Serial.print(", minimum: "); Serial.print(lowest);
    Serial.print(", maximum: "); Serial.println(highest);
    Serial.flush();
}

Edit: I changed the code in order to keep a roughly constant
sampling rate of 8000 samp/s. The main change is that, before
taking a reading, we wait until it's time to do so (until
micros() - lastTime >= SAMPLE_PERIOD).
Note that lastTime could be updated with lastTime = micros(), in
which case it would have hold the time we last took a sample. By
updating it with lastTime += SAMPLE_PERIOD it instead holds the time
we shoud have taken the last sample. This is the right choice for
enforcing a given average sampling rate.
Running on an Uno: I have no experience with the Due, but here are
some remarks that would apply to an Uno, or any other AVR-based Arduino:

analogRead() takes about 110 µs, which means we cannot sample
more than one channel, and we only have about 15 µs to process
the sample. Here the processing is simple enough that the Arduino can
do it in this limited time.
There is some jitter in the sampling, because micros() has a limited
resolution of 4 µs, because of the timer interrupt kicking in
from time to time, and because the while loop takes a finite amount
of time.

If I were to do something similar on an Uno, I would forgo
analogRead(), configure the ADC to be triggered by a timer, and set
the timer to trigger the DC every 125 µs. Not only would this get
rid of the jitter, it would also allow the CPU to do its job in parallel
with the ADC, instead of just sitting idle and waiting until the ADC is
done. This would allow for more complex per-sample processing.
About the Due: As I said, I have no experience with this board. It
has a more capable processor, but this tells you nothing about the speed
of its ADC. I would expect to face the same issues as with the Uno,
though maybe to a lesser degree. I guess it should be possible to
trigger the ADC from a timer, but I have no idea how to do so.

Thanks for the corrections. Actually I wanted to calculate maximum and minimum per cycle and then calculate the mean of their difference for the given number of samples. I have updated my code also. Sorry for Incovenience.Also how do I set the sampling rate to around 8000 samples/sec if I'm using 4 channels with Arduino Due R3 (84 MHz) ?

@SamThornton: About the sampling rate, see the expanded answer.

Thanks !! Just there is 1 doubt ? Why can't I use mutiple channels ? What if use nested loop like for(int i=0;i<4;i++) { for(int j=0;j<8000;j++) //take input and process }

@SamThornton: Yes, you can read one waveform on one channel, then another one on the other channel and so on. What you cannot do, at least with this scheme, is sample the four channels simultaneously at 8 kS/s. Unless your ADC is way faster than the ones on the AVRs.

Oh I see. Thanks ! BTW Is there a way to do it simultaneously ?

Will this set sampling rate to 8000 samples/sec ?

No, that will make it perform a block of 8000 samples as fast as it can. There's absolutely nothing in there that has anything to do with time, so how can "seconds" be included in the description of it?

How do I overcome this noise so that mean value is accurate and precise ?

That depends on where the noise is coming from. Maybe if you slowed down your sampling you wouldn't get the noise. Maybe if you made a better connection to whatever it is you're sampling you'd get less noise. Maybe if you added some external filtering you'd get less noise. Maybe if you used a different mathematical model for determining what your average value is you'd not care about the noise.

Can you tell me the way to calculate the mean such that I don't have to care about the noise ?


text:
Compiling source with Arduino.h with avr-g++
How should I include the Arduino libraries when I'm compiling from the the command line? I tried to do it like this:
avr-g++ -g -Os -Wall -mcall-prologues -mmcu=atmega328p -fno-exceptions -o blink.obj blink.cpp -L. -lutil -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" -I"D:\Projects\Arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores"

but it returns undefined reference to the function that I am trying to use.
Arduino version: 1.8.2

You need to do a whole lot more than just run the one command.
You need to compile each individual source file for the libraries you want (using -c to just compile and not link), then (ideally) archive them into a library file. Do the same for the core. Then you need to add paths to your sketch compilation command pointing to where the header files are for those libraries, and compile the sketch to an object file (again with -c). Finally you need to link everything together into an ELF file, and convert that to a HEX file.
TBH you're best off using an already-existing Makefile project, or arduino-builder.

source: Stack Exchange

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

sort: votes


text:
Decoding 2.4G RF remote controller?
There is tons of information on how IR remote controls work and how to use an Arduino to decode those signals and use any IR remote to suit your project. But I couldn't find much info about 2.4G RF remotes.
I want to control a string of addressable LEDs and cycle through different patterns using one of these 2.4G RF remotes

Is it possible to use these remotes with Arduino? If yes, how can I read the signals and assign tasks to different buttons on the remote?

First step would be to open it up, and see what chip is inside. Just the 2.4GHz isn't saying very much, as 2.4Ghz is also used by WiFi, Bluetooth, some Zigbee. All different kinds of encodings and protocols.

The usual approach for 2.4 GHz is to open the product, identify the radio chip, and use a USB logic analyzer on the SPI bus that usually connects it to the MCU to capture the configuration and data traffic, and figure out what the configuration register accesses mean from the radio chip data sheet.
The occasional appearance of combined MCU/radio parts prevents that approach, but often that is only used on one end of the link and the other will still have a distinct MCU and radio with an SPI bus in between.
This is heavily practiced in the radio control community, as people want to use their nice transmitters to fly cheap toys.  And there is code out there to transmit compatibly with some of the odder chips like the X297, using more common ones like the NRF24L01 or its workalikes from Beken, etc.
A key advantage of SPI sniffing versus over-the-air sniffing is that the usually implemented channel-hopping doesn't mean you loose the signal ever time it moves to a new channel - and you actually get to the see the frequency registers being written.  To capture a hopping scheme over the air, you would need something more like a spectrum analyzer to figure out the sequence, and then have software track the signal while you attempt to figure out the data.  However, a remote which only sends occasional button presses may not use hopping in the way something sending data continuously (like an R/C set, or possibly a keyboard/mouse) would.

I was having same issue and at the end of the day I have made it working. For the communication I have used openmili library  (project started by Henryk Plötz who has reverse engineered protocol for communication of these remotes). This didn't work with new remotes as they have changed couple of things:

Listens on a different channelset (this was true of different bulb types among the old bulbs too). The new bulbs use channels 8, 39, and 70.
Different PL1167 syncword. It uses 0x7236 , 0x1809 .
Packets have 9 bytes instead of 7.
Packets are scrambled. The same command can look completely different.

(information taken from Chris Mullins blog)
Confirmation of these info I have found in ESP8266 Milight hub project where I have found config for remotes (https://github.com/sidoh/esp8266_milight_hub/blob/master/lib/Radio/MiLightRadioConfig.cpp)
In my case I was using rgb+cct remote so it tells me that I should use 0x7236, 0x1809 as syncwords, packet length 9 and channels 8, 39, 70.
Applying those changes I was able to get data from the remote. One more usefull link.

If it is based on the nRF24L01+ (or the nRF31512C SoC, which is a combined MCU and nRF24L01+ in one chip, and used in most wireless mice and keyboards) then it may be possible to sniff the signal. If not, you're probably not going to have much luck.
You'd be better off trying to hack the existing receiver that is paired with the remote to get usable signals out of it.

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

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


text:
How do I connect through a HC-05 to PS4 Controller?
Searching for Arduino and PS4 on google, I find always the same construction using a USB host shield and a Bluetooth dongle.
But I'd like to connect a PS4 Controller to a HC-05 device. Is it possible? If not, why not?

The HC-05 uses the Bluetooth Serial Port profile (SPP). The PS4 controller doesn't.
Hence you need something that is capable of using the same profile that the PS4 controller uses (HID?). And to that end you need something a little more configurable than a simple HC-05. One option is, as most people use, a USB Host shield with a Bluetooth dongle that can then be configured to communicate using the right profile.

@NikX see https://en.m.wikipedia.org/wiki/List_of_Bluetooth_profiles

So, how do I get to know which profile a bluetooth device uses? assuming the ps4 controller uses HID, I think this could be a way to connect a hc-05 to ps4 controller.

I upgraded my HC-05 to RN42. With some experimenting it seems like it's possible to connect to the PS4 Controller. At least I could detect the controller.


text:
Searching for a good keypad
I'm wanting to make a keypad for my gragedoor. I found one like this but i don't think it is very waterproof.
Now i'm wondering if someone of you know a good keypad that can be used outdoors and can be connected to a arduino (preferably arduino nano).
Hope you can help.
Edit if found this keypad will i be able to program this one with a arduino?
link

Look for the keyword "IP65" in your searches.

I'm voting to close this question as off-topic because questions seeking recommendations for specific products or places to purchase them are off-topic as they are rarely useful to others and quickly obsolete. Instead, describe your situation and the specific problem you're trying to solve.

You can connect almost any keypad to an Arduino that does not have active circuitry (by active I mean the keypad has it's own MCU etc.), those with active circuitry might need some more work due to incompatible logic voltages or custom protocols.

@Avamander could you check out the keypad i just linked in my question? I think this one could work

It's an USB keyboard by default, Arduinos don't usually do USB. (It's also tad expensive, search more)

The membrane keyboard you have linked (first link) in your question should be water resistant, if not water proof.
We use something similar at my work. You can have the keypad stuck to the outside of the enclosure and then have a rubber seal (or silastic) sealing where the ribbon cable enters the enclosure.

You will notice that the ribbon cable pretty much exits the bottom of the keypad. The better ones to get, if you can find them, are the ones where the ribbon cable exits the keypad further away from the edge (see example image below). That way the adhesive backing of the keypad seals the cable entry into the enclosure.

As far as hooking it up to an Arduino - no problems at all. A 16 key matrix keyboard has 8 connections, 4 for each row and 4 for each column. Every time you press a key, the row and column are shorted together.

The way I would connect it up is to have the rows connected as inputs and the columns as outputs. One by one I would turn one of the columns on (HIGH) and see which input(s) are reading a HIGH. If it is I know that that key (row and column) is pressed. This method will handle multiple keys pressed at once.
There is an walk-through tutorial posted at instructables.com.
The more expensive keypad in your second link and this one both have the option of connecting by PS2. There is an Arduino page on connecting and controlling a PS2 keyboard here.

Thanks for the amazing answer but i would like to put this at the front of my house and i dislike the looks of it :). Thats why i found the more expensive one, now i was wondering if i could use that one on a arduino?

The more expensive one and this one  both have the option of connecting by PS2. http://playground.arduino.cc/Main/PS2Keyboard

Thank you! So every keypad with a ps2 connector "should" work?

"Should" is the right word. I have never tried it myself. Why not find an old PS2 computer keyboard and give it a try before you buy the keypad.

This one has a PS2 connector aswel and it has backlit:
https://www.aliexpress.com/item/Industrial-waterproof-metal-led-backlit-illuminated-keypads-with-12-keys/32812155017.html?spm=2114.40010208.4.6.MGManS

That keypad and the original metal one both have the line"Matrix output or standard USB/PS2 output  with controller". Looks like it has the matrix output as well. Worth a try!

I got it working! :) Now i'll buy the keypad thanks for everything!


text:
New Microcontroller - programmer is not responding -
I got an Arduino and after I was playing with it, I noticed that its internal micro controller si removable and decided to buy another micro controller. After I got the new one (atmega328P) and replaced with the original which came with the Arduino, I started to upload a sketch but it does not work.
I get the following:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

If I use the Original MC which came with the Arduino works fine, but with the new one it does not.
Did I buyed a bad/wrong MC, or I need to make something else?
Both have the same name :
ATMEGA328P-PU

The new micro controller has already a boot loader installed.

The new micro controller has already a boot loader installed. -- Are you sure? I have bought cheap chinese Nanos that haven't had a bootloader installed. If you don't buy it from a reputable source there is no telling what you may get. If in doubt program the bootloader on it yourself. Also make sure you set the right fuses on it.

@Majenko Also make sure you set the right fuses on it I do not understand this part. I plugged it the same how the original was. I also have two boards, and I followed Youtube tutorials about installing the boot loader and I installed the boot loader again and worked fine. But, after i decided to upload a sketch, got those errors

That's basic knowledge you should have before you start working with any microcontroller. The "fuses" tell the chip how to operate. What clock source to use, what boot vector, etc. All important stuff and has to be correct. You would normally do it before (or as part of) programming the bootloader.

@Majenko I followed this Tutorial and I had no problems.

http://heliosoph.mit-links.info/arduinoisp-reading-writing-fuses-atmega328p/

I managed to fix the problem by downloading the latest version of the Arduino IDE from their website and works fine now.
I use Linux mint 18 and installed Arduino via apt and I really do not know why I managed to install the boot loader, but failed with uploading the Sketches.

Likely you were trying to talk to the bootloader at the wrong baud rate, or were talking the wrong serial port.  If you only have the single board mentioned and no dedicated programmer or second arduino board to use as one, you haven't actually (re)loaded a bootloader.


text:
Air quality sensor reading meaning
So I got this air quality sensor running, and it's outputting some numbers.
I've read some tutorial online and it looks like the smaller the number the better the air quality.
But I don't understand what is the meaning of those number. Like what is the unit of measurement? For example, the temperature sensor gives you numbers in Celcius degree.
http://wiki.seeed.cc/Grove-Air_Quality_Sensor_v1.3/

One of those MQ gas sensors ? They are electrochemical sensors. They can be calibrated more or less with a known concentration of a certain gas. But since the are often sensitive to a number of gasses, you do not know the concentration of that specific gas that was used for calibration.
A number that is going up and down is what you have. You can make a graph with it to show the value for each hour or each day.
The MQ gas sensors have a "preheat" or "burn-in" time. It is often 24 hours. Keep the sensor on for 24 hours to get more stable output values.
A temperature sensor is completely different, it contains electronics inside and has been calibrated at the factory. The MQ gas sensors are just a few wires, a heater and some chemicals.
[ADDED]
That is a module with the MP503 gas sensor. It just like the MQ sensors a electrochemical gas sensor. According to the datasheet it is sensitive for alcohol and smoke and the "preheat" or "burn-in" is called "aging time" and can be up to one week! The module has a amplifier.
The detection of gasses is according to a certain curve. To calculate the concentration of gasses a calculation is needed (and a calibrated sensor). I don't see that calculation in the supplied library. So all you have is numbers that change according to the air quality. That's all. And that is normal for these sensors.
Read the information and pdf files on that seeed page about this Grove module. It clearly says that you can't measure the concentration of gas (not "quantitatively"), you can only tell if the air quality gets better or worse (qualitative).

This actually http://wiki.seeed.cc/Grove-Air_Quality_Sensor_v1.3/

I have found that they will give false positives immediately upon power-on, so if they are being used for alarms you might want to build a delay into your program to allow it to heat up.   -- The datasheet says it takes 24 hours to reach factory specifications, but you might try giving it a few hours and see if it working well enough for your particular project.  Ambient temperatures are an issue, of course.  The cooler the environment then the longer it will take to become accurate enough.


text:
Raspberry Pi Outputting Signal to arduino
I have been trying to get my raspberry pi to output a signal of High or Low, which is then picked up by digital pin 4 on my arduino.
On the raspberry pi, I have connected the output to GPIO 24 and have set up a simple to circuit with an led and 220 ohm resistor in series to check if there was any output. I did manage to get the led to turn on and off due to typing commands into the console on the raspberry pi, so that can't be the problem.
For the raspberry pi side of things, I have installed the WiringPi library and typed these commands:
gpio -g mode 24 out

This set up the GPIO pin and then to turn them off, I used these independently.
gpio -g write 24 1
gpio -g write 24 0

For my code on my arduino, I have adapted a rtc with stepper motor piece of code that I am working on to go with this sub project.
#include <DS3231.h>
#include <Stepper.h>

//---( Number of steps per revolution of INTERNAL motor in 4-step mode )---
#define STEPS_PER_MOTOR_REVOLUTION 32

//---( Steps per OUTPUT SHAFT of gear reduction )---
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  // 2048

// Init the stepper object with sequence 1-3-2-4 for proper sequencing
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);

// Init the DS3231 using the hardware interface
DS3231 rtc(SDA, SCL);

const int raspiPin = 4;
int raspiSwitch = 0;

int  Steps2Take;

void setup()
{
  // Setup Serial connection
  Serial.begin(115200);
  pinMode(raspiPin, INPUT);

  // Initialize the rtc object
  rtc.begin();

  // The following lines can be uncommented to set the date and time
  // rtc.setDOW(SATURDAY);     // Set Day-of-Week to SUNDAY
  // rtc.setTime(22, 32, 50);     // Set the time to 12:00:00 (24hr format)
  // rtc.setDate(3, 6, 2017);   // Set the date to January 1st, 2014
}

void loop()
{
  // Read the state from the raspi
  raspiSwitch = digitalRead(raspiPin);

  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Declare variable for later testing against
  String myTime = rtc.getTimeStr();

  if (myTime == "17:00:00") {

    Serial.println("Rotating stepper motor at " + myTime + ".");

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  } else if (myTime == "08:00:00") {

    Serial.println("Rotating stepper motor at " + myTime + ".");

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  } else if (raspiSwitch == 1) {

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  }

  delay (1000);

}

When I use the else if statement to turn the stepper motor if there is a high signal from the raspiPin, the motor will turn even when the signal is low.
I used Serial.println to output the state of the raspiSwitch variable to the serial output and for some reason, it changes by itself between 1 and 0. I do not know why and would like to resolve this so I can move onto the next stage of connecting it to the internet on a php webpage.
If anyone could help, I would greatly appreciated it

First delete everything except initializing and printing the value of the pin from a copy of the sketch; especially disconnect the motor driver.  Then use something else like a wire connected to Vcc or Ground to source the input, and verify that you are reading the pin you are switching.

Is the ground of the Arduino connected to the ground of the Pi?

@ChrisStratton I will try that, thank you for your input.

@Majenko I have not currently got the ground from the arduino going to the ground on the pi, but the signal from the pi is grounded on the pi itself.

https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/

The Arduino and the Raspberry pi should have a common ground. Connect the ground pin of the Arduino to the Raspberry pi. Both boards should be powered by the same power source and connect a pull-down resistor from the digital pin of the Arduino to ground. about 10Kohms might be enough.


text:
Change Word Color
I tried to change the color of the words but nothing happens, I do not know what I'm doing wrong. I am using official Arduino editor of code with words.txt
#######################################
# Syntax Coloring Map For testing
#######################################

#######################################
# Datatypes (KEYWORD1)
#######################################

Test    KEYWORD1
Diego   KEYWORD1
Ulises  KEYWORD1
PALMA   KEYWORD1

#######################################
# Methods and Functions (KEYWORD2)
#######################################

doSomething KEYWORD2
Argentina   KEYWORD2
Brasil      KEYWORD2
Alemania    KEYWROD2
Chile       KEYWORD2

#######################################
# Instances (KEYWORD2)
#######################################

#######################################
# Constants (LITERAL1)
#######################################

The of this page www.Arduino.cc

ARDUINO 1.8.3, es aquí https://www.arduino.cc/en/Main/Software

An IDE is a tool that helps us to develop our applications in a friendly way

is the editor of code

I'm sorry my communication in English is not perfect .. Arduino ide or Arduino Aide I was referring to using the text editor

The question's reference to “official Arduino with words.txt” is rather ambiguous.  So far there has not been any clarification whether the question refers to the usual Arduino IDE environment.
However, supposing the question intended to refer to the usual environment, note that the Library Tutorial document at arduino.cc says to do the following to set up a list of highlighted keywords:

Create a file called keywords.txt in the [library] directory

Thus, renaming your words.txt to keywords.txt may solve the problem.

Just to clarify, tabs need to be used as separators in the keywords.txt file, as spaces will not work.


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

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

Bad Request - Invalid Header

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

closing connection

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

const char* host = "187.201.44.110";

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

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

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

  WiFi.begin(ssid, password);

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

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

void loop() {

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

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

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

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

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

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

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

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

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

Yeah, I solved my problem, thanks Majenko.


text:
HMC5883L not working in continuous mode!
I'm just starting with the HMC5883L, I'm writing my code with C and also my own I2C library.
I noticed that the values on the Arduino IDE's serial monitor are constant.
Then I developed a function to read the mode register. So the value should be 0x00 for continuous mode.
But, what I get is that the device work in single mode which has the value 0x01 at first cycle of the program, then it goes to idle mode with the value 0x03.
So, why is that and what to do?
#include <I2C.h>

#define HMC5883L_read   0x3D
#define HMC5883L_write  0x3C

#define Configuration_Register_A    0x00  //Read/Write
#define Configuration_Register_B    0x01  //Read/Write
#define Mode_Register               0x02  //Read/Write
#define Data_Output_X_MSB_Register  0x03  //Read
#define Data_Output_X_LSB_Register  0x04  //Read
#define Data_Output_Z_MSB_Register  0x05  //Read
#define Data_Output_Z_LSB_Register  0x06  //Read
#define Data_Output_Y_MSB_Register  0x07  //Read
#define Data_Output_Y_LSB_Register  0x08  //Read
#define Status_Register             0x09  //Read
#define Identification_Register_A   0x10  //Read
#define Identification_Register_B   0x11  //Read
#define Identification_Register_C   0x12  //Read
#define declination_angle 3.46

void HMC5883L_init (void);
int16_t data_read (int16_t *results);
uint8_t HMC5883L_read_reg (uint8_t reg);

int16_t results[3];
float m_scale = 1.0;

void setup() {
  // put your setup code here, to run once:
  I2C_init();
  Serial.begin(9600);
  HMC5883L_init();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
}

void loop() {
  // put your main code here, to run repeatedly:
  data_read(results);
  Serial.print("x-axis = ");
  Serial.println(results[0]);
  Serial.print("z-axis = ");
  Serial.println(results[1]);
  Serial.print("y-axis = ");
  Serial.println(results[2]);
  Serial.println();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
_delay_ms(500);
}

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

int16_t data_read (int16_t *results)
{
  uint16_t lsb,msb;
  int16_t status_of_process = 0;
  I2C_start(HMC5883L_write);
  I2C_tx(Data_Output_X_MSB_Register);
  I2C_start(HMC5883L_read);

  msb = I2C_rx();
  lsb = I2C_rx();
  results[0] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[1] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[2] = msb << 8 | lsb;

  I2C_stop();

  return status_of_process;
}

uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  Serial.println(reg_dat);
}

Regards,

Try it with the Arduino Wire library. Why did you make your own I2C library ?

Because I want to know how to activate communication protocols. I can't proceed to further topics in programming without knowing to how program SPI, I2C and USART, that's very important to me. Because I can't do advanced things before doing easy things like writing a library for I2C.

Perhaps it is more useful when you explore the PWM modes of the timers. It took many, many years (far too many years) until the Arduino Wire library for AVR microcontrollers was working well. You seem to use some kind of repeated start, but I don't know if your own I2C library supports that. There are a number of working libraries for I2C. But they will probably only work when used in a straight forward way for only the most compatible sensors. Do you have a logic analyzer ? That makes it possible to pinpoint the problem.

No I don't have a logic analyzer. But in regard to my I2C library, it works well and I even have a message checking function to check the result of each I2C operation, which I don't apply anymore because I tested it while I was developing the library and when I approved that my tx and rx are working well, I removed the checking function.

When you are serious about learning communications, then you should buy a logic analyzer. It really helps a lot. I prefer 8-channel, 24MS/s with unlimited data length and software that can decode I2C and UART data. The Saleae Logic8 costs 219 dollars, perhaps the Logic4 is good enough for I2C. If you want it very cheap, here are some that costs only 5 dollars: https://sigrok.org/wiki/Supported_hardware . Get one today!

Yeah, I know but it's not that I don't respect logic analyzer, but it's that this process of programming with Arduino IDE is easy enough to debug with Serial monitor, I have a function to check the process of I2C communication which tells what is going on, if your data transmission is successful or not! So in this situation, I don't think of a logic analyzer because the Arduino IDE's serial monitor helps a lot in debugging or displaying data.

It helps a lot. It helps even more than a lot.

I noticed this: http://www.avrfreaks.net/forum/undefined-reference-function-i2c-library-and-hmc5883l-read-function You have asked the same question at avrfreaks, and many people have problems with your own I2C functions. If you want to make it work, then use code that is known to work, if you want trouble, then go ahead and wander around. The I2C is too complex as a start to learn programming.

Well, knowing that I2C is too complex to start with, and the fact that I learned something in I2C and developed a good library << to my perspective. Is really encouraging to me that I can do hard things in programming in C. I learned things in the past weeks, I ran an I2C I/O expander, I2C LCD module and this HMC5883L. That's a good advancement to me. Applying a working code from the web is one of my strategies too, it's also a good way to test your hardware and learn something in software :)

Okay. But everything is already available (Wire library, many HMC5883L libraries, and so on). Use them as an example. How about that logic analyzer ?

Yeah, I know but I can't get into those libraries because I have little experience about reading other codes. If I'm a professional programmer, then I can look into other codes to save time and apply them in my projects. But to me, it's hard to read those codes, I've been into the process where I was in the beginning of Arduino and PIC platforms, then I switched to Arduino for the wide information sources, then I was in the middle of many many codes where I have little experience in coding. In start I applied some of Arduino libraries, and then when I went into advanced codes ...

... I realized that I need to start learn how to code and time is running, and I have to learn a lot of things in future, I have to learn about Raspberry pi and ESP32. And there are a lot of projects where if I relied on pre-written codes from other people, I would be asking and waiting for them to write me a code! Why won't I learn how to code?

I really don't need a logic analyzer right now, I'm moving to an advanced college where they have different electronics laboratories. Oh, I forgot to tell you, I'm an electronics trainer, so in future if I want to teach trainees how to code, then I better learn how to write some good codes. I have different reasons which force me to learn coding.

The problem stems from this function:
void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

The way I2C in most chips work, when writing, is that the first byte defines the register to write to. All subsequent bytes are the data to write into that register and successive registers.

To minimize the communication between the master and this device, the address pointer updated automatically without
  master intervention. This automatic address pointer update has two additional features. First when address 12 or higher
  is accessed the pointer updates to address 00 and secondly when address 08 is reached, the pointer rolls back to
  address 03.

So you are actually writing:
REG  CONTENT
0x00 0x07
0x01 Configuration_Register_B (0x01)
0x02 0x01
0x03 Mode_Register (0x02)
0x04 0x00

You need to either start a new transaction for each register you want to set a value in (explicit setting) or rely on the address pointer increment to move to the right register for you (implicit setting).
So either:
void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

Or, since the registers are in sequence in the address space:
void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(0x01);
  I2C_tx(0x00);
  I2C_stop();
}

Oh, and don't forget to have an I2C_stop() after reading your register in:
uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  I2C_stop(); // <----- MISSING
  Serial.println(reg_dat);
}

Thank you so much, now I get 0x00 for mode register but the readings still constant.

Your configuration settings look messed up. You're setting an invalid measurement mode in Config Register A, and setting only an unused bit to 1 in Config Register B. I use 0x78 in register A and 0x20 in register B (which gets changes when I select a different gain).

OMG, you're so right! How did I miss with the configuration values, I followed the values in the HMC5883L datasheet.

OK, now how to learn about gain and the other calibration stuff? Regards,


text:
DHT22 and DS18B20 together
I am trying to get DHT22 and DS18B20 to work together. The code below is the one I am using:
#include <SD.h>
#include "SPI.h"
#include "DHT.h"
#include <RTClibExtended.h>
#include <Wire.h>
#include <LowPower.h>
#include <stdlib.h>
#include <avr/interrupt.h> // library for interrupts handling
#include <avr/sleep.h> // library for sleep
#include <avr/power.h> // library for power control
#include <OneWire.h>
#include <DallasTemperature.h>

#define DHTPIN 7 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22  (AM2302)
#define wakePin 2 //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
#define ONE_WIRE_BUS 4  //DS18B20 is plugged into pin 4

RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
const int chipSelect = 10;
int interval_sec=0; //An alarm interval in seconds
int interval_min=5; //An alarm interval in minutes
int interval_hr=0; //An alarm interval in hours
char file_name[25]="Readings.csv"; //
DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature.

void setup () {
  Serial.begin(9600);
  delay(3000); // wait for console opening
  /**RTC**/
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  /**INTERRUPT**/
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT_PULLUP);
  Wire.begin();
  //clear any pending alarms
  rtc.armAlarm(1, false);
  rtc.clearAlarm(1);
  rtc.alarmInterrupt(1, false);
  rtc.armAlarm(2, false);
  rtc.clearAlarm(2);
  rtc.alarmInterrupt(2, false);
  //Set SQW pin to OFF (in my case it was set by default to 1Hz)
  //The output of the DS3231 INT pin is connected to this pin
  //It must be connected to arduino D2 pin for wake-up
  rtc.writeSqwPinMode(DS3231_OFF);
  //Initialize DS18B20 libraries
  sensors.begin();
  /**SD CARD**/
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
  //Remove File from SD card and create a new one
  SD.remove(file_name);
  File dataFile = SD.open(file_name, FILE_WRITE);
  dataFile.println("Date,Hour,Minute,Air_Temp,Humidity,Surface_Temp");  //Write the header
  dataFile.close();
   Serial.println("Initialisation complete.");
  delay(100); //Allow for serial print to complete.
}

void loop () {
  DateTime now = rtc.now();
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(" (");
  Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
  Serial.print(") ");
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
  /**Temperature and Humidity**/
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  //float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  //if (isnan(h) || isnan(t) || isnan(f)) {
    if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
    // Compute heat index
    // Must send in temp in Fahrenheit!
    //float hi = dht.computeHeatIndex(f, h);
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C\t");
    delay(3000); // wait for console
    /**DS18B20**/
    // call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus
    sensors.requestTemperatures(); // Send the command to get temperatures
    float surface_temp=sensors.getTempCByIndex(0);
    Serial.print("Temperature for the device 1 (index 0) is: ");
    Serial.println(surface_temp);
    delay(3000); // wait for console

    /**Store on SD**/
    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    File dataFile = SD.open(file_name, FILE_WRITE);
    String dataString = now.day() + String("/") + now.month() + String("/") + now.year() + String(",") + now.hour() + String(",") + now.minute() + String(",") + t + String(",") + h + String(",") + surface_temp;
    //String dataString = now.day() + String("/") + now.month() + String("/") + now.year() + String(",") + now.hour() + String(",") + now.minute() + String(",") + t + String(",") + h + String(",") + String("surface_temp");
    //Serial.println(dataString);
    // if the file is available, write to it:
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      //Serial.println(dataString);
    }
    // if the file isn't open, pop up an error:
    else {
      Serial.println("error opening file to log data");
    }
    /**INTERRUPT Based sleep**/
    DateTime nextAlarm = now + TimeSpan(0, interval_hr, interval_min, interval_sec);
    //Format is TimeSpan(day,hour,min,sec). Either use interval_min or interval_sec
    Serial.print("Alarm at:");
    Serial.println(nextAlarm.hour());
    Serial.println(nextAlarm.minute());
    Serial.println(nextAlarm.second());
    rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.second(), nextAlarm.minute(), nextAlarm.hour (), 1); //set wake-up time here
    rtc.alarmInterrupt(1, true);
    delay(3000); // wait for console
    attachInterrupt(0, wakeUp, LOW); //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
    //Arduino enters sleep mode here
    detachInterrupt(0);
    //execution resumes from here after wake-up
    //When exiting the sleep mode we clear the alarm
    rtc.armAlarm(1, false);
    rtc.clearAlarm(1);
    rtc.alarmInterrupt(1, false);
    Serial.println();
    delay(3000);
}

void wakeUp() {
  // here the interrupt is handled after wakeup
}

The above code ideally should read and store the temperature from DS18B20, and temperature and humidity from DHT22 and then go to sleep for a pre-determined time (5mins now) and then wake up when an interrupt is generated from the RTC.
However, I am unable to get both DHT22 and DS18B20 to work together. The code above works as expected if I comment out the code for DS18B20. Similarly, if I just run the examples (named Single and Simple) for DS18B20 as provided by DallasTemperature on the same Arduino keeping all the connections intact (DHT, RTC, SD Card, along with DS18B20) the DS18B20 also work as expected. Hence, I think I can be certain that the connections are proper. However, if I run the code above which include both DHT22 and DS18B20, then the output I get is as follows:
Initializing SD card...card initialized.
Initialisation complete.
201Initializing SD card...card initialized.
Initialisation complete.
2⸮

I would appreciate if someone can point me to where I am going wrong.
P.S.: I have also successfully tried a simple program like the one below to ensure that there are no conflicts in libraries of DHT22 and DS18B20.
#include <DallasTemperature.h>
#include <OneWire.h>
#include <DHT.h>

#define ONE_WIRE_BUS 4
#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(void) {
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");
  sensors.begin();
}

void loop(void) {
  sensors.requestTemperatures();
  Serial.print("Temperature1: ");
  Serial.print(dht.readTemperature());
  Serial.print(" Temperature 2 : ");
  Serial.println(sensors.getTempCByIndex(0));
}

What does the compiler say about the used memory ?

@Jot: Yes! There is a warning saying that there is too less free memory and the program might not work properly. I have reduced the number of print statements and now it works as expected. Can you add your comment as an answer?

My first thought was that sram is being overwritten. That seems to be the case, as you have confirmed.
The SD library uses a lot of sram memory, because it has to handle a table of the FAT data structure from the SD memory card.
You don't use the 'PSTR()' or the 'F()' macro and not the PROGMEM.
For example this code:
Serial.println("Dallas Temperature IC Control Library Demo");
creates that text in Flash memory and during startup that text is also copied to sram memory. You can avoid that by forcing that text to stay in flash memory only with the 'F()' macro:
Serial.println(F("Dallas Temperature IC Control Library Demo"));
Perhaps you have already seen sketches that use the 'F()' macro a lot.
The names of the days of the week can be placed in Flash code with PROGMEM. It requires special functions to read data from PROGMEM, since the AVR microcontrollers can not read data from flash directly.
[ADDED] The 'F()' macro, the 'PSTR()' and the PROGMEM are explained here: Nick Gammon about PROGMEM

Nice tidbit about F(), @Jot.  It is predefined?

Yes, it is part of the Arduino and mostly used with AVR microcontrollers like the Arduino Uno, Nano, Leonardo, and so on. I have added a link to my answer to Nick Gammon's page about it.


text:
PIR with Arduino - detects only first motion
The following is an Arduino sketch for 3 PIR sensors. Two PIRs can activate 1 buzzer and show status in an LCD. The third PIR activates a relay.
The problem is only the first motion gets detected and the "L" indicator stays on. After that there is no activity.
The same Arduino Uno board is working fine with other sketches. PIR sensors are also working. The sketch seems to be working on simulation as well.
Link to simulation
"L" LED is the LED close to the 13th pin. above the TX,RX LEDs. The PIRs are set for the lowest time, sensitivity medium. The issue exists even without connecting the PIRs/relay. There is one beep from the buzzer, it happens 4-5 seconds after turning the board on, with that the "L" led goes on - forever.
The LCD also has an issue, it shows filled blocks on the first row, nothing else.
I tried connecting only one PIR and 1 buzzer to the board.
What is wrong?
#include <LiquidCrystal.h>

unsigned long time;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
int pir1Pin =9;
int pir2Pin =10;
int pir3Pin =11;
int buzzerPin =8;
int relayPin = 12;
int backlightPin = 13;
long previousMillis = 0;
long interval = 1000;

void setup() {
  lcd.begin(16, 2);
  pinMode(pir1Pin, INPUT);
  pinMode(pir2Pin, INPUT);
  pinMode(pir3Pin, INPUT);
  pinMode(relayPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(backlightPin, OUTPUT);
  digitalWrite(relayPin,HIGH);
  delay(1000);
  digitalWrite(relayPin,LOW);
  Serial.begin(9600);
}

void loop() {
  if(digitalRead(pir1Pin)== HIGH) {
    digitalWrite(backlightPin,HIGH);
    lcd.setCursor(0, 0);
    lcd.print("Pir 1 Active");
    beep();
  } else {
    lcd.setCursor(0, 0);
    lcd.print("Pir 1 is off");
    digitalWrite(backlightPin,LOW);
  }
   if(digitalRead(pir2Pin)== HIGH) {
     digitalWrite(backlightPin,HIGH);
     lcd.setCursor(0, 1);
     lcd.print("Pir 2 Active ");
     beep();
   } else {
     lcd.setCursor(0, 1);
     lcd.print("Pir 2 is off");
     digitalWrite(backlightPin,LOW);
  }
  if(digitalRead(pir3Pin)== HIGH) {
     while(digitalRead(pir3Pin)==HIGH) {
       digitalWrite(relayPin,HIGH);
     }
   } else {
     digitalWrite(relayPin,LOW);
   }
 }

void beep() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    for (int i=0; i<500; i++) {
      digitalWrite(buzzerPin, HIGH);
      delayMicroseconds(500);
      digitalWrite(buzzerPin, LOW);
      delayMicroseconds(500);
    }
  }
}

You say “the "L" indicator stays on”.  What is the "L" indicator?  Also, what amount of time are the on-time pots on the PIR units set for?  If set for several seconds, could be causing the problem.

@ James Waldby - jwpat7, It is an LED marked as "L" on the board. the LED close to the 13th pin. above the TX,RX LEDs.
The PIRs are set for the lowest time, sensitivity medium.
The issue exists even without connecting the PIRs/relay.
There is one beep from the buzzer, it happens 4-5 seconds after turning the board on, with that the "L" led goes on - forever.

Make sure that all the PIR sensors and the LCD display are effectively powered.
this might fix your problem.
i'm saying this because the same thing seems to work in the simulation. Powering 3 PIR sensors and a LCD display with a USB is not a good idea.

But the same with only 1 PIR and 1 buzzer doesnt work ? withour LCD/additional PIRs

Are you 100% sure that the pinouts of the PIR sensors are correct and all of them work?

YES, I have tried reconnecting like 2-0 times in last 3-4 days. Also tested with higher voltage. Other PIR sketches are working.

@ShijilT  this seems odd. Try these, these might work. Place the Serial.begin(9600); line before any digital writes. Don't put the digital reads inside the if statements put them all in one place and store the results in variables.           res = digitalRead(pin); and then check them

I don't really know what the problem is with your setup, but here are a few suggestions to try:

Several PIR guides (1,2,3,4) recommend using a pullup resistor on the open-collector signal pin of some models of PIR sensors.  You could also (or instead) say pinMode(pir1Pin, INPUT_PULLUP); (and so forth) rather than pinMode(pir1Pin, INPUT);.  Note, for each PIR, attach a voltmeter to its output (or, to its input on the Uno).  Trigger the PIR and verify that the signal acts as you expect it to.
Use a different pin number than 13 for your backlightPin.  The Uno's digital pin 13 corresponds to the on-board LED (presumably the LED your question calls 'L').  If you use separate pins for the backlight and the on-board LED, you can then use the on-board LED as a debugging aid.
Your code arrangement if(digitalRead(pir1Pin)== HIGH){ ...
lcd.print(...); ... beep(); }else { ...
lcd.print(...); ... } (and similarly for pir2Pin) will print stuff to the LCD on every pass through loop(), that is, every few milliseconds.  It might make sense to have variables that record previous readings on those pins, and only update the LCD when a pin reading changes.  (Without other changes, this change would lead to only one beep when the PIR triggers, rather than a train of beeps at one-second intervals.  In this case if you want a train of beeps, you would need a beep-status variable.)

To supplement, use an I2C backpack for the LCD and fmalpartida's newLiquidCrystal library. Set the jumper to autoreset the trigger.
Wire VCC to 5V
Wire S+ (outputs 3V3 when tripped) to D2 (INT0) - or whatever you use...
Wire GND to GND

This is not a complete answer because I couldn't figure out why the beep only happens once. But if I'm not mistaken, if your code would work as you intend the first motion gets detected and the code jumps to beep. There it will be stuck for 500x(500+500) ms. You would never get results for pir2 or pir3 if the setup is in a way that you can't trigger pir2 independently from the others.
Therefore:
Use pulldown resistors as mentioned by others.
Read all the pir states and save them, and afterwards run the LCD code and then the beep code.
Your system will be unresponsive for as long as the beep code runs.


text:
Problem with using pure C code to program default UART (UART0) in Arduino Mega
Can I code default serial port in Arduino Mega (USART0, I assume) in pure C? I mean to set up it and configure directly by ATmega's registers?
I'm asking because I'm trying to do it and I have a problem. Below is code which I use and Arduino doesn't transfer anything...
#include <avr/io.h>

#define F_CPU 16000000
#define BAUD_RATE 9600
#define MY_UBRR (F_CPU+BAUD_RATE*8UL)/(16UL*BAUD_RATE)-1

void setup() {

    UART_Init(MY_UBRR);
}

void loop() {
    UART_Transmit('a');

 }

void UART_Init(unsigned char ubrr)
{
   UBRR0H = (unsigned char)(ubrr >> 8);
   UBRR0L = (unsigned char)ubrr;
   UCSR0B = (1<<RXEN0) | (1<<TXEN0);
   UCSR0C = (1<<USBS0) | (1<<UCSZ00);
}

 void UART_Transmit(unsigned char data)
 {
    while(!(UCSR0A & (1<<UDRE0)))
    UDR0 = data;
 }

That code I created following the datasheet for ATmega 2560. It has been compiled and programmed but doesn't work at all...
Please give me any advice. It's important for me use just C code in that case.

You forgot the semicolon after while(!(UCSR0A & (1<<UDRE0))).

About it compiling with a missing ';': The reason it did is because it is still syntactically correct C. Indenting the "UDR0 = data;" statement should make it clear why.

I suggest to use existing code and copy that or use that.
This is the Arduino HardwareSerial : HardwareSerial.cpp
You can find more code at avrfreaks.net. Click on "Projects", search for "uart" and "usart" and try to find code that is compatible with the ATmega2560. Some projects have buffers and many functions, others are very simple.
The result might not be compatible with other Arduino code (for example with interrupts). Why do you not want to use the Arduino Serial library ?

I tried your program on an Uno, and it worked as expected once I fixed
three problems:

Removed #define F_CPU 16000000. This is not a big issue, but it
fixes a warning about that constant being already defined by the
Arduino environment.
Added the UCSZ01 bit to UCSR0C in order to work in 8-bit mode
instead of the uncommon 6-bit mode.
Added the semicolon after while(!(UCSR0A & (1<<UDRE0))).

Note also that there is no point in loading UBRR0 in two steps. You
can just UBRR0 = ubrr and trust the compiler to do the right thing.


text:
Arduino open door (outdoor) tonemelody
My problem lies in the fact that I can not stop the "void loop" function and more accurately "StatInDoor". I have to make sure that the "ButtonOpenDoor" works independently of "ButtonCall". If someone presses the "ButtonCall" button then the "ButtonOpenDoor" button must work in progress, and if the "ButtonCall" button is pressed, the "ButtonOpenDoor" button must stop playing the melody.
My idea for this this:
int StatOutDoor = digitalRead(ButtonCall && ButtonOpenDoor);

or:
if(StatOutDoor == LOW && StatInDoor = LOW){
   PlayMelody();
}

But it does not work :(
Full code:
#include "pitches.h"

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};
int ButtonCall = 4;
int buzzer = 8;
int ButtonOpenDoor = 7;
int RelayModule = 12;

void PlayMelody() {
  for (int thisNote = 0; thisNote < 8; thisNote++) {
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(buzzer, melody[thisNote], noteDuration);
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    noTone(buzzer);
  }
}

void setup(){
  pinMode(ButtonCall, INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(ButtonOpenDoor,INPUT);
  pinMode(RelayModule,OUTPUT);
}

void loop() {
  int StatOutDoor = digitalRead(ButtonCall);
  if(StatOutDoor == LOW){
    PlayMelody();
  }
  int StatInDoor = digitalRead(ButtonOpenDoor);
  if (StatInDoor == HIGH) {
    digitalWrite(RelayModule, HIGH);
  } else {
    digitalWrite(RelayModule, LOW);
    delay(3300);
  }
}

Can someone help with this? (Sorry for my bad English).

&& is logical AND. & is Bitwise AND. Use the right one, it might help.

Unfortunately both methods do not work

Unfortunately I don't speak your language, and I find those variable names almost impossible to read. Please use English (or English-like) variable names (and function names) and ideally something to break up the words within them, such as camelCase.

przyciskzadzwon=ButtonOutDoor ; przyciskotworz=ButtonInDoor ; przekaznik=RelayModule ; muzyczka=PlayMelody ; stanwew=StateInDoor ; stanzew=StateOutDoor

That doesn't help me decipher a string of seemingly random consonants in my head...

I can send again full code with translation, just tell where. I really need help ;/

Up there, where the existing code is. Press edit.

Sorry. Edit done

I'm not quite sure I understand the logic of what you're asking. Your description is a little vague. Maybe if you provided more information about what the signals are, what they mean, and where they come from, it may help.
However - if you want the melody to play when both inputs are LOW you should change:
if(StatOutDoor == LOW && StatInDoor = LOW){
      PlayMelody();
}

to:
if(StatOutDoor == LOW && StatInDoor == LOW){
      PlayMelody();
}

Note the use of == not = to denote equality (= is assignment).
Also the use of a 3.3 second delay in your else will show everything down to a crawl when StatInDoor is HIGH.

I want to make an intercom. There are two buttons - one to ring from the outside, the other to open from the inside. If outside someone pushed the call button and play the melody I want to open the door, for this moment problem is that I can only open when the melody is over.
if(StatOutDoor == LOW && StatInDoor == LOW){
PlayMelody();
}  not working too...

Ah, I see. Well for that you need to rethink your entire program. You need to learn how to write non-blocking code. Start with the BlinkWithoutDelay example in the IDE.

ohh... sure. How to transform it?

State machine(s) and using millis() instead of delay().

The Arduino doesn't multitask. So when you execute PlayMelody() the loop() function can't do anything else until the song ends.
You could use interrupts to play the song, but to keep things simple, here's a way to do it without interrupts.
// Struct to hold the song data (simpler than 2 arrays)
struct note {
    int pitch;
    int duration;
};

// Class to play songs
class song_player {
protected:
    note *melody;   // Array of all the notes
    int note_count;  // How many notes in song
    int current_note;
    bool am_playing;  // Playing song?
    unsigned long last_event;  // Time of last note
    unsigned long next_event;  // Time to play next note
    byte speaker_pin;

    // is it time to play the next note?
    bool elapsed()
    {
        unsigned long m = millis();
        if (m >= next_event) {
            last_event = m;
            return true;
        }
        return false;
    }

    // play one note
    void play_next_note() {
        if (elapsed()) {
            // Play next note unless at end of song
            if (current_note < note_count) {
                unsigned long duration = 1000 / melody[current_note].duration;
                tone(speaker_pin, melody[current_note].pitch, duration);
                next_event = millis() +  1.3 * duration;
                current_note += 1;
            }
            else {
                // Finished...
                noTone(speaker_pin);
                am_playing = false;
            }
        }
    }
public:
    // ctor
    song_player(byte speaker_pin, note *melody, int note_count) :
        am_playing(false),
        speaker_pin(speaker_pin),
        note_count(note_count),
        melody(melody)
    {
        // Note: does not make local copy, so array should be
        // valid for lifetime of this object
    }

    // Start the song
    void start() {
        // Initialize
        current_note = 0;
        am_playing = true;
        last_event = millis();
    }

    // Call this every loop()
    void loop() {
        if (am_playing) {
            play_next_note();
        }
    }
};

Then you would change the rest of the program to something like:
// Song data
note the_song[] = {
  {NOTE_C4, 4},
  {NOTE_G3, 8},
  {NOTE_G3, 8},
  {NOTE_A3, 4},
  {NOTE_G3, 4},
  {0, 4},
  {NOTE_B3, 4},
  {NOTE_C4, 4}
};
// Create a player object
song_player player(9, the_song, sizeof(the_song) / sizeof(the_song[0]));

//....

void loop()
{
    // other stuff .....

    if(StatOutDoor == LOW && StatInDoor == LOW) {
        // Start the song
        player.start();
    }
    // Important: Call this every time
    player.loop();

    // Other stuff here....
}


text:
Avoid overflowing of counter
I have a global uint32_t that keep tracks of used Bytes:
uint32_t usedBytes;
int bytesWritten;

byteWritten = myFile.print(data, FILE_WRITE);

if (byteWritten > 0) {
  usedBytes += bytesWritten;
}

What happen if usedBytes is close to the maximum (0xFFFFFFFF)? Will incrementing it make it 0, or stuck at 0xFFFFFFFF?

It will wrap around though 0.
0xFFFFFFFF + 1 = 0

You can add a higher order word to track more data:
if (byteWritten > 0) {
    uint32_t newUsed = usedBytes + byteWritten;
    if (newUsed < usedBytes) {
        fourGigsUsed ++;
    }
    usedBytes = newUsed;
}

Or you could use uint64_t to automate it - however none of the Arduino print routines cope with the uint64_t variable type.


text:
Corrupted characters with an OLED displaying thermocouple output
I'm super new to Arduinos but I'm learning as I go. I'm in the first stages of a small temperature control project and so far I've been able to display the output of a MAX31855 thermocouple breakout board on 124x64 spi OLED through my Arduino micro.
My problem is that the characters of the temperature are corrupted looking. As I think I understand it, the temperature is changing while it's being written to the display therefore you get overlapping values. I've attached an image of the display.
I've tried making the temp output an integer but that didn't work.
Any input would be greatly appreciated as I'm just banging my head against the wall.
Here's my code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_MAX31855.h>
#include <U8glib.h>

//Constructor line for OLED

U8GLIB_SH1106_128X64 u8g(13, 11, 10, 9, 8);  // D0=13, D1=11, CS=10, DC=9, Reset=8

// Default connection is using software SPI, but comment and uncomment one of
// the two examples below to switch between software SPI and hardware SPI:

// Example creating a thermocouple instance with software SPI on any three
// digital IO pins.
#define MAXDO   3
#define MAXCS   4
#define MAXCLK  5

// initialize the Thermocouple
Adafruit_MAX31855 thermocouple(MAXCLK, MAXCS, MAXDO);

// Example creating a thermocouple instance with hardware SPI
// on a given CS pin.
//#define MAXCS   10
//Adafruit_MAX31855 thermocouple(MAXCS);

void draw() {
  double c = thermocouple.readCelsius();
  u8g.setFont(u8g_font_profont29);  // select font
  u8g.setPrintPos(5, 45);  // set position
  u8g.print(c);  // display temperature from MAX31855

}

void setup(void) {

}

void loop() {

  // picture loop
  u8g.firstPage();
  do {

    draw();
  } while (u8g.nextPage());

  // rebuild the picture after some delay
  delay(5000);
}

The U8G2 library saves RAM by drawing the screen in smaller chunks (i.e., a "page").  Because you are taking a reading for each chunk, the temperature can change.  Just pull the reading out of draw and do it once in loop:
double c; // a global variable used in draw and loop

void draw() {
  u8g.setFont(u8g_font_profont29);  // select font
  u8g.setPrintPos(5, 45);  // set position
  u8g.print(c);  // display temperature from MAX31855

}

void loop() {

  c = thermocouple.readCelsius(); // set the global variable once

  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while (u8g.nextPage());

  // rebuild the picture after some delay
  delay(5000);
}

BOOM! Worked like a charm. Much appreciated.


text:
Converting array to char
I'm trying to convert a char array to a char. i used this code
char code[4] = {'1','2','3','4'};

char strcode[4];

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

void loop()
{
    memcpy(strcode, code, 4);
    Serial.println(strcode);
    Serial.println("done");
    delay(1000);
}

But for some reason when i read my serial monitor i get this:
1234
done

Why are there 2 squares behind it?  Am I doing it wrong?
EDIT: For some reason stackexchange doesn't show the 2 squares but there are 2 squares behind 1234

C strings need to be NUL-terminated.
char strcode[5];

 ...

 ...
     ...
    strcode[4] = '\0';
     ...


text:
Arduino Human Infrared Sensor
I started out again with Arduino (beginner), but I wanted to know if I could connect another human infrared sensor like this to the Arduino Uno. I know how to connect a simple pir like this one, but I dont know for sure how to connect the 12V one (if its possible). Guess the red wire goes to a seperate 12V power supply, brown goes to ground and blue then goes to a digital pin on the arduino arduino? I didnt really understand the description that was available for the 12V sensor, so thats why I am asking (I want to be entirely sure before buying).
Thanks

They're exactly the same - just one is in a fancy box and has a light sensor so it only triggers at night.

@Majenko But it says it needs 12V So the output pin of the Sensor should be fluctuating in 12V But Arduino Pins are 5V tolerant.

site says "N- Blue (zero line), L- Brown (connected FireWire), Output - Red (sensor output lines)". honestly the colors are meant for AC, but i guess it's been re-purposed... 12v is too high for arduino, use an optocoupler.

It's impossible to tell quite what the output will be from some pictures and chinglish. It should be a relay but who knows? Banggood never has any datasheets. You will need to dismantle one to find out for sure.

Blue - Ground, connect to Arduino GND
Brown - Power, connect to external 12V source.
Red - 12 V output. Connect via a diode to arduino input pin. Enable pullup on arduino pin.
This way when the sensor output is low it will pull the arduino pin low. When the output is high the diode blocks the 12V from frying the arduino while the internal pullup ensures the input pin goes to a safe voltage for a high pin.
Don't put the diode the wrong way around or things will go bang.

simulate this circuit – Schematic created using CircuitLab

I think it should be compatible with Arduino with a bit of support. Now the first issue is this that we don't really know that what sensor is this detaily. So we can't really find a datasheet that could say it's pinout or its electrical characteristics. Now assuming those pinouts are similar to those of the any sensor that are VCC Data Out GND Then you could probably use it but according to that page it says it needs 12V So according to that Data Out also must be fluctuating with voltage near 12V. So the solution would be to use a voltage divider circuit. Now you could find the resistor values from the Google. I think that setup should be Okay  but I can't tell anything up to you provide us with any data sheet.


text:
When I see the red RX LED flash I am wondering if it means there is an error?
Each time I press a particular button in my circuit the red RX light flashes briefly.
I have been having trouble with making this button perform the command it should, I and am wondering if the RX flash has something to do with that, or is at least reporting some sort of error?

Leds? Buttons? Which is it? Also, what the frog is a "red board", and what is this mystery circuit you have? And while you're at it, what code is supposedly trying to perform a "command"?

Welcome to Arduino beta.  Please take the tour to get the most out of this site:  https://arduino.stackexchange.com/Tour - You will notice the downvotes because of the way your question is formatted.  Take the tour and perhaps you can edit in a way that will attract answers.

The red light is flashing because you are pressing the button.  To stop the red light flashing I recommend not pressing the button.

The TX LED is there to show that some data or signal has been received on your Arduino. When you press the button on your circuit, it briefly sends a signal which then triggers the RX LED on your Arduino. Most often, the RX LED is used to troubleshoot whether you are receiving an input and, in your case, it seems you are.
Therefore, the RX LED is not an error and shouldn't be the source of your problem.


text:
If statement comparing array to value list throws error
In my program I have the following lines of code:
if (invest == {0, 1, 0, 0})
   {
      //code
   }

However, upon attempting to compile the code, I receive the following error:
exit status 1
expected ';' before '}' token

"Invest" is a bool array originally defined with`
bool invest[] = {0, 0, 0, 0};

How can I prevent this error from ocurring?

You cannot compare like that... you have to do it one by one (and check the length of the array).
if ((sizeof(invest) / sizeof(bool) == 4) &&
    (invest[0] == 0) &&
    (invest[1] == 1) &&
    (invest[2] == 0) &&
    (invest[3] == 0))
{
     ...
}

If you need to do such a compare often (with possibly different values), you of course can always write a dedicated function passing the array, and the array to check against and check the length and use a loop for checking all values.
Note that if invest is a boolean array, it's best to use false and true instead 0 and 1.

:((((((((((((((

@Excelseo you are not happy with my answer?

Unfortunately you cannot do that.
In addition to Michel Keijzers, another possible way is to use binary manipulation of an integer.
Your declaration of the variable would look like this:
unsigned int invest = 0x00;    // B0000 or 0 would be acceptable also

(See https://www.arduino.cc/en/Reference/IntegerConstants for notation reference.)
So your if statement would be very close to what you had originally wrote.
if (invest == B0100)
{
   //code
}

Using this method you cannot reference each bit in the same way as an array (ie invest[3]). Instead to view the 4th bit:
result = (invest && 0x08) >> 3;

To set the 4th bit you would need to write:
invest |= 0x08;    // ie. B1000

And to clear the 4th bit:
invest &= 0x07;    // ie. B0111

Arduino has bitRead(x, n) and  bitWrite(x, n, b) macros.

@gre_gor, Even better!!! Thanks for your suggestion.

You have a syntax error in that code; in C99, you would need to declare the type of the anonymous array {0, 1, 0, 0}, for example via  (bool[]){0, 1, 0, 0}.  So the following code compiles ok in C:
int main() {
  char invest[] = {0, 1, 0, 0};
  if (invest == (char[]){0, 1, 0, 0})
    printf("Yes yes yes\n");
  else
    printf("No no no\n");
  return 0;
}

However, if you compile and run this code, it will output "No no no" rather than "Yes yes yes" because the logical test invest == (char[]){0, 1, 0, 0} says to compare the address of the invest array to the address of the anonymous array, and of course they differ.
Note, if you try to compile the above as a C++ program, the result will be “error: taking address of temporary array” due to different type checking.

All that said, the straightforward way to compare arrays of bytes or in some cases arrays in general is to use the memcmp() function.  From its man page:
SYNOPSIS
   #include <string.h>
   ...
   int memcmp(const void *s1, const void *s2, size_t n);
DESCRIPTION
   The  memcmp()  function compares the first n bytes (each
   interpreted as unsigned char) of the memory areas s1 and s2.
RETURN VALUE
   The memcmp() function returns an integer less than, equal to,
   or greater  than zero  if  the  first  n  bytes of s1 is found,
   respectively, to be less than, to match, or be greater than
   the first n bytes of s2.

The following code compiles ok both in C99 and C++ and prints out "Yes yes yes.".
#include <stdio.h>
#include <string.h>
int main() {
  char invest[] = {0, 1, 0, 0};
  char others[] = {0, 1, 0, 0};
  if (memcmp(invest, others, sizeof invest)==0)
    printf("Yes yes yes.\n");
  else
    printf("No no no.\n");
  return 0;
}

Note, when compiling code like this in the Arduino IDE, you may be able to leave out one or both of the #include statements.

I think this will not work if the length of others is longer than invest, than only the elements of invest are checked (or in other words: you should check also if the length of invest equals the length of others).


text:
basic_insert with WAMP server doesn't connect with MySQL database
I'm trying to establish a connection with a MySQL database on a local server wirelessly using the following script:
The wireless connection with my router is successful but then connection with database results in
I'm using a WeMos D1 mini ESP8266, Windows 10, WAMP64, MySQL 5.7.14.
I get ping responses from MySQL at 127.0.0.1, and my host computer and also the ESP8266.  I've disabled my Windows Firewall to test it temporarily.  After the wifi connects with the ESP8266 and confirms the correct WiFi.localIP, 'Connection failed' error with additional text below.
I can manually enter data into the test_arduino table so I think it's a connection issue with the database server. Maybe something to do with my router's handling of of Port 80.
I am able to send sensor data to remote sites such as ThingSpeak.
Any help would be appreciated.
// Created by: Dr. Charles A. Bell

#include "ESP8266WiFi.h"
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

IPAddress server_addr(192,168,0,10);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "PASSWORD";        // MySQL user login password

const char* SSID = "MYSSID";         // Your network SSID
const char* PASS = "MYPASSWORD";

// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

WiFiClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect

  Serial.print("Connecting to "+*SSID);
  WiFi.begin(SSID, PASS);
  Serial.println("going into wl connect");

  while (WiFi.status() != WL_CONNECTED) //not connected,  ...waiting to connect
    {
      delay(1000);
      Serial.print(".");
    }

  Serial.println("wl connected");
  Serial.println("");
  Serial.println("Credentials accepted! Connected to wifi\n ");
  Serial.println(WiFi.localIP());
  Serial.println("");

  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
  delay(2000);

  Serial.println("Recording data.");

  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(INSERT_SQL);
  // Note: since there are no results, we do not need to read any data
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}

The following is the Serial COM4 readout:
Connected to wifi
 going into wl connect
.......wl connected

Credentials accepted! Connected to wifi

192.168.1.XX (intentionally deleted)

Connection failed.
Recording data.

Exception (3):
epc1=0x402050ea epc2=0x00000000 epc3=0x00000000 excvaddr=0x402315cc depc=0x00000000

ctx: cont
sp: 3ffef5a0 end: 3ffef7d0 offset: 01a0

>>>stack>>>
3ffef740:  0a00a8c0 00000001 3ffe8785 402050f4
3ffef750:  3ffee524 0000000e 3ffe850e 3ffee79c
3ffef760:  3fffdad0 00000000 3ffee770 402048fd
3ffef770:  402315cc 00000000 3ffee770 3ffee79c
3ffef780:  3fffdad0 00000000 3ffee770 40204945
3ffef790:  402010ae 00000000 3fff061c 4020292e
3ffef7a0:  3ffe8780 00000000 3fff061c 40201d3e
3ffef7b0:  3fffdad0 00000000 3ffee794 40204c34
3ffef7c0:  feefeffe feefeffe 3ffee7b0 40100718
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld

It looks like you haven't finished part of your question: "The wireless connection with my router is successful but then connection with database results in...."

I figured it out.  I needed to set up a User (IP  server) in the database.
In phpMyAdmin I created a new user (esp) and set the Host name to the IP address of the ESP8266.  In the sketch I changed the user from "root" to "esp".

Please expand upon your answer. Your answer may prove to be useful to someone else, who has the same issue, but with less understanding of how to solve it.

Please accept your answer once you have edited/expanded on it.


text:
2.8 Touchscreen does not work with Proto Screw Shield
I am using the Arduino Mega and the 2.8 touch screen by Adafruit, and I can't get the screen to work on my Proto R3 Screw Shield
Here are the tools I am using:

2.8 inch touch screen
Proto R3 Screw Shield

When I put the touch screen onto the Arduino Mega, no wiring needed, and run the graphic test provided by the Adafruit_ILI9341, everything works perfectly. The touch screen runs the animation, and my serial monitor outputs the information of my touch screen.
However, when I put the touch screen on the screw shield, which I place on the Arduino Mega, the touch screen stays white, no matter if I press either reset button, unplug and replug the Arduino, restart the IDE, take off and put everything back on.
I explicitly followed the instructions by Adafruit here that say how to get the screw shield working.
There is no contact between each soldered pin, and I cut and soldered the ICSP and MEGA jumpers on the bottom of the touch screen accordingly, as shown in the picture on the bottom right:

I tried using an SD card as a test to see if the proto R3 screw shield was not working at all, and reading an image off of the SD card. I got proper, working results, so everything worked fine with the screw shield then. This means that the screw shield still works with it's 5V pin.
What could be the cause of the touchscreen staying white? Thanks in advance!

You are set to use the ICSP header for communication with the screen. That is good, when you are directly connected to a Mega.
However that is bad when you are going via a shield that doesn't have an ICSP header.
The ICSP header is the 6-pin (3x2) header in the right of your picture. It has SPI signals that the screen needs. Your screw shield lacks those pins.
You need to pass those signals through. The simplest way would be to add a 3x2 stackable header (or two 3x1 stackable headers) upside down through the correct holes to line up with the ICSP header.


text:
HC-05 Bluetooth Module Blinking Red Light-Arduino Uno
I have looked on google for an answer to my problems to no avail. The you tube video I am following is here: https://www.youtube.com/watch?v=f1v0IMegCvU
So basically on my android, I can't see the HC-05 device show up and the module itself is flashing red unlike the video's flashing blue light. I have connected the circuit exactly like he has in the video with the 2 10K resisters. I am using the same app. What is wrong? Here is my code as I copied from the video.
void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  Serial.println("Connection Successful!");
}
void loop()
{
  if(Serial.available()>0){
    int data=Serial.read();
    switch(data){
      case 'a': LEDON();break;
      case 'b': LEDOFF();break;
      default : break;
    }
  }
  delay(50);
}
void LEDON(){
  Serial.println("Led On!");
  digitalWrite(13,HIGH);
}
void LEDOFF(){
  Serial.println("Led Off!");
  digitalWrite(13,LOW);
}

I also get the error avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 when connected through usb. I do not get any errors when just flashing the arduino without any wires connected to the arduino. I know that the port is correct. Any ideas would be helpful. Thanks.

You write “I do not get any errors when just flashing the arduino without any wires connected to the arduino”. Q1: By 'flashing' do you mean sending a sketch to the Arduino?  Q2: How does the sketch get to the Arduino if no wires are attached?    Q3: What else is connected to the Arduino when the USB doesn't sync?  Eg is the HC-05  connected?  Q4: Re  “I know that the port is correct”, what port do you mean?  Q5: In the IDE, what  board programmer or programming method do you have selected in the two cases? (Ie with or without USB connection)

Answers: Q1=No, I mean just not having anything connected to the arduino other than the usb cable and selecting upload. Q2 answered by Q1. Q3=ground, 5v, tx,rx and those goes to the circuit on the breadboard just like in the video. Q4=port 1 and is genuine arduino it says. Q5=Not for sure what you meant by this question. I am using C programming language, is that what you meant? Confused here.

Re Q1-2-3, looks like you mean uploading works ok when the only wire attached to Uno is the USB cable, but if app. circuit is attached it doesn't.  Re Q4, what text appears when you hover the mouse cursor over the Tools, Port line?  Re Q5, if you click Tools in the IDE, what shows up in "Programmer" field?

It is Com 1. Then in the programming field it says, "Atmel STK500 development board."

Can I just check you have the USB connected to the Arduino and the PC and you are using Serial to connect to the Bluetooth.  If so that won't work.  The code you have isn't reading from BT its reading the keyboard input of the PC.  You need 'SoftwareSerial' to create a second serial port on an Uno, or use a Mega, to connect to the blue tooth, then you can put the HC-05 into pairing mode and all that stuff.

Are you programming it from your phone, or from a PC.  (Either way the above comment still stands)

I am not trying to connect to another arduino, I am trying to connect to an android phone. When you say "SoftwareSerial" does that mean I need to change all my serials to this "softwareserial" in my coding? The video says nothing about it. I am programming from my PC and then uploading the code to the arduino.

There are several issues to consider:
• Program downloading
• HC-05 serial communication
• Bluetooth pairing
For the first issue:  The serial-over-USB connection between the development computer and the Uno ties up the Uno's hardware serial RX and TX pins.  There will be a conflict if the development computer transmits when the HC-05's TX is connected to the Uno's RX.  This can be resolved by disconnecting the HC-05 TX when downloading a program.
For the second issue:  The Uno schematic shows 1KΩ resistors between TX and RX on the ATmega328P and RX and TX on the USB chip (ie on an ATmega16U2, or a CH340, etc).  If the HC-05's TX drive is strong enough, it will overcome the drive from the USB chip and work ok.  Note, I would leave out the voltage divider (on the HC-05 RX line) that the video shows.
For the third issue:  The HC-05 in the video mentioned in the question has a blue LED that blinks steadily when the HC-05 isn't paired, and blinks at a long interval when it is paired.  Many HC-05's have red LEDs instead of blue; the LED color is not an issue.  Some HC-05's don't blink at all when paired; that's not an issue either.  What is an issue is that (according to description in question) your HC-05 keeps on blinking, so apparently isn't paired up.
Whether the HC-05 pairs with an Android app is more or less independent of whether you have the HC-05 connected to an Arduino; you should be able to pair your phone with the HC-05 when just Vcc and ground are connected to the HC-05.  If you are having trouble with pairing, try another app; try powering the HC-05 down and up; and try a different HC-05.  I mention trying another app because one serial-terminal app I installed on my Android phone needed the app or the HC-05 to be restarted to pair up after loss of pairing, and the serial-terminal app I replaced it with did not need those actions.  Note, pairing takes a few steps on my phone:  in Settings / Wireless, search for Bluetooth devices; select device; enter its passcode; run an app and tell the app which Bluetooth device to use.

I read through your answer and did what you asked me to or at least I think I did. So what I did is here:                                                                For the first issue I disconnected the HC-05 TX when downloading and it did it successfully unlike before. After downloading, I reconnected it since the arduino now has the code. Second issue: I left out the rx line resister and just put a wire in place of where the resistor was before for that line. Third issue: Noted. I tried different HC-05 and apps but after all these suggestions, it still has the same problem. More Ideas?

By "same problem", you mean blinking LED and not pairing?  That aspect doesn't depend on what the Arduino does -- it's up to the HC-05 and the phone.  Do you have another phone to try?  Did you enable BT discoverability of the phone?  [I don't remember at the moment the ins and outs of pairing, ie what matters and what doesn't; you may need to do some web searching on that topic, for your model of phone.]

I have the exact phone as in the video. I did research and nothing. And yes the same problem is blinking led and not pairing. I have BT enabled. I tried 2 different HC-05 with same results of blinking and not pairing. What is wrong? I did the same thing as in the video and it doesn't work? Just doesn't make any sense, it worked for him and I followed his exactly, so it should work.

Does your phone discover the HC-05 like video showed?  Did you send the 1234 or 0000 passcode?  Those are prerequisites for pairing.  Aside from that I don't have more ideas at the moment ... except I upvoted the question :)

The phone doesn't see the hc-05.

Try this code(it's simpler):
char data ;
void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
}
void loop()
{
   if(Serial.available() > 0)
   {
      data = Serial.read();
      Serial.print("\n");
      if(data == '1')
      {
         digitalWrite(13, HIGH);
         Serial.print("on");
      }
      else if(data == '0')
      {
        digitalWrite(13, LOW);
        Serial.print("off");
      }
   }
}

Upload this to your Arduino. Open your phone, go to bluetooth settings and connect to HC05 with password 1234. Download an app from here: https://github.com/Mayoogh/Arduino-Bluetooth-Basic
Now your circuit should work.
Arduino to HC05 connections:
   5V -> 5V
   GND-> GND
   RX -> TX
   TX -> RX
LED connection: connect LED to pin 13 and the GND pin beside it(it's fine if you don't use resistor).


text:
How to control continuous rotation servo via HC-12 rf module
I am working on a project to wirelessly control a continuous rotation servo...something like a wireless vending machine.
The problem I am having is controlling how many revolutions the servo is making. During testing I used a button and had no issues getting the delay to work properly. Now that it's connected to the HC-12 RF module I can't get the delay to control how many rotations the servo makes. The servo I'm using is the FS90R.
#include <SoftwareSerial.h>
#include <Servo.h>
SoftwareSerial mySerial(2, 3); // RX, TX
Servo badservo;

int pos = 92;
unsigned long last = millis();

void setup() {
  mySerial.begin(9600);
  badservo.attach(9);
  badservo.write(pos);
}

void loop() {
  if(mySerial.available() > 1){
    int input = mySerial.parseInt();//read serial input and convert to integer (-32,768 to 32,767)
    int servpos = badservo.read();
    if(millis() - last > 250){
      if(servpos == 92 && input == 1234){
        badservo.write(0);
        delay(470);
        //mySerial.println(8894);
      }
      else{
        badservo.write(pos);
        //mySerial.println(8894);
      }
    }
  mySerial.flush();//clear the serial buffer for unwanted inputs
  last = millis();
  }
  delay(20);//delay little for better serial communication
}

With the servo that I'm using has a stop position of 92, meaning when I do
servo.write(92);
it will stop the servo. Also, the 470 delay was tested with a button and was a single full rotation.
Now, with the HC-12 module, I can't get the servo to rotate less than 2.5 times.
Anyone have any idea what I'm doing wrong? The goal is to get the servo to rotate only once when the RF module receives the proper signal.

Feeling that adding a delay to a serial receive routine will result in "better serial communication" is pretty much always a bad idea, and indicates a severely broken underlying design.  You probably don't want to call flush() either - what you want, is sound event-driven code.

You can't rely on a specific delay being one rotation - especially when you are using SoftwareSerial. SoftwareSerial breaks many things, and anything that uses interrupts (such as the Servo library) gets broken by it. It's a real interrupt hog.
The proper way of doing it is to use a rotary encoder on the servo to report the position (or change in position) so that you know where the servo is. That's really the only reliable method of getting the servo to perform precise operations.
By the way:
mySerial.flush();//clear the serial buffer for unwanted inputs

does absolutely nothing. The operation of flush() changed when the Arduino API turned one. It is now supposed to wait until both the TX circular buffer and the UART TX FIFO are empty. It has nothing to do with emptying any inputs.  Instead you want:
while (mySerial.read() != -1);

Thanks for clearing that up! Which library would you recommend for communication with the HC-12 wireless device?

There are numerous alternatives to SoftwareSerial, and most of them are considerably better - but all software serial implementations suck. You really want to use hardware serial, but most small Arduino boards only have one UART which is used by the USB interface.

Ah. I should note that I'm using a Arduino Pro Mini for this project as everything has to be very compact. Can you point me to any resources that will help with this? There's a lot of info out there in the few Google searches I just did.

You might consider the Teensy-LC instead; I believe it has multiple hardware serial ports, and is quite small.  However, it introduces the complexity of its own IDE plugin.  It should be possible to get this to work, if awkwardly, with an ordinary Arduino and soft serial.


text:
Where are RX and TX pins on the GT2560?
I'm adding WiFi (ESP8266) to my GT2560 board. Does anyone know where on the board are the RX and TX pins and the best place to connect to them?
This is all, no more info on the board in the internet and forums: https://www.geeetech.com/Documents/Users%20Manual%20of%20GT2560.pdf

Does anyone know where on the board are the RX and TX pins

The serial Rx and Tx signals from the ATmega2560, go to the nearby FT232RQ USB-to-serial adapter. You can look at the part numbers on the ICs and find those two devices on the PCB.

no more info on the board in the internet and forums

It's good news that there does seem to be more information available :-) After a few minutes with Google (searching for GT2560 schematics) I found this download link for the schematics on this forum page.
Although it would be possible to reverse-engineer the PCB (or at least the relevant part of it) the schematics are still helpful, since the white coating makes the actual copper traces harder to follow visually.
The schematic shows that two 1k resistors, R3 and R13, are in series with serial signals:

R3 between ATmega Tx -> FT232 Rx
R13 between ATmega Rx <- FT232 Tx

You may want to confirm that the linked schematic still applies to your specific PCB (since PCB and schematic versions could have changed). With the power disconnected, you could check with a multimeter that there is continuity between the appropriate ATmega pin and one end of each resistor R3 & R13, and between the other end of each resistor and the appropriate FT232 pin, as shown on the schematic.
I have put a red ring around those 2 resistors on the GT2560 top view below, to help you to find them:

(original image source)

best place to connect to them

If you are going to drive those serial signals from an ESP8266, you must first disconnect them from the on-board FT232, to avoid contention and so the ESP8266 replaces the FT232. Removing those two resistors would make each resistor's (now vacant) pads leading to the ATmega serial port, an ideal place to connect the ESP8266. (Of course you could attach wires directly to the pins of the ATmega or FT232, but I don't see any advantage to doing that.)
One issue which you need to consider, is the voltage compatibility of the serial port signals. The ATmega2560 uses 5V signal levels, whereas the ESP8266 is a 3.3V device. There have been discussions on various websites (example) that suggest the ESP8266 is 5V-tolerant on I/O pins. You will need to satisfy yourself whether to use voltage translation, or to rely on information discussed on web pages like that one.

The GT2560 uses USB for communications and USB has a combined RX/TX and not individual pins.