text:
Multiple devices on SPI
Whenever I use multiple devices on SPI, TFT Screen, and the BME280 breakout board from Adafruit, the Arduino fails to detect the devices.
Code of the screen separately (works)
// include the necessary libraries
#include <SPI.h>
#include <SD.h>
#include <TFT.h>  // Arduino LCD library

// pin definitions
#define sd_cs  7
#define lcd_cs 10
#define dc     9
#define rst    8

// Define screen pins
TFT TFTscreen = TFT(lcd_cs, dc, rst);

//Define variables
char sensorPrintout[4];
char sensorPrintout2[4];

// this variable represents the image to be drawn on screen
PImage logo;

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

  Serial.print("Initializing SD card...");
  if (!SD.begin(sd_cs)) {
    Serial.println("failed!");
    return;
  } else {
    Serial.println("OK!");
  }

  // Start and clear TFT screen
  TFTscreen.begin();
  TFTscreen.background(0, 0, 0);

  // Lookup image on TFT screen
  logo = TFTscreen.loadImage("Logo.bmp");
  if (!logo.isValid()) {
    Serial.println("error while loading Logo.bmp");
  }
  if (logo.isValid() == false) {
    return;
  }

  //Draw logo on the screen
  Serial.println("drawing image");
  TFTscreen.image(logo, 0, 0);

  // Change textcolor to white
  TFTscreen.stroke(255,255,255);

  //Write some text
  TFTscreen.setCursor(0,25);
  TFTscreen.print("Schuif 1: ");
  TFTscreen.setCursor(75,25);
  TFTscreen.print((char)247);
  TFTscreen.print("C");

  //Write some text
  TFTscreen.setCursor(0,50);
  TFTscreen.print("Schuif 2: ");
  TFTscreen.setCursor(75,50);
  TFTscreen.print((char)247);
  TFTscreen.print("C");
}

void loop() {
  // Read value of A0
  int value = analogRead(A0);
  Serial.println(value);
  float voltage = value * (5.0/1023.0);
  Serial.println(voltage);
  String sensorVal = String(analogRead(A0));
  String sensorVal2 = String(voltage);

  // Change sensor value to a character array
  sensorVal.toCharArray(sensorPrintout, 4);
  sensorVal2.toCharArray(sensorPrintout2, 4);

  // Change text color to white
  TFTscreen.stroke(255,255,255);

  // Write value of sensor 1
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout);

  // Write value of sensor 2
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);

  // wait  500ms
  delay(1000);

  // Change text color to black
  TFTscreen.stroke(0,0,0);

  // Write value of sensor 1
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout);

  // Write value of sensor 2
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);
}

Code of the BME280 separately (works)
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 6

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme(BME_CS); // hardware SPI

unsigned long delayTime;

void setup() {
  Serial.begin(9600);
  Serial.println(F("BME280 test"));

  bool status;

  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  status = bme.begin();
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
  Serial.println("-- Default Test --");
  delayTime = 1000;
  Serial.println();
  delay(100); // let sensor boot up
}

void loop() {
  printValues();
  delay(delayTime);
}

void printValues() {
  Serial.print("Temperature = ");
  Serial.print(bme.readTemperature());
  Serial.println(" *C");

  Serial.print("Pressure = ");
  Serial.print(bme.readPressure() / 100.0F);
  Serial.println(" hPa");

  Serial.print("Approx. Altitude = ");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println(" m");

  Serial.print("Humidity = ");
  Serial.print(bme.readHumidity());
  Serial.println(" %");
  Serial.println();
}

Code of the TFT screen with the BME280 (doesn't work)
// include the necessary libraries
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <SPI.h>
#include <SD.h>
#include <TFT.h>   // Arduino LCD library
#include <Wire.h>

// pin definitions
#define bme_cs  6
#define sd_cs   7
#define rst     8
#define dc      9
#define lcd_cs 10
#define mosi   11
#define miso   12
#define sck    13

//var definitions
#define SEALEVELPRESSURE_HPA (1013.25)

//Define hardware SPI connection with BME280
Adafruit_BME280 bme(bme_cs); // hardware SPI

// Define screen pins
TFT TFTscreen = TFT(lcd_cs, dc, rst);

//Define variables
char sensorPrintout1[6];
char sensorPrintout2[6];
unsigned long delayTime;

// this variable represents the image to be drawn on screen
PImage logo;

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

  bool status;

  // Initializing SD card
  Serial.print("Initializing SD card...");
  if (!SD.begin(sd_cs)) {
    Serial.println("failed!");
    //while (1);
  } else {
    Serial.println("OK!");
  }

  //Initializing BME280
  Serial.print("Initializing BME280");
  status = bme.begin();
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  } else {
    Serial.println("BME 280 sensor found");
  }

  // Start and clear TFT screen
  TFTscreen.begin();
  TFTscreen.background(0, 0, 0);

  // Lookup image on TFT screen
  logo = TFTscreen.loadImage("Logo.bmp");
  if (!logo.isValid()) {
    Serial.println("error while loading Logo.bmp");
  }
  if (logo.isValid() == false) {
    return;
  }

  //Draw logo on the screen
  Serial.println("drawing image");
  TFTscreen.image(logo, 0, 0);

  // Change text color to white
  TFTscreen.stroke(255,255,255);

  //Write some text
  TFTscreen.setCursor(0,25);
  TFTscreen.print("temperatuur 1: ");
  TFTscreen.setCursor(100,25);
  TFTscreen.print((char)247);
  TFTscreen.print("C");

  //write some text
  TFTscreen.setCursor(0,50);
  TFTscreen.print("luchtvochtigheid 2: ");
  TFTscreen.setCursor(100,50);
  TFTscreen.print((char)37);
  TFTscreen.print("C");
}

void loop() {
  // Read value of temperature
  int value1 = bme.readTemperature();
  int value2 = bme.readHumidity();
  String sensorVal1 = String(value1);
  String sensorVal2 = String(value2);

  // Change sensor value to a character array
  sensorVal1.toCharArray(sensorPrintout1, 6);
  sensorVal2.toCharArray(sensorPrintout2, 6);

  // Change text color to white
  TFTscreen.stroke(255,255,255);

  // Write value of temperature sensor
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout1);

  // Write value of humidity sensor
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);

  // wait  500ms
  delay(1000);

  // Change text color to black (aka overwrite text)
  TFTscreen.stroke(0,0,0);

  // Write value of temperature sensor
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout1);

  // Write value of humidity sensor
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);
}

Now this is the serial output:
Initializing SD card...failed!
Initializing BME280Could not find a valid BME280 sensor, check wiring!

At first it only showed the first line, then it stopped because of the while(1) loop. So I put it in comment to see if the BME initializes on its own.
I also tested the screen+SDcard and the BME280 separately, which worked just fine.
Update
I tried to test the programs with the complete circuit. The program of the TFT screen works fine that way but when I try the program of the BME280 it doesn't work. I have to remove the TFT screen from the breadboard to make it work.
Update 2
After some measurements with the scope I determined that the MOSI is pulled to 0V when I connect the 5V to the TFT screen. I also saw that the MOSI output on the BME280 board is 3.3V instead of 5V.
Could it be that the conflict in voltages is the cause for all my troubles?

And your question is...?

Have you examined the libraries to see if they initialize the SPI hardware in conflicting ways?

@IgnacioVazquez-Abrams i have not how can i fix this

Could you post the Serial output you get?

I will edit the original to add the serial output

It seems that it failed in setup for two out of three devices. It is kind of difficult to figure out whats wrong, it could be conflicts in different libraries, or simply due to wrong wiring. The easier way is to comment out your code and only active one device at a time, to make sure it works before adding another device.

I will add the code of the devices working seperately.

@hcheung both the BME program use the SPI library. so i don't think it's a conflict

Please check my blog post about this issue exactly.
The main idea is that the different SPI components do not respect the chip select and interfere with each other on the SPI bus. The way I solved it was to toggle between the different components using an array of switches- transistors in a way that in any given time only one component is connected to my Arduino (or any other master) through the SPI.
How to use multiple SPI devices with Arduino
While building my SmartHomeDIY project I encountered a problem trying to use multiple SPI devices connected to the same Arduino. Although the SPI bus should support multiple devices at the same time (toggling the Chip-Select line), this does not always work (mostly due to the part using the bus not respecting the chip select or other configuration issues). So after reading for some time and experimenting I came up with the following solution.
The above station is an IR recorder and sransmitter station. It can be set into recording state, which then saves the recorded IR-in data into and SDCard connected over SPI. But when not in recording mode it will listen over the RF24 (also connected via SPI) for commands. Once a command is given it will try to send the IR code request (for example turn TV on). To do that it will again have to move to SDCard mode and read the previously recorded data and retransmit it over the IR out LED.
So to solve this I have connected the SPI lines to couple of transistors/switches, then just CUT the lines of the part not being used at the moment and there for prevent the SPI lines collision.
Attached is the code and hardware layout to do just that.
Note that it does not matter which type of project you have. You can always do the same transistor-switch trick to cut of the problematic SPI lines while using the others.
A special note for the transistor configurations. It will not work if you pass as usually suggested, which means to set a logic level by design at the output of the transistor so that the base will toggle the out voltage (same as an amplifier).
Instead I set the signal to go trough the transistor, which is needed, so testing to select the transistor, which does not affect the actual signal (it will depend on the transistor type, spec and configuration...). So it took me some time to figure out the right transistor values and configuration.
For trial and error I used a logic analyzer with 8 logic lines or an oscilloscope.
I inspected the incoming signal and the outgoing signal to make sure the transistor does not temper with the incoming signal, so everything will continue to work as expected (the transistor is transparent to the actual data).
You could also use this logic multiplexer [8 Channel Logic Level Converter Convert TTL Bi-directional] to do the same job, which I have not tested yet. But I think my way is more fun! :)

Avoid links. Edit your answer and add the relevant information here. Links die, SE survive.

Connect the BME280 board by I2C, it cannot be used in a multi-SPI setup. The problem is that the MISO line it not decoupled from the bus if CS is HIGH but constantly pulled HIGH. This will disturb other bus members.

Thank you very much. Is there another solution possible because in my project i need to use 2 BME280 boards. so I2C won't be much of a solution.

most i2c devices will support more than 1 address, usually with a couple of pads on the board, connecting or breaking connections can change the address, so then you would be able to use 2 sensors on i2c

The BME280 supports two I2C slave addresses by tying SDO to either GND or Vddio. If you need to connect more than 2 devices to the same master use an I2C multiplexer as the PCA9547.


text:
Programming 5 inch TFT Display + Arduino Mega with Touch Shield (w/SSD1963)
I am newbie on Arduino and TFT Screens. But I am a semi-professional on programming and I decided to develop a device that can be controlled by Arduino via capacitive touch screen (there will be 2 buttons on the screen and while one of them will increase the current of a device, other will decrease). To do that, I've bought a complete solution (Arduino Mega + 5" TFT LCD + Arduino Shiled but without Resistive touch screen - this one), instead of resistive touch screen, I've bought this one and I've bought a separate PSU.
At the end, I have an Arduino Mega, 5 inch TFT Display, 5 inch Multi Touch Screen Panel with Controller GSL1680F (assembled to the Display) and Arduino Shield which is produced for this system. But I don't know how to communicate these three devices with each other. I know that, Arduino has built-in storage for the codes, and both TFT Display and Shield have micro-sd storage slots for placing codes. E.g. I don't know what is the aim of micro-sd storage slot on the shield.
As a result, is there any code samples / tutorials / video that I can follow to develop with this system? Thanks.

BuyDisplay have a full archive of libraries and samples for the TFT screen on the page you link to.

Hi @Majenko , Thanks for your reply. Can I use same codes on the product page for capacitive screens? Because, it is written as "8080 16-bit 5"Resistive Touch Shieid+SD Card" or can I use touch screen codes directly?)In addition what is the aim of SD Card Slot on the shield?
Because, all examples that I downloaded from product page are about Resistive Screens.

There is example code for the touch on the touch sensor page. You will need to adapt it for Arduino, or ask Google for a library. The SD card is for you to store data on, such as images to display, or sensor data that you want to record. It is the same as an SD shield.

source: Stack Exchange

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

sort: votes


text:
Transmit IR-Signal A, Receive IR-Signal B
I used the following program to send an IR code and I got the an unexpected result as below:
/*
   IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
   An IR LED must be connected to Arduino PWM pin 3.
   Version 0.1 July, 2009
   Copyright 2009 Ken Shirriff
   http://arcfn.com
*/

#include <IRremote.h>

IRsend irsend;

int j = 0;
void setup()
{
}

void loop() {
  for (int i = 0; i < 3; i++) {
    irsend.sendNEC(0xFF6897, 32);
    delay(40);
    j = j + 1;
  }
  delay(5000); //5 second delay between each signal burst
}

With the following schematic:

I expected to receive:

FF6897 Decoded NEC: FF6897 (32 bits) Raw (68): 8750 -4450 550 -550 500
  -600 550 -550 550 -550 550 -550 550 -600 500 -600 500 -600 500 -1650 550 -1650 550 -1650 500 -1650 550 -1650 550 -1650 500 -1700 500 -1650
  550 -550 500 -1700 550 -1600 550 -600 500 -1650 550 -600 500 -600 500
  -600 500 -1650 550 -550 550 -600 500 -1650 500 -600 500 -1700 500 -1650 550 -1650 550

Instead I receive consistently

C101E57B Unknown encoding: C101E57B (32 bits) Raw (68): 8850 -4450 500
  -650 450 -600 500 -600 550 -550 500 -650 450 -650 500 -600 450 -650 450 -1800 450 -1700 500 -1750 500 -1700 500 -1750 500 -1700 500 -1750
  450 -1750 500 -600 500 -1750 450 -1750 500 -600 450 -1750 500 -650 450
  -600 550 -600 500 -1700 500 -600 500 -600 500 -1750 500 -600 500 -1700 500 -1700 550 -1700 450

anyone knows how to fix this?
Code the Reciever uses to decode the just send signal:
/*
 * IRremote: IRrecvDump - dump details of IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
 * LG added by Darryl Smith (based on the JVC protocol)
 */

#include <IRremote.h>

/*
*  Default is Arduino pin D11.
*  You can change this to another available Arduino Pin.
*  Your IR receiver should be connected to the pin defined here
*/
int RECV_PIN = 6;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void dump(decode_results *results) {
  // Dumps out the decode_results structure.
  // Call this after IRrecv::decode()
  int count = results->rawlen;
  if (results->decode_type == UNKNOWN) {
    Serial.print("Unknown encoding: ");
  }
  else if (results->decode_type == NEC) {
    Serial.print("Decoded NEC: ");

  }
  else if (results->decode_type == SONY) {
    Serial.print("Decoded SONY: ");
  }
  else if (results->decode_type == RC5) {
    Serial.print("Decoded RC5: ");
  }
  else if (results->decode_type == RC6) {
    Serial.print("Decoded RC6: ");
  }
  else if (results->decode_type == PANASONIC) {
    Serial.print("Decoded PANASONIC - Address: ");
    Serial.print(results->address, HEX);
    Serial.print(" Value: ");
  }
  else if (results->decode_type == LG) {
    Serial.print("Decoded LG: ");
  }
  else if (results->decode_type == JVC) {
    Serial.print("Decoded JVC: ");
  }
  else if (results->decode_type == AIWA_RC_T501) {
    Serial.print("Decoded AIWA RC T501: ");
  }
  else if (results->decode_type == WHYNTER) {
    Serial.print("Decoded Whynter: ");
  }
  Serial.print(results->value, HEX);
  Serial.print(" (");
  Serial.print(results->bits, DEC);
  Serial.println(" bits)");
  Serial.print("Raw (");
  Serial.print(count, DEC);
  Serial.print("): ");

  for (int i = 1; i < count; i++) {
    if (i & 1) {
      Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
    }
    else {
      Serial.write('-');
      Serial.print((unsigned long) results->rawbuf[i]*USECPERTICK, DEC);
    }
    Serial.print(" ");
  }
  Serial.println();
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    dump(&results);
    irrecv.resume(); // Receive the next value
  }
}

Schematic wise:
one IR reciever with VCC and Ground connect and signal-out on pin 6

Where/How do you receive the data? What's your setup?

I Use a seperate arduino for that. It has an IR transmitter and an example sketch loaded.

What is the value of the voltage Vcc on the infrared transmitter circuit?

Possible duplicate of Arduino emits signal A (infrared) but another Arduino receives everything but A (IR-LED problem)

Eventho I did ask that question a two months ago and came across a similar problem. There is one key diffrence. Back then the signals where never ever constant. I never recieved the same IR-signal twice. Now after some changes and I dont know which made it so :). I get very consistant signals. Step closer to my goal.

The Vcc is connect to 5v on the arduino. I can check later today if this really is 5v

@Anton van der Wel: Show us the receiving half: Schematic and code. It will be sooo much easier to find where the problem is.

post updated aswell @AltAir I tested the voltage over the IR-LED  it was 1.7 V

In the received RAW codes, the width of the modulated pulses is less than the expected value. And the width of the spaces is bigger than expected.
This is due to the lack of an infrared sensor.
Use infrared receiver another model. For example TSOP4838.
Or try reducing MARK_EXCESS in the IRremoteInt.h of the Arduino-IRremote library from 100 to 50 or 0.
...
// Pulse parms are ((X*50)-100) for the Mark and ((X*50)+100) for the Space.
// First MARK is the one after the long gap
// Pulse parameters in uSec
//

// Due to sensor lag, when received, Marks  tend to be 100us too long and
//                                   Spaces tend to be 100us too short
#define MARK_EXCESS    0
...

And please increase the delay time in transmitter sketch (to avoid codes overlapping) :
...
for (int i = 0; i < 3; i++){
  irsend.sendNEC(0xFF6897, 32);
  delay(200);
  j = j + 1;
}
...

I changed the delay, still gives the same output as described in my post ;/ (C101E57B)

myReceiver.markExcess= 100;  gives me the exit status 1 'class IRrecv' has no member named 'markExcess'  so is my libary missing something?

@Anton van der Wel, in the previous question, you used the IRLib2 where the parameter is used. I updated my answer according to the library you are currently using.

sadly it didnt make a diffrence. Tried both 50 and 0 both send C101E57B. as IR reciever Im using VS1838B

Please, try to change tolerance to 30 or 35 in IRremoteInt.h #define TOLERANCE0       30 .

also didnt change the output ;/

@Anton van der Wel, you are using an LED without a limiting resistor.  This can lead to overload and distortion of the signal. Also, nothing is known about the infrared receiver and how it is connected to the power supply.

The IR reciever is connected to the 5v pin on an arduino the ground to the ground next to the 5v pin and the Output pin to pin 6 on the arduino. how to not overload the LED?

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


text:
Arduino Yun with PoE does not work when powered via PoE
I have a Arduino Yun with PoE with LininoOS version

Linux arduino 3.3.8 #1 Thu Jun 2 12:28:33 CEST 2016 mips GNU/Linux

I have the Version 4.0 of the module.
I often notice that when I connect the module via a USB cable and login via Serial the WAN and WLAN LEDs blink and I can SSH via both the mediums.
However I cannot do the same when the Yun is completely powered via an Ethernet Cable and the I see the Yun frequently restarting and becoming inaccessible via SSH.
I cannot troubleshoot this problem via software as whenever I connect the USB cable along with the Ethernet Cable the power supply switches completely to the USB and the PoE stops and everything suddenly works well again.
Has someone faced the same issue? Is it because of the High Frequency Whistle problem where I need to solder a 100µF Electrolytic Capacitor to the PoE adapter?
Update
I measured the 5 V and 3.3 V pins on the Yun they provide their respective voltages via a multimeter.
I have a Microsens fast ethernet switch with PoE which provides standard (minimum 44V DC)

Apparently, the WAN LED blinks indicating the Ethernet Connection is available however everytime I ping the Yun it goes down.

Do you have a multimeter? Try measuring the 5 Volt and 3.3 Volt supply voltages on the Yun.  What voltage are you supplying over the ethernet cable?

PoE Adapter
Silvertel AG9600 1R requires a 100µF 16V Electrolytic Capacitor between it's PIN 7 and PIN 8
According to the PoE Yún Thread the capacitor polarity should be as follows:

PIN 7 --> Capacitor_Negative. PIN 8 --> Capacitor_Positive

solved my problem. I think the default 470uF capacitor might not be able to charge-discharge appropriately with data signals in the PoE.


text:
Are pins 0 and 1 (Rx and Tx) parallel with the USB jack? Can I connect another USB jack th 0 and 1 and use it to upload sketches?
I have a compact weatherproof enclosure and the onboard USB jack of my Mega is close to the edge. I didn't want to add a bulky weatherproof USB jack, so I'd like to just leave a female USB pigtail loose inside the enclosure.
The only thing is, I want to avoid the extra assembly step of soldering leads directly to the lugs on the board. I'd like to make a shield instead, with screw lug headers to attach all my wires to. That way a lot of my connections can be solderless and the assembly tech can just plug in the shield.
Can I connect the four wires of a USB cable to the header pins? I suspect I'd use Vin, GND, pin 0 and pin 1, but I'm not 100% sure. Thanks for your advice, gentlemen.

Have you had a chance to look at its schematic yet?

I have, but unfortunately I could not make sense of it.

No. For many reasons. No. USB is not TTL. You need an adapter to connect rx/tx pins of arduino to USB. And the on-board adapter has the DTR line connected to reset the Atmega before writing a program into it. Without it, you would need to push the reset button in the right moment.


text:
Should I use an accelerometer or gyroscope in my project?
A friend and I are working on a sign language translation glove.
Our glove currently successfully uses 5 flex sensors to determine the bend of each finger and can accurately detect letters in the sign language alphabet.
We are now trying to add the functionality to detect one-handed words. Many of these words involve making a letter, but adding some motion. For example, the colour "blue" involves making a B, then shaking/waving your hand in the B position.
We are wondering which type of sensor would be able to handle this. From our research so far, we assume this will either be an accelerometer or a gyroscope, but are not sure which one would be best in the scope of our project.
Any help would be much appreciated!

try each one. that way you can learn how each behaves. that knowledge can be very useful in your future projects.  something like this has both https://www.amazon.com/Makerfocus-MPU-9250-Gyroscope-Accelerometer-Magnetic/dp/B01MU0HV8T/ref=sr_1_1_sspa?ie=UTF8&qid=1512674896&sr=8-1-spons&keywords=gyroscope+module&psc=1

You should use both.

Second both. I'm not even sure if you can get (MEMS) gyroscopes without also an accellerometer within it. For example an MPU-6050

Use both. Accelerometer measure movement in direction of axes when gyroscope measure rotational movement. Being very delicate you can spin accelerometer and sensor won't see any changes, and you can move gyro in one axis without sensor detection. Having both mounted on one board (or in one casing) there is no possibility that motion will be missed by both. Look at the pictures what the sensors do:

There is a plenty of integrated accelerometer-gyro sensors, for example MPU-6050 Accelerometer + Gyro with supporting libraries. Please check here

An accelerometer is a better choice here. For your application, you aren't worried about initial motion but just acceleration. Plus, an accelerometer is cheaper.


text:
Looking for link to Double Pole Single Throw (DPST) relay for Arduino
Need to find a DPST relay that is 'Arduino' friendly and that is capable of 30A at 240VAC. Anyone can share links ?
Not looking for recommendation, just ideas on what you saw or used in the past.
Thanks.

30A is going to be a large relay. Get ready to put down a bit of cash.

cash is not an issue here, finding one that I can couple to an Arduino is...

I am maybe confused... The 240V circuit is composed of 2 live wires, 120V each, phased out by 90 degree to get the full 240Vac.

you could use a solid state relay ... it should work directly on the arduino

I use this: https://www.seeedstudio.com/Grove-SPDT-Relay%2830A%29-p-1473.html

@juraj How would you connect the 2 phase wires on that ?

A relay that can switch 30A on mains voltage is not going to be able to switch directly from 5V. Getting something that can switch from 24V is much more realistic.
High amp relays are often called contactors. 4-pole ones are not uncommon for industrial motor applications. 3 high-amp poles are for 3-phase power and a low-amp one for a control signal.
You can buffer up the signal using a transistor (you'd need one anyway to supply the coil amps) or another relay.

Indeed and using an other relay to control the main relay is possible.

Do not be scared from other answers. There are relays which hold the coil with 5 V from Arduino. Like the relay on this Grove 30 A Relay Module. It is powered from 5 V pin and the command to close is from the GPIO pin (works with 3.3V IO too).
Use two of these SPDT modules, if you can't find DPST powered with 5 V.
If you will use the Grove module and you do not use other Grove modules, there is no need to buy the Grove base shield. You can connect the module with this cable.

The Grove module mentioned in this answer is only single pole. The question asks for a double pole relay.

You will be hard-pressed to find a mechanical relay that you can directly connect to the Arduino digital pins. Any general purpose relay that fits your specs for the switched side will do, but you will need to pay attention to the datasheet for the coil voltage and current required to activate the relay.
Then, you'll want to use a driver circuit like a transistor (BJT or MOSFET) so that the low-voltage, low-current digital output of the Arduino can control the larger-current needed to trip the relay coil.

Yeah and opto isolation ;-)

A well designed relay driver circuit ought not strictly need opto-isolation. If you put a reverse-biased diode across the relay coils to prevent voltage spikes from damaging the transistor, the relay itself provides sufficient isolation between the switched circuit and the microcontroller.

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


text:
Transmit data to long distance (120m)
I want to transmit data from multiple sensors to an Arduino and distance would be approximately 120 meters.
What protocol or configuration should I use?
Actually I am trying to read values from 5 temperature sensors located in 5 different spots of warehouse. I want to read them and trigger some relay based on the values.
I thought about I2C but I have read somewhere that its not built for long distances. Also thought about RS-485, but I don't know if that supports bus (connect all sensors to same line).
Which solution do you suggest?

You want to transmit ~120m over wire. If wireless is adequate, see SX1278 ICs and LoRaLib (50m in dense forest, 200m in urban terrain, more with LOS). If you stick with wired, use CAT5 cable or better, it’s well insulated against EMI and cheap. CAT5E/CAT6 is better, costs a bit more. You could use coax RG6, which is just wonderful.

While thinking about RS-485, did you read about it? It is a bus. It is designed for long distances.

So if i use rs485(via max485) will i have to use microcontroller on every side between bus and sensors ? Or its enough to connect the sensor (analog sensor) to max485 directly ?

You will need some kind of controller to react to the bus. RS-485 is a digital bus specification, you cannot just put analog signals on it... Each node will have to have an address assigned to it and respond to the bus master's requests.

Thanks for your answer jose. One last question: will i need that kind of controllers if the sensors be digital?

Since this is arduino.stackexchange -- An Arduino will make an excellent bus access controller. And you will need one even if the sensor is digital. Something has to have the smarts to handle bus access.

I2C is not built for long distances (max. some meters) But you can make it via RS485, But you will need to add termination resistors to each end.


text:
External ADC reference when using MATLAB support package for Arduino
I am using the MATLAB support package for Arduino.
However, I need to configure the ADC reference to external. MATLAB documentation doesn't really explain how to do this?
Is there any way I can use the MATLAB support package and configure the Analog pins to use external ADC reference?

MATLAB documentation doesn't really explain how to do this?

it makes sense. read your arduino documentation instead.

Is there any way I can use the MATLAB support package and configure the Analog pins to use external ADC reference?

absolutely.

Any more details on how to do this will be much appreciated. I am programming using only MATLAB and not writing a single line of C code using Arduino IDE. There is no mention of any wrapper function in the MATLAB documentation of its Arduino support package that lets the user configure the ADC reference to external.


text:
How the output of a bicycle dynamo can be displayed using Arduino?
I am on a project in which I need to make bicycle dynamo frequency meter.
The power generator’s output should vary with the speed of the wheel.
Which parts do I need to make it work?
The project should look like: : http://www.lanzo.se/experiments/dynamo/dynamo.html
                 or http://practicalphysics.org/bicycle-dynamo-and-oscilloscope.html
-->without oscilloscope ( which is replaced with Arduino and panel )

The power generator’s output WILL vary with the speed of the wheel, and the frequency / amplitude of the signal will vary as well. Are you attempting to measure and display the frequency of the bicycle dynamo "pulses" or do something else?

I want to measure period where voltage is measured along the y axis and time along the x.

The first thing to look at before you connect the bicycle dynamo to an Arduino is what type of signal / voltage it generates. The link you've provided: http://www.lanzo.se/experiments/dynamo/dynamo.html gives you the answer. It's an AC signal which varies between +4V and -4V (It could be much higher if you spin it faster). On the Atmega328P data sheet under "Absolute Maximum Ratings" it says "Voltage on any Pin except RESET with respect to Ground -0.5V to VCC +0.5V". Obviously, -4V exceeds the -0.5V maximum so don't connect it directly to an Arduino.
The signal from the dynamo to Arduino must be limited to between 0V and 5V (for an Arduino operating at 5V). The answer on how to accomplish this is a general electronics question and should be asked on a different forum e.g. https://electronics.stackexchange.com/questions/132330/8v-ac-signal-into-3-3v-digital-input-pin
The "frequency meter" part of your question is easy to build with an Arduino. You could use an Uno or something smaller like a Pro Mini with a 16 x 2 LCD display and this library: https://github.com/k3ng/k3ng_antenna_tuner/tree/master/libraries/FreqCounter. An I2C backpack for the LCD is only a dollar more and makes the wiring much easier. To use the backpack you'll need this library: https://github.com/marcoschwartz/LiquidCrystal_I2C.

It al depends on what is the maximum output of the dynamo.

less than 5V (not likely): great just connect it directly with the Analog measuring pin of the Arduino (A1- A7)
more than 5V: we got different options here

Make a simple voltage divder to measure the output
use an external ADC

I have old bicycle with dynamo but not sure what the dynamo voltage actually is. I'm prefering "more than 5V".

Also, I'm beginner in this and describing the process would help me the most.


text:
OBOE: Need help understanding, possible type conversion issue
I have an algorithm that its main purpose is decoding, converting, or what have you a string of uppercase letters (A-Z) into a number. This is almost like converting a base 26 number into base 10, however I believe that a base 26 number encoded would actually include numbers, I am working strictly with uppercase letters, I digress.
I have an implantation working in C++11, in fact most of the controller algorithm was a direct copy, with a slight change to the indexOf method.
The C++11 version works as I expect it to. So initially I thought the new indexOf method was incorrect, but after a simple test, it is working as expected. I have narrowed down the problem to a line in the convertTo10 where I am calling the pow function.
As you can see from the Serial.println()'s in the convertTo10 method, the output is printing exactly what we expect, 0 & 26.
However, the output of this function is 25. WHAT?
I have read the docs on the pow method from the Arduino lib, and it takes in two floats and returns a double. Even if the issue was a type conversion issue, converting a double to an int truncates the number, it does not round it. Well, this is from working with C++.
Any help with this issue would be much appreciated.
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <inttypes.h>

#include <Arduino.h>
#include <avr/pgmspace.h>
#include <Wire.h>

const char _values[26] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z'
};

const int _val_len = 26;

int indexOf(char needle);
int convertTo10(String value, int len);

String x = "BA";
int len = 2;

void loop() {
  Serial.print(x);
  Serial.print("=> ");
  Serial.println(convertTo10(x, 2));
  delay(50000);
}

int convertTo10(String value, int len) {
    int lastIndex = len - 1;
    double output = 0;
    int pos = 0;
    Serial.println();
    for (int i = lastIndex; i >= 0; i--) {
        int r = indexOf(value[i]);

        output += (r * pow((_val_len, pos));
        Serial.print("     output => ");
        Serial.println( output );
        pos++;
    }
    return output;
}

int indexOf(char needle) {

    int first = 0;
    int last = _val_len - 1;
    int mid;

  do {
    mid = (first + last) / 2;

    if (_values[mid] == needle)
      return mid;
    if (_values[mid] > needle)
      last = mid - 1;
    else
      first = mid + 1;
  } while (first <= last);

  return -1;
}

For Reference, Here what it is outputting:
BA =>
     output => 0.00
     output => 26.00
25

Also posted on the Arduino Forum.

You can make the return value be 26 in this case by rounding. That is change the last line of your conversion function to be: return round (output);. The fact that it is returning 25 indicates that the pow function is not giving an exact result. If you increase the number of decimal places printed you will see that you are actually getting 25.9999961853.

way too complicated:
int convertTo10(char *num_26, int len) {
  int tmp = 0;  //hold the output
  int i = 0;  //indexing the input
  while (len--) tmp = tmp * 26 + (num_26[i++]-'A');
  return tmp;
}

note:

"* 26" can be further simplified;

error checking could be built-in here, or somewhere else (better).

better structuring could get rid of one of the temporary variables.

Thank you for the optimized code! However, I was hoping I could get an explanation on what is happening in the code I posted? What did I do wrong?

What you did wrong was to rely on a floating point number to be exact.  They hardly ever are.

@Delta_G I realize this now. Thank you for the correction, I should have just waiting until the morning to revisit the problem, instead of ask dumb questions. I do appreciate the help.

@dannyf As much as I appreciate this solution and the time and effort you took to help me. I have to mark this solution as incorrect. I have verified that  on a atmel2560 compiled with avr-gcc, and on Debian x64 compiled with g++ under standard 11, this method will always return 0.

This code fails because i is not initialized. Otherwise it is conceptually similar to my answer. If you change the third line to int i = 0; it works.

Your code is incredibly complex for a simple thing like converting a number from another base. This works (prints 26):
const char * test = "BA";

long convertTo10 (const char * s)
  {
  long result = 0;
  for (const char * p = s; *p; p++)
    {
    result *= 26;   // base
    result += *p - 'A';  // make zero-relative
    }
  return result;
  } // end of convertTo10

void setup()
  {
  Serial.begin (115200);
  Serial.println ("Starting.");
  Serial.println (convertTo10 (test));
  }

void loop() { }

With input "CBA" it prints 1378 as expected.  Sketch size: 2,300 bytes of program memory. The sketch size reduces to 2,236 bytes if I make the function return int (as you did) rather than long.
You don't need to use String (in fact it saves RAM and avoids memory fragmentation to not use it). You don't need to pass the length, with both char* and String you can deduce the length. If you use long as the return type you can handle larger numbers.
By using pow you are bringing in a library which is not needed and which will consume program memory. By using double you are introducing possible inaccuracies since double does not necessarily store numbers exactly. Your code used 7,604 bytes of program memory once I corrected the syntax error and added an empty setup function.

Also, the method I illustrate above is much faster. I timed it at converting "BA" in 4.3 µs, whereas the method using the pow function takes 442 µs. So the simpler method is also 100 times faster.


text:
When Raspberry Pi is preferred over Arduino
We are doing some projects in class. One of my friends is doing a weather and humidity station using raspberry Pi with a couple of sensors and LCD. I have a little experience in Arduino. So I asked her, why doesn't she do it using an Arduino? She said Pi is more 'powerful'. In what aspects, is it more powerful than Arduino? When should I go for Raspberry Pi over Arduino?

It is more powerful indeed. Yet an overshoot for a "weather station". RPi is a full featured computer. Arduino is a pretty stupid and weak microcontroller.

Overshoot. Hm I kinda felt the same :-)

As explained in the answers, each has its own strengths. Some projects can even benefit from using both. See the answers to this somewhat related question: Why connect arduino with Rasberry pi?

@EugeneSh. Yet it always beats Pi on uptime, power consumption, GPIO output current, has ADC, and the driver libraries for WiFi shields don’t break in operation. Try keeping a live WiFi  link with a Pi for two weeks...

Arduinos usually also beat a Pi in terms of security, a full OS most certainly has more exploits than a Nano running a few hundred lines of code. :D

Somewhat of an opinionated question but I'll give some feedback. It depends on various things:

How much UX and UI you want to give to your client
How easily can you program it
Which is a cheaper solution
How fast do you want the program to run
What is more durable and how long do you want to use the device

To prevent this answer from being lengthy, I'll do a quick comparison from my experiences with both.
Arduino: Cheap, easy to program, capable of flexibility with UX and UI but has very limited memory. The Arduino is typically good for something that can just complete tasks on their own. I've written state machines and have used it for PLCs with an Arduino. It's a good device for a cheaper budget. Arduino is pretty fragile, however.
Raspberry Pi: More expensive, a lot more powerful in terms of processing speed, has a lot more memory, extremely good for UX and UI devices that are being developed, good for artificial intelligence, state machines, PLCs, etc. Also really good for data logging, image processing, and radio frequency applications. You can also boot an operating system on it (e.g. Linux/Unix). In other words, a Raspberry Pi can used as a computer while the Arduino... well I guess it depends how you define, "computer" LOL.
So if you're trying to do something as simple as using sensors and LEDs, I'd go for the Arduino Uno.

Yea. I guess Arduino is better for sensor related projects. Also I think Pi consumes more power.

Dont forget that there are more Arduinos than just the Arduino UNO, for example the DUE is a 32bit MCU which can be used for tasks that are not normally suited for a standard microcontroller such as DSP.

@A.J. Before I edited my answer, I did talk about the Due but I didn't find a purpose of including it because the functionality is still the same as its 8 bit siblings... I have seen people write their own operating systems with the Due, which is quite a feat.

Raspberry pi is more powerful but a micro controller is more consistent. If you need to be pushing a value down a wire with very specific timings the you will need an arduino because having a full OS on the raspberry pi means sometimes there will be delays from the OS scheduling other tasks first.

The claim that the Pi is more "powerful" is a bit misleading. What does "powerful" really mean? And is it relevant to making a weather station?
I made a temperature and humidity sensor as described here using an Atmega328P (the processor that is in the Arduino Uno). The estimated average power consumption is 42 µA which has allowed it to run from 3 x AA batteries for a couple of years before they needed replacing. I think you'll find that the Pi with its more "powerful" processor and extra components would not be able to do that.
I see from a quick search that the Pi consumes 80 mA to 240 mA when idle (depending on the model). This would make a Pi-powered weather station eat through batteries 2000 times as quickly. Perhaps that would be a consideration.
The Pi is really a Unix PC on a board, which means it goes through the normal boot sequence with a possibility of errors occurring during booting. To see what those errors are you need to connect up a keyboard and screen, or connect via a network to it from another PC.
I don't want to run down the Pi - it's a nice cheap Unix computer on a small board. But the Arduinos (many of them) are somewhat simpler to program. You don't need to worry about the operating system for a start. For a weather station, taking a reading every 5 minutes, who cares if the Pi can take the reading "50 times faster"?

Speed of recovery from sleep
I have an answer about letting serial data wake an Arduino - after some experimenting I was able to get the Atmega328P to wake from its deepest sleep (260 nA - yes 0.260 µA!) within 6 clock cycles (750 ns). I doubt you could achieve that on the Pi, either the low power consumption, or waking up in under a microsecond.
This was fast enough to detect the start bit in serial data at 9600 baud, process the start bit, and then the rest of the incoming byte without losing data.

The errors point is pretty good. Because the pi is doing all the normal linux stuff like writing to storage, it it loses power it could end up breaking the OS where as an arduino should be able to be powered off and on with no issues.

As opposed to the Arduino boards, the Raspberry Pi is a single-board computer with a quad-core CPU, a GPU, on-board RAM, and many peripherals. The main difference between the Pi and the Arduino (or any basic microcontroller) is the operating system. The Pi runs many Linux distributions (Debian being the official one), enabling the user to execute complex computing tasks that would be impossible to run on Arduino without external circuitry. Hence, the Raspberry Pi would be adequate for any software requiring significant CPU/GPU power or memory. Keep in mind that most Arduino's can be interfaced with the same type of peripherals that are found on the Raspberry Pi, although processing power might be lacking. Also, low-level interfacing with analog signals is much more convenient with Arduino, since it has integrated ADCs (analog-to-digital converters).

When should I go for Raspberry Pi over Arduino

There is always the price difference but apart from that I would say: The Raspberry Pi can do everything the Arduino can and do it better and faster EXCEPT tasks which are very time critical. Thus if you need to responds to events in micro seconds or millisecond or if you need to generate signals in those order of magnitudes you will need an Arduino.

Bare metal programs on RPi won't perform any worse than Arduino for any realtime requirements. People are just spoiled by having OS on it.

Yea bare metal programs will be too faster than Arduino. Cz, Pi's clock is almost 50 times faster :D

In "pure hardware" based systems, real time systems, you can always prefer Arduino over Pi with OS. Power consumption, price are other plus points for UNO. Pi is always the better one in complex computing tasks, where its OS simplifies those tasks. But you don't wanna use a "computer" for sensor related projects for sure !


text:
Arduino uno and ESP8266
Scenario :

I want to connect ESP8266 to Raspberry-pi's wifi network.
Arduino Uno is connected to ESP8266
Raspberry-pi will send a signal (1/0) to ESP8266, when its 1 Arduino will turn on/off a Relay.
I do not have a USB to UART Serial module

So my question is how to complete this task? Is it a feasible one?
I had been looking for many websites, almost all are using USB to UART Serial module to burn firmware to ESP8266.

You can use the USB-to-Serial adapter of the Arduino UNO, it has one on-board (ATmega16U2). Check the schematic of the UNO to understand what's going on.
First, upload an empty sketch to the UNO's ATmega328P, to make sure that it doesn't use the UART.
Connect the TX pin of the ATmega16U2 (i.e. the RX pin of the Arduino, digital pin 0) to the RX pin of the ESP8266. Connect a 2kΩ resistor between the ESP's RX pin. Together with the 1kΩ resistor on the ATmega16U2's TX line (on the Arduino), this creates a voltage divider that acts as a level shifter from 5V to 3.3V.
Connect the RX pin of the ATmega16U2 (i.e. the TX pin of the Arduino, digital pin 1) to the TX pin of the ESP8266.
Connect the grounds together as well.
In the Arduino IDE, select the ESP8266 under Tools > Board. Then enter programming mode on the ESP:

Bring reset low
Bring GPIO0 low
Bring reset high
Bring GPIO0 high

Then upload your sketch to the ESP.
I recommend adding simple push buttons and pull-up resistors:

(The ESP-01 has GPIO15 shorted to ground internally, so you don't have to worry about that. If you were using an ESP-## module that breaks out this pin, you need an external pull-down resistor.)
Keep in mind that you will also need a decent 3.3V power source, and some decoupling capacitors.
A Beginner's Guide to the ESP8266


text:
Problem opening multiple text files simultaneously/in-order using <SD.h>
I am looking to log analog sensor data using 3 pins, A1, A2, A3. My project requires continuous mapping of data, and hence an SD card shield was necessary. However, I need to log the incoming data into 3 different text files, and for that purpose I assumed that opening the 3 files simultaneously might or might not be possible as indicated here (I am a beginner, so I wasn't able to comprehend everything, and I am short on resources:)
So for the time being, I worked my way around with opening the three files in order. Rather than opening them all at once,writing the data on to each file and then closing them, I did all three tasks in 1) separate functions for all three files and calling them in the loop() function, 2)keeping all the stuff in the loop() function itself.The result for method-1 was no file was ever created, and that for method-2 was only the first file was created and the rest, nope. Here's the code for both the versions. What could I be doing wrong? Thanks in advance!
My board is an Arduino Uno. Yes, I have formatted the SD card with FAT32. My wiring is in place, my code is the only possible problem I see.
Method 1
#include <SD.h>
File Cu_volt;
File Gunmet_volt;
File Al_volt;
static float volt_Cu, volt_Gunmet, volt_Al;

void setup() {
  Serial.begin(9600);
  analogReference(INTERNAL);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);

  //Initialize SD card module, CS pin set at 4
  Serial.println("INITIALIZING SD CARD...");
  //check for SD errors
  if ( !SD.begin(4)) {
    Serial.println("INITIALIZATION FAIL...");
    while (1);
    return;
  }
  Serial.println("INITIALIZATION DONE");
}

void loop() {
  // read the input on analog pin 0 copper electrode:
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 to VRef=INTERNAl)
 copperFile();
 gunmetalFile();
 aluminiumFile();
 delay(3000);

}
void copperFile() {
  Cu_volt = SD.open("Copper.txt", O_RDWR | O_APPEND);
  if (!Cu_volt) {
    Cu_volt = SD.open("Copper.txt", O_RDWR | O_CREAT);
    if (!Cu_volt) {
      Serial.println("Failed to open file at all");
    }
  }
  volt_Cu = analogRead(A1) * (1.1 / 1023.0);
  // print out the value read(COPPER):
  Serial.print("Copper voltage=");
  Serial.println(volt_Cu);
  if (Cu_volt) {
    Cu_volt.println(volt_Cu);
    Cu_volt.close();
  }
}

void gunmetalFile() {
  Gunmet_volt = SD.open("Gun_metal.txt", O_RDWR | O_APPEND);
  if (!Gunmet_volt) {
    Gunmet_volt = SD.open("Gun_metal.txt", O_RDWR | O_CREAT);
    if (!Gunmet_volt) {
      Serial.println("Failed to open file at all");
    }
  }
  volt_Gunmet = analogRead(A2) * (1.1 / 1023.0);
  // print out the value you read(GUNMETAL):
  Serial.print("Gun metal voltage=");
  Serial.println(volt_Gunmet);
  if (Gunmet_volt) {
    Gunmet_volt.println(volt_Gunmet);
    Gunmet_volt.close();
  }
}

void aluminiumFile(){
  //opening aluminium file
  Al_volt = SD.open("Aluminium.txt", O_RDWR | O_APPEND);
  if (!Al_volt) {
    Al_volt = SD.open("Aluminium.txt", O_RDWR | O_CREAT);
    if (!Al_volt) {
      Serial.println("Failed to open file at all");
    }
  }
   volt_Al = analogRead(A3) * (1.1 / 1023.0);
  // print out the value you read(ALUMINIUM):
  Serial.print("Aluminium voltage=");
  Serial.println(volt_Al);
  if (Al_volt) {
    Al_volt.println(volt_Al);
    Al_volt.close();
  }
}

Method 2
#include <SD.h>
File Cu_volt;
File Gunmet_volt;
File Al_volt;
static float volt_Cu, volt_Gunmet, volt_Al;

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  analogReference(INTERNAL);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  //Initialize SD card module, CS pin set at 4
  Serial.println("INITIALIZING SD CARD...");
  //check for SD errors
  if ( !SD.begin(4)) {
    Serial.println("INITIALIZATION FAIL...");
    while (1);
    return;
  }
  Serial.println("INITIALIZATION DONE");
}

void loop() {
  // read the input on analog pin 0 copper electrode:
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 to VRef=INTERNAl)
  volt_Cu = analogRead(A1) * (1.1 / 1023.0);
  // print out the value you read(COPPER):
  Serial.print("Copper voltage=");
  Serial.println(volt_Cu);
  //opening copper file
  Cu_volt = SD.open("Copper.txt", O_RDWR | O_APPEND);
  if (!Cu_volt) {
    Cu_volt = SD.open("Copper.txt", O_RDWR | O_CREAT);
    if (!Cu_volt) {
      Serial.println("Failed to open file at all");
    }
  }
  if (Cu_volt) {
    Cu_volt.println(volt_Cu);
    Cu_volt.close();
  }
  volt_Gunmet = analogRead(A2) * (1.1 / 1023.0);
  // print out the value you read(GUNMETAL):
  Serial.print("Gun metal voltage=");
  Serial.println(volt_Gunmet);
  //opening copper file
  Gunmet_volt = SD.open("Gun_metal.txt", O_RDWR | O_APPEND);
  if (!Gunmet_volt) {
    Gunmet_volt = SD.open("Gun_metal.txt", O_RDWR | O_CREAT);
    if (!Gunmet_volt) {
      Serial.println("Failed to open file at all");
    }
  }
  if (Gunmet_volt) {
    Gunmet_volt.println(volt_Gunmet);
    Gunmet_volt.close();
  }
  volt_Al = analogRead(A3) * (1.1 / 1023.0);
  // print out the value you read(ALUMINIUM):
  Serial.print("Aluminium voltage=");
  Serial.println(volt_Al);
  //opening aluminium file
  Al_volt = SD.open("Aluminium.txt", O_RDWR | O_APPEND);
  if (!Al_volt) {
    Al_volt = SD.open("Aluminium.txt", O_RDWR | O_CREAT);
    if (!Al_volt) {
      Serial.println("Failed to open file at all");
    }
  }
 if (Al_volt) {
    Al_volt.println(volt_Al);
    Al_volt.close();
  }
  delay(3000);
}

Does it works if you only write to one file and comment out the rest?

Writting the three reading in the same file can be an alternative, writting as three comma separated values per line.

@LookAlterno I'll check it out. Using the alternative looks like a plausible idea anyhow:)

There are several variations of the SD library - some support multiple files, others do not.
Try calling .begin (and .end) on each write loop, and add in .flush - see below.
If that works with your library then take the (.begin / .end) out of the loop and try again.
#define FILENAME "myfile.txt"

void writeToFile() {
    File f;
    // begin and end on each write
    if (SD.begin(10, 11, 12, 13)) { // I use an older library that allows pin reassignment
        f = SD.open(FILENAME, FILE_WRITE);  // This will append and create if not exisiting
        if(f) {
            f.println("a string");  // Your write operations
        }
        f.flush();          // This ensured the write buffer actually went to file
                            // even if less than the block size (512b?)

        f.close();
        }
    SD.end();                   // Do this after every write operation
}

For people having similar problems with creating multiple files on an SD card, it may be a memory issue. You need to have a certain amount of unused dynamic memory (about 300 bytes of free space, in my experience) in order to write to an SD card - and more if you are writing multiple files. Following the instructions on this page may help.


text:
Serial Port Issues Elegoo Mac OX High Sierra
Edit:
Unfortunately the question that has been linked to my question does not answer my question. I have followed its instructions but it is a slightly different issue. Any help on my question would be hugely appreciated:

Apologies but I am very new and trying to learn how to use the Arduino. I bought a starter kit from Elegoo the included an Arduino Uno (I think it is a knock off and no the real thing?). I Have been trying to get the code to upload on to it and keep getting the following errors:

Sketch uses 2282 bytes (7%) of program storage space. Maximum is 32256 bytes. Global variables use 212 bytes (10%) of dynamic memory,
  leaving 1836 bytes for local variables. Maximum is 2048 bytes.
  avrdude: stk500_recv(): programmer is not responding avrdude:
  stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

So I know that that my iMac is recognising the Arduino but I am still not able to upload any code to it. I have spent hours trying work around solutions I have found on the internet or Elegoo have sent me.
I have three questions. Firstly if I just buy a real Arduino from Arduino (I had not realised I was being sent an imitation) will this solve my problems?
Secondly, if not can anyone recommend a work around that I would be able to implement? I am reasonably computer literate but not to the level of diving into the Terminal and inputting lots of code!
Thirdly, I am really struggling being a beginner with the instructions given by Elegoo, they are very badly translated and confusing. Can anyone recommend a way to learn the basics and complete some basic projects for a beginner. I am happy to pay for the tutorials if needed.

Possible duplicate of My Arduino isn't showing up on my computer. What should I do?

"So i know that that my iMac is recognising the Arduino " => How?

Ah hi! I followed the instructions in the question that got linked to my question. By going to About this Mac and then looking at the Hardware and the USB port and i can see under Communication device it says all the device information and then: Manufacturer: Arduino (www.arduino.cc)

And in the Arduino IDE, you have selected a programming port that looks like /dev/tty[something] ?

The Port i have selected is: /dev/cu.usbmodemFA131 (Arduino/Genuino Mega or Mega 2560)

The Programmer i have selected is: AVRISP mkII. Is that what you meant?

I don't know if i should have also said when i plug it in there is a constant green LED and a flashing yellow LED

I have also tried to fix the problem with this video that says it is for High Sierra. I get the same errors, although the yellow light does become constant while my Mac is trying to upload the code.


text:
Creating String Arrays and passing each index value to a variable after a given period
Is there a way to take an input string, store it into a array and then pass each index of that array to a variable to hold  before being overwritten by the next array index value?
For example:
A number of input values which are of type:String are being created
String 1 is given as "Value: 7.93 22-10-2017 10:33:32"
String 2  is given as "Value: 8.93 22-10-2017 12:10:15"
.
.
.
String 10  is given as "Value: 6.93 22-10-2017 18:03:04"

The string structure is known but its contents as such will vary
After a time period of say 60sec. The contents of array[0] which will be String 1 will be assigned to a given variable "output"
After the next 60sec time period .The contents of array[1]  Which will be String 2 will be stored into  the same "Output" variable in which the previous value will be now overwritten
This continues until array[9] i.e String 10 in which the array will begin over and start to populate "output" with newly presented string values

http://idownvotedbecau.se/imageofcode

Also, please tell us what you are trying to achieve. Passing an index to a variable is not the real goal, but only the means to an end. What is your real goal?

Originally I was attempting to pass the characters of each string using the toCharArray() function. The solution was much simpler and straight forward in the end. I've posted it below.

Solution Used Below:
// Input 1-3 represents input string

String Input1 ="Value: 7.93 22-10-2017 10:33:32";
String Input2 ="Value: 8.93 22-10-2017 12:10:15";
String Input3 ="Value: 8.93 22-10-2017 12:10:15";
String message[] ={Input1,Input2,Input3};

// Assigned 'Output' Variable will be populated by each index of the array
String Output;

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

// Each index of the array will be stepped through and passed to 'Output'
//delay() will control period between each index value

void loop()
     {
         for (int i = 0; i < 3; i++)
            {
                  Output=message[i];
                  Serial.println(Output);
                  delay(5000);
            }

     }


text:
Arduino Nano timer, please advice
I'm new here and in the Arduino world. I try to put together a system to cut the power of a LED night light after a preset time. The light is powered by a 5V accu and I would like to avoid to re-charge the accu each morning if the light stays on all night...
I purchased an Arduino Nano, a RTC module and a mini OLED display. I would like to kindly ask you for help in putting the system together: programming the Arduino and connecting the module together. The RTC module should open the possibility to completely automate the system (turn power on and off between precise times) and the OLED Display should give the feedback of the current settings.
The RTC and OLED modules are just "nice to have", my main goal would be to have an automatic cutting of of the power after a certain time (i.E. 60 min.) after initialization of the system (through a push button, for example).
Thank you in advance for your advices!

it is much simpler to do a countdown timer then a scheduler with RTC.

Welcome to Arduino SE. Please realize that this is not a free design house, homework-answering service or an on-line technical encyclopedia, copied out to you on demand. People will help you take the next step if your question shows that you've done as much as you possibly could on your own - which your post doesn't. Please revise your question showing your work and findings so far. Or delete the question if Internet searches give you your answer anyway.

As Juraj said, you don't need an RTC for this. You just have to:

turn the LED on
wait for 60 minutes
turn it off

And do this every time the user presses a push-button.
The code that does this is pretty trivial:
const uint8_t BUTTON_PIN = 2;
const uint8_t LED_PIN = 3;
const uint32_t MINUTE = 60000;
const uint32_t ON_TIME = 60 * MINUTE;

void setup() {
    pinMode(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED_PIN, OUTPUT);
}

void loop() {
    if (digitalRead(BUTTON_PIN) == LOW) {  // button pressed
        digitalWrite(LED_PIN, HIGH);       // LED on
        delay(ON_TIME);                    // wait
        digitalWrite(LED_PIN, LOW);        // LED off
    }
}

Now, you can build on top of that whatever “nice to have” functionality
you want.


text:
Why these specific voltage divider resisters needed for Arduino Uno RX TX pins?
I have an Arduino Uno attached to a Parallax Boe-Bot shield, and plugged into the shield breadboard, the Parallax WX ESP8266 Wi-Fi SIP.
When I attach the DO/DI pins of the ESP8266 board to the RX/TX pins of the Uno, it does not work without a very narrow range of resisters in a voltage divider configuration. I'm trying to learn more about electronics and I would like to know, why these specific values in this specific case?
The DI/DO pins of the SIP are documented as "SIP - output high (set by Vin voltage, either 3.3 or 5.0 V), low 0 V. Input high >Vin/2, input low

When I attach the Parallax shield 5V to the SIP Vin, and the DO to a 220 resister to RX, and also DO to a 1K resister to ground, and DI to 220 to TX and also DI to 1K to ground, serial communications works fine.
If I use the shield 3.3V to SIP Vin, it does not work.
If instead of 220 / 1K, I use 470 / 2K, or 4.7K / 10K, for example, it doesn't work.
If I only set up the voltage divider on the RX pin, it doesn't work.
However, if instead, with either 5V or 3.3V to the SIP Vin, and no resisters, I can run the Uno TX direct to the SIP DI, and the SIP DO to a digital pin, and run that digital pin with SoftwareSerial, for example.
I can run both DI and DO directly with SoftwareSerial, and either 5V or 3.3V to supply Vin.
It's only when I want to connect DO/DI direct to use the Uno's UART (because I don't want serial-driving interrupts to interfere with servo pulses) that I have to carefully select these resisters (through trial and error) and be sure to power with the 5V. Some combinations get communication with errors, but just these specific values (out of the resisters I happen to have on hand) work.
I understand that it is something to do with 3.3V vs TTL serial, but I would like the details. (I will be picking up a logic level converter to try in place of the voltage divider.)
EDIT:
By "not working" -- in all but two cases, with fresh batteries, the SIP seems to get data from the Uno TX, and the DO lamp on the SIP flashes, but Serial.read() sees nothing on the Uno regardless of configured rates. In one of the two cases (I can't recall which) unintelligible, incomplete data is read on the RX pin, and in the last, good case -- where both pins have voltage dividers and the SIP is powered by the 5V line of the Arduino shield (for the Boe-bot) -- with those specific resister values -- the data from the SIP DO is received on the Serial, from pin RX.

A schematic would be in order here. Your question is a bit vague with a few alternative configurations and voltages. Please post a specific configuration that is causing you problems.

I'll add some diagrams.

The output of a voltage divider is:
Vout = Vin * R2 / (R1 + R2)
Where R2 is the resistor in your case which is connected to ground.
See: Sparkfun - voltage dividers
Now in your example of 220 / 1k you have a multiplier of:
Vout = Vin * 1000 /1220 = Vin * 0.82

If both boards are running at 5V you don't need the voltage divider at all, but if you do use it the output would be:
Vout = 5 * 0.82 = 4.1

Now the Atmega328P chip on the Uno has the electrical characteristics defined in the datasheet, amongst others is that a digital pin high has to have a minimum of 0.6 * Vcc (if Vcc is in the range 2.4V to 5.5V)
So if Vcc is 5V (which it is on the Uno) you have to have 0.6 * 5 (that is, 3V) as the minimum for it to be recognised as high.
So, using the voltage divider of 220/1k you have a high still being 4.1V which is in the range 3 to 5V.
However if you have the board set to 3.3V then the output of the voltage divider will be 3.3 * 0.82 = 2.76V which is too low to be recognized as high.
For sending serial from a 3.3V board to a 5V board, simply omit the voltage divider, and then the 3.3V (for high) is in range (it has to be 3+ volts).
However for sending from a 5V board to a 3.3V board you do need a voltage divider (or level shifter) because 5V is too much for a 3.3V board. You can use a voltage divider calculator to simplify the maths.
Something like 1k/1.8k would be about right.
Vout = 5 * 1800 / 2800 = 3.21

According to the documentation for the Parallax WX ESP8266 Wi-Fi Module:

(9) Level shifters and buffers
To ensure maximum compatibility with a wide range of 3.3V and 5V microcontrollers and development boards, the Parallax Wi-Fi module includes voltage level shifters and buffers to ensure that the logic voltage levels at the SIP header are set by the VIN voltage level. If you
  supply 3.3V to VIN, then the IO pins logic voltage level will be 3.3V. If you supply 5V to VIN, then the IO pins logic voltage level will be 5V

I don't see why you need to use a voltage divider or level shifter in the first place.

References

Atmega328P datasheet (32.9 MB)
Sparkfun - voltage dividers
Voltage divider calculator
Another voltage divider calculator
Voltage dividers - Wikipedia

That is what I read elsewhere, but that is not how this hardware combination behaves. Of the combinations I listed, only 220 / 1K works, and only if both are connected (only one divider from DO to RX will not work). 470 / 2K gives 4V and does not work. There must be some other consideration for pins 0 and 1 on the Uno, which happen to be wired to the internal UART. I will pick up a 1.8k resistor and try that, though.

If you look at the Uno reference schematic there is a 1k resistor in series with both D0 and D1 and the UART. However I don't quite see how that would alter your results.

Can you clarify what "does not work"? Sending from the SIP to the Uno? Vice-versa? At what operating voltages?

Also see amended answer regarding the level shifting requirements.

I didn't see that level shifters / buffers note -- thx. By "does not work", the SIP DO/DI LEDs flash, and it appears to get a command, but the Uno does not read any response on Serial. SoftwareSerial reads it fine on another pin. In one case of resisters (I'll have to double check which) Serial gets a read error, but in other cases, nothing is detected.


text:
Adafruit 128x64 OLED not turning on
I ordered a 128x64 pixel OLED display from Adafruit and wired it according to their guide. (To an Arduino Uno) I'm using SPI right now and the display will not turn on or do anything. I haven't tried i2C, but I don't think that should make a difference. Maybe I will if nothing else works. I've installed the two libraries from the guide and am running the SPI 128x64 example. I've tried to find people with this same issue but I haven't found that much about it. Any help would be greatly appreciated!
Edit: Added pictures. I've used header pins in the past in case anyone is wondering if the connection using these wires isn't good, but the pins did not work either, so it's not a bad connection.

There isn't exactly a question here that has a definite answer. A clear photograph of your setup would help. Please state the exact part number you are using, also the exact sketch that you are testing it with.

The sketch is an example from the SSD1306 library called "ssd1306_128x64_spi". I will add a picture soon.

I don't see any soldering in those pictures. You can't just poke wires into holes and hope they'll work. That will be your problem.

and wired it according to their guide - No you didn't. See the this - you didn't solder the pins to the board.

I understand that, but I've done this with a few different sensors in the past and as long as the wires are touching the metal holes there is a connection. I also have set it up exactly how they showed it in the guide just without soldering it.

When I move the OLED around a little bit the "L" light on the Arduino flashes and I get a notice on my computer saying that a USB device is using too much power. That usually happens when something gets shorted, and I'm not sure why that would be happening here.

The green and yellow wires on the right look very close. I suggest you install it properly, soldering the wires in and not having large amounts of bare wire which are almost touching. Or at least solder on a header strip as shown in the article. The whole point of using a breadboard is that those pins stick into it.

These devices are selectable to use SPI or I2C by means of a soldered-in jumper on the back. You can use either but your jumper selection must match. Does yours?

Wiring is your problem. Use soldering iron/solder and flux. Solder your wires. Intermittent connections and accidental shortages with current setup may damage your Arduino and display (and possible your PC/laptop).

I know this issue and understand it well.
If the module is genuine from Adafruit then it should definitely work, if not then once try this library https://github.com/olikraus/U8glib_Arduino
This library has very good documentation. Further if it does not work, attach the picture of wiring.

Its not every time fault of hardware, check the program as well. Load example test program and try again.
https://iotforgeeks.com/i2c-oled-display-not-working/
helped me to resolve the same issue.


text:
Locking ATmega328 from reading back the hex file
I want to completely block the access to an ATmega328. How do I do this?
I have Atmel ICE, AVR studio 7 and Arduino.
Bootloader - optiboot_atmega328
Fuses(without lock) - 0x05, 0xDE, 0xFF
Steps I am executing:

Program fresh ATmega328 with bootloader using Atmel Studio.
Burn the fuses as mentioned above.
Go to Arduino and program the code.
Come back to Atmel Studio >> lock bits >> enable no further programming and verification.>> Fuse bits>> disable reset.

Is the above way OK? Or should I add something to the above?
I have programmed the fuse bit with "Further programming and verification disabled". I read out the hex file and it does not match even I programmed the same hex into a different micro and it didn't work. This seems to be fine. But will high Voltage programmer brick this wall?
Note: When I program the above fuse bit. I am unable to disable the RESET or SPI. It says one or more register differ
I want avoid a readback via high voltage programmer too.
I have too many people to steal my code I want to avoid it. Kindly help
Siddharth

Why don't you want to disable SPI?

Locking out programming prevents writing, and locking out verification prevents reading, via all programming methods.
Note that there is no way to prevent erasing the chip, which will clear both the lock bits and the flash.

This is not an answer. But a reply to the abive post. So Further programming and verification disabled.
Will this option do the job??? Siddharth

That will prevent writing to and reading from the flash memory, just as it says in the datasheet.

"Locking" the chip only has any effect when using one of the hardware programming interfaces. Yes, it prevents anyone with a programmer from reading the data from the chip (verify disabled).
However, it does not stop software on the chip itself from reading the contents of the chip. And that includes the bootloader.
Since you use a bootloader it is possible (if implemented in your bootloader, I am not familiar with what is implemented in Optiboot) to use the bootloader to read the contents of the chip through USB.
To properly protect your software you will have to either remove the bootloader and only program through a hardware programmer or ensure that the bootloader has no method to read or otherwise access the flash memory of the chip (intentional or otherwise).


text:
Stop Buzzer after some seconds/time?
This is a "water level alarm/display" sketch using and Arduino and ultrasonic sensor.
The buzzer gets on when the water level hits 100% or more.
But most of the time the water level will stay @ 100%, and I dont want the buzzer to run for long time.
How can I set the buzzer to make sound only for 15 seconds ?
It should turn off after 15 seconds, even if the water level is @ 100%
#define trigPin 8
#define echoPin 9
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int BUZZER = 10 ;

void setup(){
      int duration,distance,percentage,heightTank;
      Serial.begin (9600);
      pinMode(trigPin,OUTPUT);
      pinMode(echoPin,INPUT);
      lcd.begin(16,2);
      lcd.print("HELLO");
        pinMode(BUZZER,OUTPUT);
}

void loop(){
      int duration,distance,percentage,heightTank,deviation;
      //You'll probably want to change the next 2 lines.
      // The first one is the max. level of the water.
      // The next one is how high the sensor is above that max. level.
      heightTank=65;
      deviation=4;

      digitalWrite(trigPin,HIGH);
      delayMicroseconds(1000);
      digitalWrite(trigPin,LOW);
      duration=pulseIn(echoPin,HIGH);
      distance=(duration/2)/29.1;
      percentage=100-(((distance-deviation)*100)/heightTank);
      Serial.println(distance);
      Serial.println(percentage);
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Current tank");
      //lcd.print(distance);
      //lcd.print(" cm");
      lcd.setCursor(0,1);
      lcd.print("level: ");
      lcd.print(percentage);
      lcd.print(" %");
      delay(1000);

      digitalWrite(BUZZER,HIGH);
  if (percentage > 99) {digitalWrite(BUZZER,HIGH); delay(100); digitalWrite(BUZZER,LOW); delay(100);}
  else  {digitalWrite(BUZZER,LOW);}
  }

Try this at the end of loop
static unsigned long lastBuzzer = 0;

if(percentage > 99 && lastBuzzer == 0) {
    lastBuzzer = millis();
}

if(percentage > 99) {
    if(millis() - lastBuzzer < 15000L) {
        digitalWrite(BUZZER,HIGH);
        delay(100);
        digitalWrite(BUZZER,LOW);
        delay(100);
    }
} else  {
    digitalWrite(BUZZER,LOW);
    lastBuzzer = 0;
}

lastBuzzer is the last buzzer activation time (in ms). It's use to control that buzzing stop after 15 seconds. It's zero when the percentage is < 99; it's not zero when percentage >= 100.
(Not tested).
(Two if's instead of one for clarity).

May be nitpicking but... 0 is a perfectly valid return value for millis(), once every 49.7 days.

@EdgarBonet. True, but I can't see how it affects operation. If millis is zero in lastBuzzer = millis();, then millis() - lastBuzzer (both unsigned long) still will be < 15000L.

For this you will have to implement a finite state machine. This is a
very common paradigm in the embedded world. I recommend you start by
studying this tutorial: The Finite State Machine, by Majenko.
Four your particular problem, I would implement a machine with three
states: IDLE, ARMED and ALARM, the ALARM state being the only one in
which the buzzer is on. The transitions would be:

ARMED → ALARM when the level hits 100%
ALARM → IDLE after 15 seconds spent in the ALARM state
IDLE → ARMED when the level gets below 90%

Note that the only difference between IDLE and ARMED is that the IDLE
state will not go into ALARM when the level reads 100%, as you have to
go through the ARMED state before. The threshold at 90% percent is meant
to add some hysteresis. You can tweak the threshold value to your
taste.
I leave the implementation to you. It should be easy one you have
studied Majenko's tutorial.

Edit: Just to illustrate the generality of the concept, I would like
to point out that the code in Look Alterno's answer can be thought of as
a finite state machine where the state is implicitly encoded into the
variables lastBuzzer and percentage. The implicit state is:

ARMED when lastBuzzer == 0
ALARM when percentage > 99 && millis() - lastBuzzer < 15000L
IDLE when  percentage > 99 && millis() - lastBuzzer >= 15000L

The line lastBuzzer = 0 establishes the ARMED state as soon as
percentage ≤ 99. Note that this lacks hysteresis: if the reading
fluctuates between 99% and 100%, the alarm will sound again and again.
I personally prefer using an explicit state variable, as it makes the
code clearer to me. But then, the best approach is whichever makes the
code clearer to you.


text:
Checksum is wrong - Air Quality Monitoring Station PMS5003, BME280 | Code review
I working at air quality station. I measure particulate matter with PMS5003 and meteorological parameters with BME280. Everything seems to work just fine, but sometimes program hangs on checksum calculations.

I wonder if the problem lies either in my software or in hardware. Can anyone have a look at my code and tell me how I can improve it. Thanks in advance :)
Here's my code:

#include <Arduino.h>
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

// needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
#include <PubSubClient.h>
#include <Wire.h>
#include <SPI.h>

// BME280 Sensor
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

//Constants
#define TOKEN "TOKEN"
char thingsboardServer[] = "SERVER_ADDRESS";

// Settings for PMS5003
#define LENG 31  //0x42 + 31 bytes equal to 32 bytes
#define TIMEOUT 10000 //Microseconds to wait for PMS do wakeup

unsigned char buf[LENG];
char ergebnisstr[50];

struct dustvalues {
 unsigned int PM10Val=0; // Byte 4&5
 unsigned int PM2_5Val=0; // Byte 6&7
 unsigned int PM01Val=0; // Byte 8&9
 unsigned int Beyond03=0; // Byte 16&17
 unsigned int Beyond05=0; // Byte 18&19
 unsigned int Beyond1=0; // Byte 20&21
 unsigned int Beyond2_5=0; // Byte 22&23
 unsigned int Beyond5=0; //Byte 24&25
 unsigned int Beyond10=0; //Byte 26&27
};

struct dustvalues dustvalues1, dustvalues2;

//unsigned char gopassive[]={ 0x42, 0x4d, 0xe1, 0x00, 0x00, 0x01, 0x70 }; //don't need here
//unsigned char readinpassive[]={ 0x42, 0x4d, 0xe2, 0x00, 0x00, 0x01, 0x71 };
unsigned char gosleep[]={ 0x42, 0x4d, 0xe4, 0x00, 0x00, 0x01, 0x73 };
unsigned char gowakeup[]={ 0x42, 0x4d, 0xe4, 0x00, 0x01, 0x01, 0x74 };

// BME280 init
Adafruit_BME280 bme;

// Connection to PubSubClient
WiFiClient espClient;
PubSubClient client(espClient);

int status = WL_IDLE_STATUS;
unsigned long lastSend;

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

    wifiManager.autoConnect("AP", "pass");
    Serial.println("Connected to the network :)");
    delay(500);
    //  pins for RGB diode
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);
    pinMode(14, OUTPUT);
    //BME280 sensor check
    if (! bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
    }
    // set server for MQTT PubSubClient Library
    client.setServer( thingsboardServer, 1883 );
    lastSend = 0;

}

void loop() {

    if (!client.connected()) {
    reconnect();
    }
    if ( millis() - lastSend > 30000 ) { // Update and send only after 1 seconds
    getpms5003();
    getAndSendTemperatureAndHumidityData();
    lastSend = millis();
    }
    client.loop();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Connecting to ThingsBoard node ...");
    // Attempt to connect (clientId, username, password)
    if ( client.connect("Stacja3", TOKEN, NULL) ) {
      Serial.println( "[DONE]" );
    } else {
      Serial.print( "[FAILED] [ rc = " );
      Serial.print( client.state() );
      Serial.println( " : retrying in 5 seconds]" );
      // Wait 5 seconds before retrying
      delay( 5000 );
    }
  }
}

void getAndSendTemperatureAndHumidityData()
{
  Serial.println("Collecting temperature data.");

  // Reading temperature or humidity takes about 250 milliseconds!
  float humidity = bme.readHumidity();
  // Read temperature as Celsius (the default)
  float temperature = bme.readTemperature();

  float pressure = bme.readPressure() / 100.0;

  // Check if any reads failed and exit early (to try again).
  if (isnan(humidity) || isnan(temperature) || isnan(pressure)) {
    Serial.println("Failed to read from BME sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print(" *C ");
  Serial.print("Pressure: ");
  Serial.print(pressure);
  Serial.print("hPa");

  String temperature1 = String(temperature);
  String humidity1 = String(humidity);
  String pressure1 = String(pressure);

  // Just debug messages
  Serial.print( "Sending temperature, humidity & pressure : [" );
  Serial.print( temperature1 ); Serial.print( "," );
  Serial.print( humidity1 ); Serial.print( "," );
  Serial.print( pressure1 );
  Serial.print( "]   -> " );

  // Prepare a JSON payload string
  String payload = "{";
  payload += "\"temperature\":"; payload += temperature1; payload += ",";
  payload += "\"humidity\":"; payload += humidity1;  payload += ",";
  payload += "\"pressure\":"; payload += pressure1;
  payload += "}";

  // Send payload
  char attributes[150];
  payload.toCharArray( attributes, 100 );
  client.publish( "v1/devices/me/telemetry", attributes );
  Serial.println( attributes );
}

bool checkValue(byte *buf, byte leng){
    int receiveSum, checkSum;
    for(byte i = 0; i < (leng - 2); i++){
        receiveSum += int(buf[i]);
    }
    receiveSum += 0x42;
    checkSum = (buf[leng-2] << 8) + buf[leng-1];
    testCheckValue(receiveSum, checkSum);
    if(receiveSum == checkSum){
        return true;
    }
    return false;
}

void testCheckValue(int calc, int found){
    byte strSize = 64;
    char strOut[strSize];
    snprintf(strOut, strSize, "Checksum Calculated: %d\nChecksum Found: %d\n", calc, found);
    Serial.print(strOut);
}

unsigned int transmitPM(char HighB, char LowB, unsigned char *buf){
 unsigned int PMValue;
 PMValue=((buf[HighB]<<8)+buf[LowB]);
 return PMValue;
}

void getpms5003(void){
  unsigned char found=0;

  Serial.println("PMS5003 Wakeup: ");
  Serial.write(gowakeup,7);
  Serial.println();
  Serial.println("gowakeup ist out");
  delay(30000); //Stable data should be got at least 30 Second from wakeup (Datasheet!)
  while (found<2){
   delay(TIMEOUT);
   if(Serial.available()>0){
    if(Serial.find(0x42)){  //start to read when detect 0x42
     Serial.println("0x42 found");
     Serial.readBytes(buf,LENG);
     if (buf[0] == 0x4d){ //second byte should be 0x4D
       found++;
       if(checkValue(buf,LENG)){
        Serial.println("Checksum okay");

        if(found==1){
         dustvalues1.PM01Val=transmitPM(3,4,buf);
         dustvalues1.PM2_5Val=transmitPM(5,6,buf);
         dustvalues1.PM10Val=transmitPM(7,8,buf);

         if (dustvalues1.PM2_5Val <= 36) {
           // digtal write green pin
           digitalWrite(12, LOW);
           // digitalWrite(13, HIGH);
           digitalWrite(14, HIGH);
         }

         if ((dustvalues1.PM2_5Val > 36 ) && (dustvalues1.PM2_5Val <= 80)) {
           // diode change to yellow
           digitalWrite(12, LOW);
           // digitalWrite(13, HIGH);
           digitalWrite(14, LOW);
         }

         if(dustvalues1.PM2_5Val > 84) {
           // diode change to red
           digitalWrite(12, HIGH);
           // digitalWrite(13, HIGH);
           digitalWrite(14, LOW);
         }

         sprintf(ergebnisstr,"PM2.5:%4dug/m3\nPM10: %4dug/m3\n",dustvalues1.PM2_5Val,dustvalues1.PM10Val);
         Serial.println(ergebnisstr);
         Serial.flush();

         // Just debug messages
         Serial.print( "Sending air quality PM2.5 & PM10 values: [" );
         Serial.print( dustvalues1.PM2_5Val ); Serial.print( "," );
         Serial.print( dustvalues1.PM10Val);
         Serial.print( "]   -> " );

         // Prepare a JSON payload string
         String payload = "{";
         payload += "\"pm25\":"; payload += String(dustvalues1.PM2_5Val); payload += ",";
         payload += "\"pm10\":"; payload += String(dustvalues1.PM10Val);
         payload += "}";

         // Send payload
         char attributes[100];
         payload.toCharArray( attributes, 100 );
         client.publish( "v1/devices/me/telemetry", attributes );
         Serial.println( attributes );
       }
        if(found==2){
         dustvalues2.PM01Val=transmitPM(3,4,buf);
         dustvalues2.PM2_5Val=transmitPM(5,6,buf);
         dustvalues2.PM10Val=transmitPM(7,8,buf);
         sprintf(ergebnisstr,"PM1: %4dug/m3\nPM2.5:%4dug/m3\nPM10: %4dug/m3\n",dustvalues2.PM01Val,dustvalues2.PM2_5Val,dustvalues2.PM10Val);
         Serial.println(ergebnisstr);
         Serial.flush();
        }
      }else{
       Serial.println("Checksum not okay");
       Serial.flush();
       if(found>0)found--;
       delay(500);
      }
     }
   }
   }
   }

  found=0;
  Serial.println("PMS5003 - go to sleep");
  Serial.write(gosleep,7);
  Serial.println();
 }

My hardware:

PMS 5003 Datasheet - http://www.aqmd.gov/docs/default-source/aq-spec/resources-page/plantower-pms5003-manual_v2-3.pdf

Is the checksum function expecting to be run on an 8-bit CPU with only 16-bit integers? You have a 32-bit one there...

Cited from the documentation

Check code=Start character1+ Start character2+……..+data13 Low 8 bits

Please try to change the code as follows:
...
bool checkValue(byte *buf, byte leng){
    int receiveSum, checkSum;
    receiveSum += 0x42;
    for(byte i = 0; i < (leng - 2); i++){
        receiveSum += int(buf[i]);
        receiveSum = receiveSum & 0xFFFF;
    }

    checkSum = (buf[leng-2] << 8) + buf[leng-1];
    testCheckValue(receiveSum, checkSum);
    if(receiveSum == checkSum){
        return true;
    }
    return false;
}
...

Or use the updated code by the same author :PMS7003-on-Particle


text:
Will a genuine Arduino board have the same issues with High Sierra as other non genuine ones?
I think my question is quite specific to High Sierra. I am very new and have bought a starter Elegoo kit to learn the basics. I did not realise that their boards are not the real thing.
I have an iMac running High Sierra and although the Mac recognises the board (I checked this through the apple menu) every time i try to upload code i get the error message:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
I have watched several videos on line that have taken me through installing drivers including one specific to High Sierra. However the problem continues.
Does anyone know if i buy a genuine Arduino board, will i have the issues? Will Arduino just not work with High Sierra.
Any help or advice would be so appreciated by someone very new and trying to learn!
Thank you
Paddy

Does the board use the CH340G USB chip?

By looking. Read the chip numbers.

The one that isn't the ATMega328p.

This is a Mega2560 R3. Sorry am probably seeming very stupid, i do appreciate your help, im just not sure what im looking for

In that case it's the one that isn't the ATMega2560.

The only sequence of numbers i can see written on it is CS4725V

Do you even know what a chip is? You're looking at capacitors there. Chips. They're black, either square or rectangular, sometimes with metal pins sticking out the sides.

If it's the same as the image I am looking at it should be an ATMega16U2. If it is, and it's been programmed correctly, then it should be no different to a genuine one.

Im so sorry no i did not, but now that you explain i can see the big chip is ATMEGA2560 and then a smaller one Mega16U2 1734. Thank you

Ah i see i have just seen your previous comment, it seems it is the same chip. Maybe they will just not work with High Sierra?

The 1734 is the date code from when the chip was made. It's quite new - August 21-27 2017. So it should function the same as a genuine Arduino. If it's all been programmed right.

Does anything work with High Sierra? With all the bad press it's been getting recently I am surprised they haven't pulled it ;)

Ah okay, brilliant thank you that is great to know. In your opinion would it be worth sending it back for a new one or maybe there are just too many problems working on Mac and High Sierra?

Your very right about High Sierra!! :)

I would suggest getting hold of a genuine Arduino and trying it (maybe borrow one from someone else). If it works and yours doesn't there's an issue with yours. If neither work then there's an issue with (maybe only your installation of) OS X.

I will do that, thank you so much. I will get a new one anyway as maybe i have to find an old PC to work on. Could i ask you for some quick advice about learning? I really struggle with the Elegoo instructions, they are badly translated and so for a novice it is very confusing. Is there another platform you would recommend at all?

You need to learn two separate spheres of knowledge - electronics and programming. Start by learning about simple circuits and how electronics function - separate to Arduino. Then learn basic programming techniques (again not necessarily related to Arduino) and then fit the two together.

Okay thank you, i so appreciate your help! :)

From reading both your questions, I'm not sure whether you've gotten your board to upload yet.
But here's another data point: I just tried an Arduino Mega r2 and iMac with High Sierra - worked perfectly, first try. Arduino IDE 1.6.12.
In your other question, you said you were getting a solid green LED and a blinking yellow one. The green LED is the power LED. The yellow one is programmable so it sounds like the Blink sketch is already loaded and running.
If you're still getting upload errors, check the Arduino IDE Tools menu and check you hardware selections in the Arduino IDE Tools menu. Here are mine; your /dev/cu.usbmodemxxx number might be different but there should only be one of those if you only have one Arduino plugged in:

that was it, i think it is probably my fault for religiously following the instructions sent me by Elegoo that told me to select the Arduino Genuino and i did not see the option to select the board as Mega 2560! I guess you live and learn... thank you so much for your advice. I feel a bit stupid no that it was such a simple solution! Thank you again

As long as the firmware on the ATMega16U2 chip is the same as on a Genuine Arduino and the bootloader on the ATMega2560 chip is the same as on a Genuine Arduino then your boards should function exactly the same as a Genuine Arduino.
If you find a Genuine Arduino works but your boards don't then there must be a difference, and that can really only be in the software on the chips - so reprogramming the chips to match a Genuine Arduino would probably help.
I haven't heard reports of High Sierra not working with Genuine Arduino boards, but given the severity of some of the bugs that have crept in recently, it seems likely that more problems are hidden away under the hood that no one really knows about yet.

I use High Sierra on my ageing 2011 MacBook and it works with reputable Arduino clones (it is difficult to get a genuine Arduino in Australia, although compatible Freetronics boards are available from a major retailer).
There were some problems with ARDUINO 1.8.4 but the latest works flawlessly.
Anything with a CH340G chip is out, but then the CH340G don't seem to last anyway.

thank you. I realised i was being very stupid and had not selected the right board. I feel and idiot but hopefully have learnt not to follow instructions too carefully in future. Thank you so much for you help


text:
Arduino Servo with Serial
I have an interesting problem. I want to control ESC and servo with Arduino. I'm using HC-12 to communicate with 2 Arduino and I'm using SoftwareSerial on the nano.

#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial mySerial(2, 3); // RX, TX
Servo esc,servo1;

String okunan;
int escval;

void setup() {
  okunan="";
  esc.attach(9);
  servo1.attach(10);
  mySerial.begin(2400);
  Serial.begin(9600);
}

void loop() {
   while (mySerial.available()) {
    delay(3);  //delay to allow buffer to fill
      char c = mySerial.read();  //gets one byte from serial buffer
      okunan += c; //makes the string readString
   }

  if(okunan.length()>0)
  {
    Serial.println(okunan);
    //escval= map(okunan.substring(0,okunan.indexOf(',')).toInt(),0,1023,,2000);

    servo1.writeMicroseconds(map(okunan.toInt(),0,179,1000,2000));

    okunan="";

mySerial.flush();
  }
  delay(20);
  }

When I use a potentiometer, It works successfully. But When I use with serial and if three digit value(between 0-179, for example, 120) comes from serial(HC-12), motor works and stops continuous and irregular. If the value is under three digit there is no problem.
Also, if I delete the ESC variable(servo) or add a new servo to code, it always starts and stops interestingly(Using or not it doesn't matter. If I add Servo servo2 etc., it is going crazy.
I've tried on Uno. That is the same.
Thanks in advance...

Did you look at the source code for SoftwareSerial and Servo? What does SoftwareSerial do when it detects a start bit? Receives the character in the ISR. And how does that affect Servo? It blocks the Servo ISR and delays pulse generation.

Like Mikael Patel said, SoftwareSerial disables interrupts for the entire character receive time.  Bad juju.
This answer lists the alternatives:

HardwareSerial is always the best.  Simply connect the device to pins 0 & 1 and use the pre-defined Serial variable.  On some Arduinos, there are extra HardwareSerial ports, called Serial1, Serial2, etc.  The UNO only has Serial.  Serial would not interfere with the Servo.
AltSoftSerial is the best of the software serial libraries.  Only one instance is allowed, and it is must be used on the Input Capture pins (pins 8 & 9 for a Nano).  It would not interfere with the Servo.
My NeoSWSerial is next best.  It works on any two pins, but only at baud rates 9600, 19200 and 38400.  Receiving characters does not disable interrupts, but transmitting does (i.e., TX would interfere with the Servo).
SoftwareSerial is the worst choice.  It works on any two pins, but it is very inefficient.  It disables interrupts for the entire time that a character is being sent OR received, and it cannot transmit and receive at the same time (unlike all other choices).  This can interfere with other parts of your sketch, other device communications, or with libraries (e.g., Servo).

In your case, I would suggest connecting the HC-12 to pins 0/1 and use Serial.  No software serial library required, but you will have to disconnect pin 0 to upload new sketches over USB.  Some people put a switch in that wire so it's easy to upload a new sketch.
If you need debug prints, I would suggest using AltSoftSerial and an extra TTL Serial-to-USB adapter (aka FTDI module) to your PC.  Then print your debug messages to the AltSoftSerial variable:
#include <AltSoftSerial.h>
AltSoftSerial debugPort; // always pins 8 & 9

   ...

void loop()
{
  if (something) {
    debugPort.println( F("something happened!") );

Or, if the HC-12 connection is receive only, don't connect pin 1 (TX).  Then your debug prints won't go to the HC-12.
BTW, don't use delay and don't use String.  They will get you into trouble sooner or later.

Thank you very much. Can I hardware serial on nano or uno? Do I have to eject USB?

Yes, you can use HardwareSerial (0 & 1) on a Nano or UNO.  You only have to disconnect pin 0 from the HC-12 when you upload a new sketch over USB.  You do not have to disconnect the USB cable when running the sketch (reconnect pin 0 after the upload completes).