How to get readings on serial monitor in every 10s? I am doing my final year project and here I am attaching the code I am using. According to the code, I will get the sensor output in serial monitor. But I want to get reading once n 10ms. Since serial monitor can't work with that resolution, I need to save the reading in an array and then output the array in serial monitor or any other way. Please help me in modifying the code.

The code is as follows:

/*
   The circuit:
  * VCC connection of the sensor attached to +5V
  * GND connection of the sensor attached to ground
  * TRIG connection of the sensor attached to digital pin 2
  * ECHO connection of the sensor attached to digital pin 4
 */

const int trigPin = 2;
const int echoPin = 4;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop()
{
  long duration, cm;

  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  cm = microsecondsToCentimeters(duration);

  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(100);
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

There is one fundamental error with your code that I feel I should point out - one that I see time and time again.

The basic structure of your code is:

Forever:

Send a ping
Wait for the pong
Print the result
Delay for 100ms (or whatever time you choose)

And you expect to get a result every (delay) milliseconds.

However, you won't.  What you will actually get is a result every so often, where that time is defined as 100ms + the time to send and receive a ping.

So if it takes 11.6ms (200cm, the limit of most pin sensors) to receive the pong, then you also delay for 100ms, you're going to end up with 111.6ms between each print. It's even worse if the pong never arrives back - then pulseIn() will wait for up to a second before returning. You can, of course, reduce that to say 15ms by adding the timeout parameter as per the manual

When you reduce your printing delay to just 10ms you actually run the risk of delaying for more than double the time you expect to (21.6ms instead of 10ms).

Instead you need to use millis() to check to see if it is time to print something so that it doesn't matter how long the pong took to arrive, as long as that never exceeds the amount of time you want between prints, otherwise it's going to get delayed regardless.


Adding an LCD to Uno but not enough pins left I am an absolute beginner and wanted to build a simple home automation system using DTMF module using this guide. My problem is out of 12 pins most of them are getting used in DTMF module(5) and the relay module(4). So how do i add an LCD display to it?

You are using 8 GPIO pins for your existing modules. That leaves 12 left for an LCD (assuming you aren't using the serial port).

An LCD can work from as few as 6 pins (4 data, E and RS) - WR can be tied LOW and RESET can be tied HIGH, and the remaining 4 data pins left floating (or tied low).

That still leaves you 6 pins to do other things. Or 4 if you (advisedly) steer clear of using pins 0/1 for anything.


What is the function of the XBee / USB switch on an XBee shield? I recently bought an XBee shield (this). The shield has a switch that seems to switch between USB/XBee. However, there is no USB port. What exactly is the switch supposed to do?

In case someone does ask the same question in the future, this is the explanation for the USB/XBee switch functionality on the XBee Pro Shield V3
The switch serves to connect/disconnect the XBee Pro shield v3 to the Hardware TX->1 & RX<-0 Lines of the Arduino. Moving the switch to the USB side, allows you to disconnect the XBee Pro shield v3 from the hardware serial lines and upload code to your Arduino. If the switch is on the XBee side, this allows your XBee Pro shield v3 to use the TX->1 and RX<-0 lines of the Arduino and if you want to upload code to your Arduino, you would have to remove the shield otherwise it would result in an error trying to upload code.


LCD Lifespans Constantly Running I am creating an arduino alarm clock/light sculpture, but I can't for the life of me find any information about the lifespans of LCDs that are running 24/7 for a very long time. If anyone has any information on them, please tell me. Specifically, I am using this one.

The lifespan of the LCD and the electronics is just like any electronics part. When it is bad quality it will last a few years, when it is good quality it is more than 10 years.

A LCD watch from the 1970s might still work today. That is a few decades.

The backlight might get dim. That depends on the quality of the led and how bright it is set. The cheapest leds have only 50% brightness left after a few months. I suppose they didn't put the cheapest led in that display. I expect it to be okay for many years. Don't set it to the highest brightness. A resistor for the backlight of 220 Ω is common, you could start with 470 Ω and see if that is bright enough.

I see sometimes that the backlight display is directly connected to 5V, without resistor. If you have done that, then you have reduced its lifespan.

There are a few weak parts: The potentiometer for the contrast, the large capacitors on the Arduino board (if there are any), and the power supply.

If the display is more or less at the same room temperature, you could replace the potentiometer with a single resistor of 100Ω to 10kΩ from the LCD contrast pin to GND.


Set Bluno Beetle to Broadcast mode I recently purchased Bluno Beetle (basically a smaller Arduino with a BLE chip). It is based on the Bluno: Wiki I know that its Bluetooth Chip, the TI CC2540, supports the Broadcast mode: Official page

However I can't find any AT commands that would allow me to set it to this mode, does anyone of you have an idea? I am trying to relay the messages they are sending (sensor readings), essentially building an interconnected network.

It looks like the Bluno only supports the Central and Peripheral roles (i.e. not the Broadcaster and Observer roles.) Keep in mind AT commands are a feature of the firmware, not the actual chip. As such, even if the chip supports a particular mode or role, that doesn't necessarily mean the firmware makes the feature available.


Help choosing an ESC for a 500W/60V motor I have a 3 phase (3 wires) unicycle motor - 500W, 60V and a battery 50 - 60V (if I understand correctly - 16 cells x 3.7 V), 2.9 Ah.

I want to control this motor with Arduino PWM pin.

I understand, that I need an ESC to do that, but with what kind of specs? How can I know what voltage and amps should I look for? Maybe someone could explain this to me and also give some URL's to real ESC's.

Thanks.

I would suggest you study Brushless 3 phase DC motors.  It would take a book to explain how to do it.  You will be creating three separate synchronized phases 120 degrees out of phase.  That is not easy to do.

Try this link for a start: https://www.youtube.com/watch?v=E3BS8CO9APA
This is also good: https://www.youtube.com/watch?v=WyQInXjpGwU  Sorry I did not find part 1.

After you get through these and a few others you find I am almost certain you will pick another controller if you do the project.

Good Luck,
Gil


Why Are My High and Low Values Not Updating Correctly During Successive Loops I am attempting to capture the high and low temperature and humidity values, then clearing the LCD and displaying them on 2 successive screen updates. All is working correctly except that the variables for high and low are updating on every loop to the current sensor pin read after the "if" statements are run. Why is this occurring?
Also note that I declare the floats for the highs and lows to the unlikely value of 10000 in order to change them all to the initial pin read on the 1st loop as I didn't find a method to determine null on the initial loop.  I would appreciate any suggestions for a better method!  TIA
    #include <dht.h>
    #include <LiquidCrystal.h>

    //Low and High Temp and Humidity Variables
    float lTemp=10000;
    float hTemp=10000;
    float lHumid=10000;
    float hHumid=10000;

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    dht DHT;

    #define DHT11_PIN 7

    void setup(){
      lcd.begin(16, 2);
      Serial.begin(9600);
    }

    void loop(){
       lcd.clear();

      int chk = DHT.read11(DHT11_PIN);

      float CurrTemp = DHT.temperature * 1.8 + 32;  //Converts celsius read from DHT read to farenheit

    //Sets High and Low Temperature Readings

       if (lTemp = 10000) {
         lTemp = CurrTemp;
       }
      if (CurrTemp < lTemp) {
         lTemp = CurrTemp;
      }

      if (hTemp = 10000) {
        hTemp= CurrTemp;
      }
       if (CurrTemp > hTemp) {
        hTemp = CurrTemp;
      }

    //Sets High and Low Humidity Readings

      if (lHumid = 10000) {
        lHumid = DHT.humidity;
       }
      if (DHT.humidity < lHumid) {
        lHumid = DHT.humidity;
      }

      if (hHumid = 10000) {
        hHumid = DHT.humidity;
      }
      if (DHT.humidity > hHumid) {
        hHumid = DHT.humidity;
      }

      //Prints Current Temp and Humidity to LCD and Serial Monitor
      lcd.setCursor(0,0);
      lcd.print("Temp: ");
      lcd.print(CurrTemp,1);
      lcd.print((char)223);
      lcd.print("F");

      Serial.print(CurrTemp,1);

      Serial.println(" F");

      lcd.setCursor(0,1);

      lcd.print("Humidity: ");
      lcd.print(DHT.humidity,0);
      lcd.print("%");

      Serial.print("Humidity: ");
      Serial.print(DHT.humidity,0);
      Serial.println("%");
      Serial.println("");

      delay(10000);

      //Prints Low and High Temp to LCD and Serial Monitor
      lcd.clear();

      lcd.setCursor(0,0);
      lcd.print("L Temp: ");
      lcd.print(lTemp,1);
      lcd.print((char)223);
      lcd.print("F");

      Serial.print("Low Temp: ");
      Serial.print(lTemp,1);
      //Serial.print((char,223);
      Serial.println(" F");

      lcd.setCursor(0,1);

      lcd.print("H Temp: ");
      lcd.print(hTemp,1);
      lcd.print((char)223);
      lcd.print("F");

      Serial.print("High Temp: ");
      Serial.print(hTemp,1);
      Serial.println(" F");
      Serial.println("");

      delay(3000);

     //Prints Low and High Humidity to LCD and Serial Monitor
      lcd.clear();

      lcd.setCursor(0,0);
      lcd.print("Low Humid: ");
      lcd.print(lHumid,0);
      lcd.print("%");

      Serial.print("Low Humid: ");
      Serial.print(lHumid,0);
      Serial.println("%");

      lcd.setCursor(0,1);

      lcd.print("High Humid: ");
      lcd.print(hHumid,0);
      lcd.print("%");

      Serial.print("High Humid: ");
      Serial.print(hHumid,0);
      Serial.println("%");
      Serial.println("");

      delay(3000);

    }

Although you already have two perfectly valid answers, I will share a
trick that completely sidesteps the problem. Instead of choosing a
particular number (here, 10,000) as a “magic” value that has a special
meaning, you can instead initialize the highs and lows in a way that
ensures they will be updated on the very first iteration:

make lTemp higher than any temperature you may ever read
make hTemp lower than any temperature you may ever read

For example:
float lTemp = +INFINITY;
float hTemp = -INFINITY;

and the same of course for the humidities. This way the first iteration
does not need special handling anymore, as it becomes a regular
iteration:
if (CurrTemp < lTemp) lTemp = CurrTemp;
if (CurrTemp > hTemp) hTemp = CurrTemp;

Note that the choice of ±∞ for the min and max of an empty set of
readings is not just a dirty hack. It is actually consistent with the
mathematical notion of infimum and supremum of the empty
set.


Arduino DC motor with 2 buttons I have a problem with my Arduino project and I tried everything to fix it but nothing helps.

I am trying to rotate my DC motor with two buttons:

one button is to stop/start rotating on left side, and;
the second one is for stop/start rotating on the right side.

I can't switch the states and if the motor is rotating I can't stop it. The speed is controlled by the potentiometer and works fine, just the buttons are the problem. I hope somebody can help me.

int enablePin = 11;
int in1Pin = 10;
int in2Pin = 9;
int switchPin = 7;
int switchPin1 = 6;
int potPin = 0;
int statusPin= 13;
boolean status;

void setup()
{
  pinMode(in1Pin, OUTPUT);
  pinMode(in2Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);

  pinMode(switchPin, INPUT_PULLUP);
  pinMode(switchPin1, INPUT_PULLUP);

  pinMode(statusPin,OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(13,HIGH);

  int speed = analogRead(potPin) / 4;

  boolean reverse = digitalRead(switchPin);
  boolean reverse1 = digitalRead(switchPin1);

  if(reverse == false){
    status = true;
  }
  if(reverse1 == false){
    status == false;
  }

  setMotor(speed, status);
}

void setMotor(int speed, boolean reverse)
{
  analogWrite(enablePin, speed);

  digitalWrite(in1Pin, ! reverse);
  digitalWrite(in2Pin, reverse);
}

I just added the second button with paint, so don't get confused.

In your code the buttons only control the direction, but are not turning the motor on or off. This is only be done with the potentiometer, which can be set to zero speed.

To really enable the motor with the buttons, you have add some logic for the enable pin. For example change the setMotor() function and give it also a boolean as parameter, which indicates the enabling of the motor:

void setMotor(int speed, boolean enabled, boolean reverse)
{
    if(enabled) analogWrite(enablePin, speed);
    else        analogWrite(enablePin, 0);
    digitalWrite(in1Pin, ! reverse);
    digitalWrite(in2Pin, reverse);
}

You can set a corresponding boolean variable in the loop() function like you did with the status variable. Set this new variable to true in both if-statement of the buttons. Alternatively you can do this inline with the setMotor() call by writing:

setMotor(speed, reverse || reverse1, status);

The || is a logical OR operation. It returns true if any of both operands are true. In a similar way you can ditch the other if-statement with the status variable:

setMotor(speed, reverse || reverse1, !reverse && reverse1);

! negates the value of reverse and && does a logical AND. You can decide yourself, if you want to use if-statements (which are a bit easier to read or these logical statements (which are more compact).

Also you should use better variable names. reverse and reverse1 are not really good to distinguish. Better would be reverse and forward.


Using two ultrasonic sensors for counting cars when they enter to a garage I want to use two ultrasonic sensors for counting incoming cars to a garage. What I want is: When both sensors detect the object then the counter should increase.

Can anyone help me and give me an example?

If you have two sensors, you use analogRead.

int sensor1 = A0;
int sensor2 = A1;
int distance = 50; // or whatever you want here
bool car_passing = false;

void setup(){
    int counter = 0;
}

void loop(){
    if(analogRead(sensor1) < distance &&
       analogRead(sensor2) < distance &&
       !car_passing)
    {
        car_passing = true;
        counter++;
    }

    if(analogRead(sensor1) > distance){
        car_passing = false;
    }
}

To prevent the counter keep counting while the car is passing by, we need to make a boolean, so the counter does not wait for count again, before the car has passed.


Multiple 3-wire SPI sensor interfacing with Arduino I want to connect 4 MAX6675 thermocouple to Arduino.
MAX 6675 description.

It comes with its own Arduino library. library link.

I tested the example code for one sensor and it works perfectly. Now I want to connect all the four sensors to Arduino using minimum GPIO pins possible.

I connected - (for 2 sensors only for initial testing):

D7 -> clk (slave 1) ->clk (slave 2)
D3 -> so (slave 1) ->so (slave 2)
D4 -> cs (slave 1)
D5 -> cs (slave 2)

My code (I modified the original example code a bit):

// this example is public domain. enjoy!
// www.ladyada.net/learn/sensors/thermocouple

#include "max6675.h"

int thermoCLK = 7;
int thermoDO = 3;
int thermoCS = 4;
int thermoCS2 = 5;
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
MAX6675 thermocouple2(thermoCLK, thermoCS2, thermoDO);

void setup() {
  Serial.begin(9600);
  Serial.println("MAX6675 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp
  Serial.print("C = ");
  Serial.println(thermocouple.readCelsius());
  Serial.print("F = ");
  Serial.println(thermocouple.readFahrenheit());
  Serial.print("C 2= ");
  Serial.println(thermocouple2.readCelsius());
  Serial.print("F 2= ");
  Serial.println(thermocouple2.readFahrenheit());
  delay(1000);
}

I am able to read only one sensor information correctly. The other output is nan. Am I wiring the circuit wrong or is my code incorrect or both?

First off ditch that library. It's completely pointless and actually makes things harder.

Secondly connect your sensors to the SPI pins, selecting a new CS pin for each sensor.

Arduino SCK (pin 13) to all the SCK pins.
Arduino MISO (pin 12) to all the SO pins.
Individual GPIO pins to individual CS pins (use pin 10 for one of them).

Then just use a simple function to read the data using the SPI library (adapted from the library you link to). For instance with CS on 10 an 9:

#include <SPI.h>

double readCelsius(uint8_t cs) {
    uint16_t v;

    digitalWrite(cs, LOW);
    v = SPI.transfer(0x00);
    v <<= 8;
    v |= SPI.transfer(0x00);
    digitalWrite(cs, HIGH);

    if (v & 0x4) {
        // uh oh, no thermocouple attached!
        return NAN;
    }

    v >>= 3;

    return v*0.25;
}

void setup() {
    SPI.begin();
    pinMode(10, OUTPUT);
    pinMode(9, OUTPUT);
    digitalWrite(10, HIGH);
    digitalWrite(9, HIGH);

    Serial.begin(115200);
}

void loop() {
    Serial.print(readCelsius(10));
    Serial.print(" ");
    Serial.println(readCelsius(9));
    delay(1000);
}


How to send string over bluetooth LE from Arduino How do you send a string over BLE from Arduino? (and is it any different for an Adafruit Feather 32u4?)

Background: I have force sensitive resistor (fsr) sending an Int value. I would like to convert it to a string (or char or whatever it needs to be) and send it via BLE to an app.

Update:
I was able to successfully send the string via BLE by simply using ble.println(); on my Adafruit Feather 32u4. I have learned that the ble. method inherits commands similar to the Serial.print methods. I used ble.println() to send a string, as opposed to using ble.write() which send data as bytes. I also learned that different hardware devices have different names for this method, such as BTLEserial.write, as well as other names specific to each device. Hopefully, this info helps other people figuring this out, too.

I've used a HC-O6 Bluetooth device connected to pins 2 & 3.  After setting up SoftwareSerial to use those pins, I sent my messages to that SoftwareSerial using the normal method as a "string"/character array.

I would assume this would work the same with a BLE device that used a serial connection.

I'm not familiar with the AdaFruit Feather, but it looks like it's supposed to be a direct Arduino Nano competitor.  You might need to use a different library, but the idea should still be the same.


Storing latitude and longitude floats as chars with specified precision I am receiving lat and long data from a GPS and want to store these numbers in the middle of a sequence of chars.

E.g. lat = -23.123456

long = 135.123456

I am after something like "Your coordinates are -23.123456,135.123456" as an array of chars.

I have tried:

float latitude = -23.123456;
float longitude = 135.123456;

String one = "Your coordinates are ";
String two = ","
String message = one + latitude + two + longitude;

// Convert String to char array
int str_len = message.length() + 1;
char textmessage[str_len];
message.toCharArray(textmessage,str_len);

Serial.println(textmessage);

but the result is: Your coordinates are -023.12,0135.12

How can I correct this?

Thanks in advance!

When formatting serial output is a concern, it's worthwhile to download and use the Streaming.h contributed library that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  If you don't have Streaming.h installed, you can get Streaming5.zip from arduiniana.org.

At present, Streaming.h doesn't support setw() and setfill(), which in ordinary C++ set a field width and a fill character.

However, it does support  four base-conversion specifiers, _HEX, _DEC, _OCT, and _BIN; a _FLOAT function with number of decimal places specified; and endl.

Thus, to print  “Your coordinates are -23.123456, 135.123456” one would write:

Serial << "Your coordinates are " << _FLOAT(latitude,6) << ", " << _FLOAT(longitude,6) << endl;

Note that unlike the String class, use of Streaming.h does not entail any dynamic memory management – everything it does happens at compile time – and it does not increase code size – it translates stream-style operations into ordinary .print() and .println() calls.  It should result in somewhat smaller, faster, and more-robust code, by avoidance of String.  Use of dynamic memory on small-memory embedded systems can be problematic, and this avoids those problems.

Edit 1a: As Chris Stratton points out, Arduino floats don't support 9-digit precision.  I think Arduino floating-point arithmetic is intended to comply with IEEE 754, which sets out standards to be used on modern computers that support floating-point arithmetic.

In the binary32 format used to implement IEEE 754 single-precision binary floating-point, significand precision is 24 bits.  That equates to about 7.22 decimal digits (ie, 24*log₁₀(2)), so for simple calculations, 7-digit accuracy is realistic, more than that is not.

[Part of] Edit 1b:  In the larger scheme of things perhaps there's no need to create and save a formatted string like that.  It is not useful for computing – the float values are better for that.  It is not needed for communication – another streaming write can be done.

Edit 2 [replaces most of 1b]: Streaming.h  doesn't build any strings, but just delivers the text of its <<-arguments character-by-character to a stream.  However, a PString class at arduiniana can build strings from stream inputs, as in the following example code.

#include <Streaming.h>
#include <PString.h>

char buffer[28];
PString pstr(buffer, sizeof(buffer));

void setup() {
  Serial.begin(115200);
  pstr.begin();     // Empty the buffer
}

void loop() {
  int first=50, second=100;
  pstr.begin();     // Empty the buffer
  pstr << 'X' << first << 'Y' << second << 'T';
  pstr += " hihi ";
  pstr << millis() << endl;
  Serial << pstr;
  delay(1000);
}

Here's what some of its output to Serial looks like:

X50Y100T hihi 263198
X50Y100T hihi 264199
X50Y100T hihi 265199
X50Y100T hihi 266201
X50Y100T hihi 267201
X50Y100T hihi 268201

What the sample of code does is first initialize a string buffer, then build part of a character string using streaming operator <<, then part of it using concatenation, then some more with <<, then print the string.  Note that the strings involved here are in fixed buffers, rather than dynamically allocated buffers like the String class uses.


Problem with my usb plug First of all, we connected our usb plug to arduino board (starter kit). After that, we completed Project 1 successfully (circuit with led and switch.) We tried unplug the usb cable, but it was very difficult, we had to pull very hard, but we couldn't unplug it. Finally, I managed to take it away with the help of my partner. I was pulling the usb and my partner was keeping the arduino board stable. The result wasn't very nice, we probably broke the usb cable. You can see what I mean in these images, the metallic coating part of the cable is still stuck on the board.
https://ibb.co/6wtf02J
https://ibb.co/4pZg2w0
https://ibb.co/WPchtgN
https://ibb.co/gPHZYnt
Nevertheless, we put the remaining cable back where it was, and the board seems to be working normally.
My question is if it safe to use it. Is there any chance of electrical damage or something like that?
Thank you!
P.S. In addition, we are planning to buy a new arduino starter kit. How can we avoid this problem with the new board?

Without the center part of the USB plug, it should be possible to make some deformations of that shield without damaging rest of the usb connector and pull it out. Aim for the weakest spot - seam (usually in the middle of bottom).
But even if you damage on board connector, it can be replaced (but it might be better to give it to someone with soldering experience - at least for unsoldering it)
And as noted in comments, even without working usb connector it can be programmed either by connecting USB-TTL serial converter to D0/D1 (but without auto-reset, unless you provide 100nF capacitor between reset and RTS), or it can be programmed by another Arduino as SPI (it needs bit more wires, and by default it doesn't burn bootloader, so if you fix USB, you'll have to burn bootloader).
Easier might be swapping Atmega328p between boards, however it needs some practice, so you won't bend or rip pins)


Why it shows d2 was not declared in scope #define BLYNK_PRINT Serial
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include <DHT.h>
#define BLYNK_PRINT Serial
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS D2

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
char auth[] ="your auth token";
char ssid[] = "your wifi name";
char pass[] = "your wifi password";

#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
SimpleTimer timer;

void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Blynk.virtualWrite(V5, h);  //V5 is for Humidity
  Blynk.virtualWrite(V6, t);  //V6 is for Temperature
}

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);

  dht.begin();

  timer.setInterval(1000L, sendSensor);
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
   sensors.begin();
}

int sensor=0;

void sendTemps()
{
  sensor=analogRead(A0);
  sensors.requestTemperatures();
  float temp = sensors.getTempCByIndex(0);
  Serial.println(temp);
  Serial.println(sensor);
  Blynk.virtualWrite(V1, temp);
  Blynk.virtualWrite(V2,sensor);
  delay(1000);
}

void loop()
{
  Blynk.run();
  timer.run();
  sendTemps();
}

Arduino pins are defined only by a simple number, with the exception that the analog pins are also named as 'A0' through 'A8' (or however many analog pins the specific processor has). Thus, D2 is not defined. If you mean to refer to Arduino pin 2, its name is just '2'. So:
#define ONE_WIRE_BUS D2  ->  #define ONE_WIRE_BUS 2


How i convert to Arduino Mega? i need using OV7670 camera on my arduino mega, and i found this site have tutorial using ov7670 camera, but in this tutorial they use arduino Uno. if i'm using arduino Mega2560, what i need to do? do i have to change their code and pin connection ?

here is the link

https://www.instructables.com/id/OV7670-Arduino-Camera-Sensor-Module-Framecapture-T/?amp_page=true

Yes, you will have to change the code to match the Mega pinout.

Because the program need to run quite fast, and the Arduino functions
digitalRead() and digitalWrite() are dead slow, the author of the
program used direct port access for performing the raw IO.
For example:

    //Wait for vsync it is on pin 3 (counting from 0) portD
    while(!(PIND&8));//wait for high
    while((PIND&8));//wait for low

This is testing pin PD3 (8 is 23), which on the Uno is
digital 3, but on the Mega is digital 18. The same code could
be written in a portable fashion:

    //Wait for vsync it is on pin 3 (counting from 0) portD
    while (digitalRead(3) == LOW);   //wait for high
    while (digitalRead(3) == HIGH);  //wait for low

but it would probably be too slow.

Note also that here:

    UDR0=(PINC&15)|(PIND&240);

the program takes advantage of the particular pin mapping of the Uno in
order to read 8 inputs with only two port reads (4 bits on
port C and 4 bits on port D). You could do even better on the Mega
if you use pins A8 through A15 for the data bus, and then read the whole
8-bit word as PINK.

There may be some other differences between the Uno and the Mega that
need to be taken into account, but the pin mapping is the only one that
is obvious to me just by quickly going through the code.


Connect the output of an Arduino to the input from another Arduino I'm making a project and i'm trying to send bits from an Arduino to another Arduino with the digital pins. So my setup are 2 Arduino's connected with a jumper.
I connected the grounds and they have both a different power supply.
Now I tried this set-up and as soon as I connect the output pin to the input pin from the other Arduino the voltage lowers from 5V to 2.6V so we can't detect our bits.
Anybody an idea how to solve this problem?

Thanks in advance!

Kind regards,
Manu

As you are trying to communicate with two arduinos I will suggest you to use some sort of standard communication protocol such as Two wire interface or I2c. There is the Wire.h library you can use and it has also a reference on the main Arduino site. If you have different necessity and want to carry on with you're methods you need to specify in more depth the connections you have made. As for now I can guess that the output is being connected to ground or some sort of load and that might be the reason you are seeing a drop out of voltage. But it might be also the case that you're output pin is changing so fast that the multimeter is not capable of reading the high state correctly


Calculating Amp/Hrs of a solar panel I am interested in calculating the amp/hour output of a solar panel using an Arduino. I am confident I can get the voltage (with a voltage divider) & the amperage (with an ACS712). My question is about the math of calculating Amp*hour.

Here is my plan:

My plan is to pull the voltage and amperage every second.
I would then add this amp*second value to a variable. I would also increment another variable for each second.
I would then be able to get an average or total of Ampseconds from these 2 variables. I could also divide the ampsecond by 3600 if I wanted Amp*Hour.

Is it too much a stretch to poll the amperage every second and call it amp/second? How can I make this more accurate?

There's lots of misunderstandings here, but here's the gist of it.

What you want to do is a perfect application of an Arduino. No need to buy a coulomb counter, instead, you should make one with your Arduino.

  I would then add this amp/second value to a variable.

First correction, it's an amp*second, NOT an amp/second. You are multiplying amps by the number of seconds that current value existed.

amp*seconds / 3600 = amp*hours. Read about that here: https://en.wikipedia.org/wiki/Ampere_hour. Multiply that by the voltage over that same time period and you've got amps*hours*volts = (amps*volts)*hours = Watts*hours = units of energy! Remember, your house electricity it purchased in units of kilowatt hours, which is kilowatts*hours, or kWhr. And in engineering units a joule is  the standard unit of energy, and it is simply Watts*seconds. So, you can convert kWhr to joules like this, where units are in square brackets [].

Joules = kWhr * 1000 [Whr/kWhr] * 3600 [sec/hr] = [Watts*sec] = [Joules]

So, 1 kWhr x 1000 x 3600 = 3600000 Joules = 3600kJ

  I would also increment another variable for each second.

That doesn't make any sense. Don't do that. You've already captured the seconds by adding your new bit of amps*seconds to your old sum of it.

DO account for voltage too! What you're really after is energy, which can be expressed in units of joules or kWhr, as already described above.

  Is it too much a stretch to poll the amperage every second and call it amp*second?

(my corrections in bold)

No, absolutely not! That's exactly what an amp*second is! It's the current, amps, times the number of seconds that current existed. That's a coulomb counter!

  How can I make this more accurate?

This is the part where the engineer and programmer (you) determines the quality of the result.

Don't assume 1 second elapsed because you told it to. Measure it for each and every measurement!
The smaller the time interval, the more accurate, since it allows you to capture the small current fluctuations, so use a smaller time slice than 1 second. I'd start with 10ms.
Measure voltage AND current AND actual time elapsed on this loop as close to the same time as possible.
Do NOT use blocking techniques, such as delay() or delayMicroseconds().
What you're doing when you're multiplying a new amp reading x seconds, and adding it to the previous sum is called numerical integration. You're simply numerically integrating, or summing, the area under the Amp (y-axis)-time (x-axis) curve, or, if you're doing what I'm saying to do intead: the Watt (y-axis)-time (x-axis) curve, where the area under the curve is the total energy collected. Don't do rectangular integration, do trapezoidal integration following the trapezoidal rule! It's more accurate!
Calibrate your clock! An Arduino's clock can be off by a couple percent. Figure out how much it's off by comparing its clock output over, say, 10 minutes, and comparing it to a better clock source, say...an internet time server displaying the atomic clock in Colorado or wherever it is. Then, multiply each measurement by a scaling factor to fix it!
On the same lines as above, ideally you'd also compensate in real-time for temperature, as the clock frequency drifts with temperature.
Calibrate the voltage measurement.
Calibrate the current measurement.

Extra: when is trapezoidal integration most beneficial?

The merits of trapezoidal integration can be argued, and it's probably not as important as I originally made it sound, but it is super easy to implement, so why not!? Also, it is most important when:

The time sampling rate is super low.
The rate of change of readings (ie: their derivative, or slope) is super high.
The readings consistently have a rising slope (rectangular integration _under_estimates the area in this case) OR a consistently falling slope (rectangular integration _over_estimates in this case).
When you care about real-time readings in this instant, not just overall trends or averages. This is because trapezoidal integration instantly removes overestimation and underestimation error which can accumulate over short periods but then "de-accumulates", or is negated, over long periods, when the opposite slope occurs in the data.
When the readings consistently rise at a different rate than the fall, as this results in asymmetric accumulation of error. This means that the rectangular integration error accumulated by the values rising distance delta_y will NOT be fully negated by error in the opposite direction when the values fall distance delta_y. Therefore, even over long periods, rather than seeing the error negated, it will accumulate more and more over time. [Note: I'd need to analytically/numerically play with this hypothesis for a while to prove it conclusively to myself, but I'm pretty sure it is correct].

Full coulomb counter example in code:

Here's a full coulomb counter example in code. You just need to implement a few functions to read samples and do calibrations is all.

I'm borrowing the timestamp-based cooperative multitasking part of this code from my answer about cooperative multitasking here, so go check it out for more information on that.

As written, this code compiles, but I haven't wired anything up or tested it. Here's the compilation output:

  Sketch uses 3750 bytes (12%) of program storage space. Maximum is 30720 bytes.
  Global variables use 262 bytes (12%) of dynamic memory, leaving 1786 bytes for local variables. Maximum is 2048 bytes.

coulomb_counter.ino:

Jump to the bottom for the setup() and loop() functions. They are both really short.

/// Coulomb counter example
/// By Gabriel Staples
/// See: https://arduino.stackexchange.com/questions/75932/calculating-amp-hrs-of-a-solar-panel/75937#75937

/// @brief      A function-like macro to get a certain set of events to run at a desired, fixed
///             interval period or frequency.
/// @details    This is a timestamp-based time polling technique frequently used in bare-metal
///             programming as a basic means of achieving cooperative multi-tasking. Note
///             that getting the timing details right is difficult, hence one reason this macro
///             is so useful. The other reason is that this maro significantly reduces the number of
///             lines of code you need to write to introduce a new timestamp-based cooperative
///             task. The technique used herein achieves a perfect desired period (or freq)
///             on average, as it centers the jitter inherent in any polling technique around
///             the desired time delta set-point, rather than always lagging as many other
///             approaches do.
///
///             USAGE EX:
///             ```
///             // Create a task timer to run at 500 Hz (every 2000 us, or 2 ms; 1/0.002 sec = 500 Hz)
///             const uint32_t PERIOD_US = 2000; // 2000 us pd --> 500 Hz freq
///             bool time_to_run;
///             uint32_t actual_period_us;
///             CREATE_TASK_TIMER(PERIOD_US, time_to_run, actual_period_us);
///             if (time_to_run)
///             {
///                 run_task_2();
///
///                 // OR, if `run_task_2()` needs the actual period that just occurred, for
///                 // whatever reason, you may pass it in to your `run_task_2()` function:
///                 run_task_2(actual_period_us);
///
///                 // OR, just do all your code right here instead of in `run_task_2()`
///             }
///             ```
///
///             Source: Gabriel Staples
///             https://stackoverflow.com/questions/50028821/best-way-to-read-from-a-sensors-that-doesnt-have-interrupt-pin-and-require-some/50032992#50032992
/// @param[in]  period_desired_us  (uint32_t) The desired delta time period, in microseconds;
///                             note: pd = 1/freq; the type must be `uint32_t`.
/// @param[out] time_to_run     (bool) A `bool` whose scope will enter *into* the brace-based scope block
///                             below; used as an *output* flag to the caller: this variable will
///                             be set to true if it is time to run your code, according to the
///                             timestamps, and will be set to false otherwise.
/// @param[out] actual_period_us  (uint32_t) The actual period, in us, since the last time it was
///                             time to run--ie: since the last time `time_to_run` was set to true.
/// @return     NA--this is not a true function
#define CREATE_TASK_TIMER(period_desired_us, time_to_run, actual_period_us)                                            \
{ /* Use scoping braces to allow multiple calls of this macro all in one outer scope while */                          \
  /* allowing each variable created below to be treated as unique to its own scope */                                  \
    time_to_run = false;                                                                                \
                                                                                \
    /* set the desired run pd / freq */                                                                                \
    const uint32_t PERIOD_DESIRED_US = period_desired_us;                                                              \
    static uint32_t t_start_us = micros();                                                                             \
    uint32_t t_now_us = micros();                                                                                \
    uint32_t period_us = t_now_us - t_start_us;                                                                        \
    actual_period_us = period_us;                                                                                \
                                                                                \
    /* See if it's time to run this Task */                                                                            \
    if (period_us >= PERIOD_DESIRED_US)                                                                                \
    {                                                                                \
        /* 1. Add PERIOD_DESIRED_US to t_start_us rather than setting t_start_us to t_now_us (which many */            \
        /* people do) in order to ***avoid introducing artificial jitter into the timing!*** */                        \
        t_start_us += PERIOD_DESIRED_US;                                                                               \
        /* 2. Handle edge case where it's already time to run again because just completing one of the main */         \
        /* "scheduler" loops in the main() function takes longer than PERIOD_DESIRED_US; in other words, here */       \
        /* we are seeing that t_start_us is lagging too far behind (more than one PERIOD_DESIRED_US time width */      \
        /* from t_now_us), so we are "fast-forwarding" t_start_us up to the point where it is exactly */               \
        /* 1 PERIOD_DESIRED_US time width back now, thereby causing this task to instantly run again the */            \
        /* next time it is called (trying as hard as we can to run at the specified frequency) while */                \
        /* at the same time protecting t_start_us from lagging farther and farther behind, as that would */            \
        /* eventually cause buggy and incorrect behavior when the (unsigned) timestamps start to roll over */          \
        /* back to zero. */                                                                                \
        period_us = t_now_us - t_start_us; /* calculate new time delta with newly-updated t_start_us */                \
        if (period_us >= PERIOD_DESIRED_US)                                                                            \
        {                                                                                \
            t_start_us = t_now_us - PERIOD_DESIRED_US;                                                                 \
        }                                                                                \
                                                                                \
        time_to_run = true;                                                                                \
    }                                                                                \
}

// Convert microseconds to seconds
#define US_TO_SEC(us) ((us)/1000000UL)
// Convert Joules to KWh (Kilowatt*hours)
#define JOULES_TO_KWHRS(joules) ((joules)/3600/1000)

/// @brief      Obtain a corrected time measurement from a raw time measurement.
/// @details    Assuming you have done experiments to determine your microcontroller (mcu)
///             clock's error, you can correct for it with this function. Pass in a time
///             measurement the mcu has timed directly, and get back a corrected value.
/// @param[in]  raw_sec     A raw time measurement, in seconds
/// @return     A corrected time measurement, in seconds
float do_time_correction(float raw_sec)
{
    // You determine the correct calibration constant. Perhaps it is 0.9813, or perhaps it is
    // 1.19.... You will need to determine this for each individual mcu.
    constexpr float TIME_CORRECTION_CONST = 1.0; // default: 1.0
    float corrected_sec = raw_sec*TIME_CORRECTION_CONST;
    return corrected_sec;
}

/// @brief      Obtain a new instantaneous (at this moment) current reading, in Amps
/// @param      None
/// @return     Current, in Amps
float get_current()
{
    // you implement this
}

/// @brief      Obtain a new instantaneous (at this moment) voltage reading, in Volts
/// @param      None
/// @return     Voltage, in Volts
float get_voltage()
{
    // you implement this
}

/// @brief      Run the coulomb counter task to sum the total energy received from the solar panels
/// @param[out] total_energy_joules_p  (optional) A pointer to a float to receive back the total
///                         energy value acquired, in Joules (Watts*sec). Pass in `nullptr` to not
///                         receive back this value. Note that the previously-cached value is
///                         passed out in the event it's not time to calculate a new value.
///                         The return value of this function will indicate whether a new value
///                         or cached value is passed out here.
/// @param[in]  reset_sum   (optional) pass in true to reset the internally-stored "total energy
///                         acquired" value during this call (prior to performing the latest
///                         power_watts_avg calculation, if it is time for that).
/// @return     true if a new total_energy_joules value was just calculated and passed back via the
///             pointer above, or false if an old, cached value was passed out instead since it
///             wasn't time to obtain and calculate a new value.
bool run_coulomb_counter(float* total_energy_joules_p = nullptr, bool reset_sum = false)
{
    // Set this task to run at 100 Hz
    constexpr uint32_t PERIOD_DESIRED_US = 10000; // 10000us = 10ms, or 100Hz run freq

    static float total_energy_joules = 0;

    if (reset_sum)
    {
        total_energy_joules = 0;
    }

    bool time_to_run = false;
    uint32_t actual_period_us;
    CREATE_TASK_TIMER(PERIOD_DESIRED_US, time_to_run, actual_period_us);
    if (time_to_run)
    {
        // Time to obtain new samples and perform some numerical integration to obtain the total
        // energy received.

        // the previous power calculation, in watts; required for trapezoidal integration
        static float power_watts_old = 0;

        // take new samples, & calculate power from those samples
        float current_amps = get_current();
        float voltage = get_voltage();
        float power_watts = current_amps*voltage;

        float actual_period_sec = US_TO_SEC((float)actual_period_us);
        actual_period_sec = do_time_correction(actual_period_sec);

        // Perform trapezoidal integration to obtain the "area under the curve", which is equal to
        // the energy in joules. Imagine a plot where the y-axis is power and the x-axis is time. If
        // you split the x-axis up into segments of width PERIOD_DESIRED_US, then the trapezoidal
        // area under the curve, within each of those time segments, is equal to time_delta x
        // (power_old + power)/2. This is the energy (Joules) obtained during that time period.
        float power_watts_avg = (power_watts + power_watts_old)/2;
        power_watts_old = power_watts; // prepare for next iteration
        float energy_joules = actual_period_sec*power_watts_avg;

        total_energy_joules += energy_joules;
    }

    if (total_energy_joules_p != nullptr)
    {
        // output this value back to the user
        *total_energy_joules_p = total_energy_joules;
    }

    return time_to_run;
}

void setup()
{
    // do whatever you need to here
    Serial.begin(115200);
}

void loop()
{
    // Energy, in Joules, or Watt*seconds. To convert to Watt*hours, simply divide by 3600 [sec/hr]
    float total_energy_joules;
    bool new_measurements_made = run_coulomb_counter(&total_energy_joules);

    // Let's do an event-based print where we print the latest total_energy_joules value at a rate
    // of 2 Hz, which is typical for digital displays showing information expected to be read by
    // us slow humans. Since the run_coulomb_counter() task is running at 100 Hz, that means we
    // need to print the latest value every 50 runs.
    if (new_measurements_made)
    {
        static uint16_t run_count = 0;
        run_count++;
        if (run_count % 50 == 0)
        {
            float total_energy_kwh = JOULES_TO_KWHRS(total_energy_joules);
            Serial.print("total energy received (J) = ");
            Serial.print(total_energy_joules);
            Serial.print("; (kWh) = ");
            Serial.println(total_energy_kwh);
        }
    }
}

References:

[my own answer about generic, timestamp-based cooperative multitasking] https://stackoverflow.com/questions/50028821/best-way-to-read-from-a-sensors-that-doesnt-have-interrupt-pin-and-require-some/50032992#50032992


Multimaster I2C with same address I use the Wire Library and need to have multi-master setting. I see multi-master examples, where the masters have their own ID's -- which make sense.

Now I have just connected three devices on the bus with the same ID (for example 0x05) and they can communicate! Every node can listen to all traffic, which is not common but this was exactly what I want.

The question is: Will I have trouble in the future? Is my setup something like "multi-slave"?

const byte MY_ADDRESS = x;  // where x is whatever unique address you like

byte RxByte[32]  //32 byte buffer

void setup() {
  //insert unique ddress
  Wire.begin(MY_ADDRESS);

// this line allows the arduino to listen for i2c broadcast at address 0

TWAR = (MY_ADDRESS << 1) | 1;
//set up a receive handler
 Wire.onReceive(receive_data);

then call
Wire.beginTransmission (0)  //transmit broadcast so all devices will receive

Wire.write( address of destination) // make the first byte the destination

Wire.endTransmission ();

then you need a receive handler

void receive_data() {
//use a buffer to temporarily store the data

for ( int d = 0; Wire.available() > 0 ;d++){

RxByte[d] = Wire.read();} // READ WIRE BUFFER UPTO 32BYTES, INTO AN ARRAY
datareceived = 1;

//then test if it was for this device
if (RxByte[0] == MYADDRESS){ do somthing with RxBytes[1-31];}
else {}

I use this extensively its very handy and works well I have a complex transmission table which has a 4 byte header and the rest of the bytes can be used as data send

destination, myaddress, a command, and how many data bytes to follow

Addendum to Original answer. below is a complete working example.

//so the basics of the tranmission table are the first 4 bytes (ie Rx or Tx byte 0-3 depending on if we are talking about the sender or recipient)
    //are used as a header 0= recipient (0 for broadcast. or address) 1= senders address 2= is the command (ie tells the recipient what to do)
    //and 4= the number of data bytes which follow in the packet
    //not all of these need to be specified at any time but its usefull to have a structure to follow at each end which never changes
    //copy and past this upload to 2 arduinos connected by i2c change the 2 addresses and it should work.
its a n example of how data can be moved around in a multi master situation
that should hopefully give you some ideas. it looks complicated but half of it is just generating some example data and triggering method and the transmit part is repeated 3 times to send out different data.. you should be able to create a more general purpose transmit block for your application

to send data just attach a button or wire to pin 2 directly to ground

watch the 2 serial windows

#include <Wire.h>
//device address  MAKE DIFFERENT FOR EACH

const byte MY_ADDRESS = 20;
const byte PARTNER_DEVICE = 25;

// transmission table stuff
byte RxByte[32]; //setup a receive buffer to hold data
byte TxByte[32]; //setup a transmit buffer to hold data
byte datareceived;

// stuff to generate some data
const int Sensor1 = A0;
byte SensorVal1 = 0;

//stuff to debounce pin 2
const byte digitalpin = 2;
byte pinstate = 0;
byte lastpinstate = 0;
unsigned long checktime = 0;
const byte debouncetime = 50;

// timer
unsigned long timing_loop = 5000;

void setup() {
  Wire.begin (MY_ADDRESS);
  TWAR = (MY_ADDRESS << 1) | 1;                                                      // ENABLE BROADCASTS TO BE RECEIVED
  Wire.onReceive(ReceiveData);     // INTERUPT ON I2C DATA RECEIVE
  Serial.begin(9600);
  pinMode (  digitalpin  , INPUT_PULLUP );// set the pin to input pullup so we can trigger the code by connecting directly to ground
  Serial.println( "READY" );
}

void loop() {
  // generate some random data

  GenRandData();
  //Serial.print(  pinstate);Serial.print( " " );Serial.println( lastpinstate );
  // debounces pin 2 so we can trigger a data broadcast
  pinstate = digitalRead (digitalpin);
  if ( pinstate != lastpinstate && millis() >= checktime) {
    if ( pinstate == 0 && lastpinstate == 1 ) {
      checktime = millis() + debouncetime;
      Serial.println( " button working" );
      REQUEST();
    }
    lastpinstate = pinstate ;
  }

  // this triggers the process data method after receive of data
  if (datareceived == 1  ) {
    datareceived = 0 ;
    ProcessData();
  }

  // 10 second timer triggers transmission of some data
  if ( millis() >= timing_loop ) {
    BROADCAST();
  }
}
void GenRandData() {
  // this just reads analog0 and maps it to a byte then sequentially shifts the transmit buffer
  SensorVal1 = random(255);
  TxByte[7] = TxByte[6];
  TxByte[6] = TxByte[5];
  TxByte[5] = TxByte[4];
  TxByte[4] = SensorVal1;
}

void ReceiveData() {
  // READ AVAILABLE BYTES INTO 32BYTE BUFFER (while data is available)
  for ( byte d = 0; Wire.available() > 0 ; d++) {
    RxByte[d] = Wire.read();
  }
  //set a trigger event
  datareceived = 1;
  Serial.println( "receive" );
}

void ProcessData() {
  Serial.println( "process" );
  // check what the data is an who its for then do something with it (RECEIVE TABLE)
  if (RxByte[0] == MY_ADDRESS) { // for this device
    switch (RxByte[2]) {
      case 1:       Serial.print("RECEIVED DATA FOR THIS DEVICE, = "); Serial.println( RxByte[4] ); break;
      case 255:       Serial.println("RECEIVED A REQUEST FOR DATA, SENDING READ FROM  > Sensor1"  ); ActAsMaster();              break;
      default:      Serial.print("D-Type byte = error"); Serial.println(RxByte[2]);                   break;
    }
  }

  else if (RxByte[0] == 0) {       //handle broardcast
    Serial.print( "RECEIVED BROADCAST FROM DEVICE = " ); Serial.println( RxByte[1] );
    Serial.print( "DATASIZE = " ); Serial.print( RxByte[3] ); Serial.println( " Bytes" );
    Serial.print( "DATABYTE 1 = " ); Serial.println( RxByte[4] );
    Serial.print( "DATABYTE 2 = " ); Serial.println( RxByte[5] );
    Serial.print( "DATABYTE 3 = " ); Serial.println( RxByte[6] );
    Serial.print( "DATABYTE 4 = " ); Serial.println( RxByte[7] );
    Serial.println( "DONE" );
  }
  Serial.println(  );
}

void BROADCAST() {
  // this is transmission table to send data to everyone
  Serial.println("Sending broadcast");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (0);                       // broadcast
  Wire.write(0);                                    // ADDRESS =0 BROARDCAST
  Wire.write(MY_ADDRESS);                           // SEND my address
  Wire.write(0);                                    // DATA TYPE CODE
  Wire.write(4);                                    //number of bytes being sent
  Wire.write(TxByte[4]);                            //data
  Wire.write(TxByte[5]);                            //data
  Wire.write(TxByte[6]);                            //data
  Wire.write(TxByte[7]);                            //data
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;
    Serial.println( "fail" );
    goto Tx;
  }
  //reset timer to run this again
  timing_loop = millis() + 10000 ;
  Serial.println(  );
}

void ActAsMaster() {
  //this is transmission table to send data to specific device OR return a result of a task
  Serial.println("Sending data");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (RxByte[1]);               //the return address
  Wire.write(RxByte[1]);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(1);                                  // DATA TYPE CODE
  Wire.write(1);
  Wire.write(SensorVal1);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );

}
void REQUEST() {
  //this is transmission table to send data request of partner device
  Serial.println("Sending request");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (PARTNER_DEVICE);               //the return address
  Wire.write(PARTNER_DEVICE);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(255);                                  // DATA TYPE CODE (MASTER ADDRESS)
  Wire.write(0);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );
}


Why using static volatile for variables and only static for arrays in TWI library? I want to know why to declare variables with static volatile and arrays with only static in TWI library?

For example;

static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_masterBufferIndex;
static volatile uint8_t twi_masterBufferLength;

You use volatile to mark variables that are going to change at any moment, in a ISR (Interrupt Service Routine) typically.

You mark them so the compiler doesn't optimize, and always go and pick its actual value. If you don't do that, then an ISR may update a variable while the main "thread" of execution keeps using its old value. That's is a nasty situation to debug.

You only need to mark variables that are used both in the ISR and in the main sketch. If twi_masterBuffer is not changed inside an ISR, you don't need to mark it with volatile.

static is used inside function to mark variables that need to be permanent, i.e., keep their values between calls, but not accessible from outside that function.


L298N, HC-05 Simple Bluetooth remote car not running in Arduino Arduino board type used in this session is Arduino Uno R3 DIP/SMD CH340

Below is the description of wiring and code in Arduino to assemble a Bluetooth RC car using android smartphone:

Tested the motor dc result both of wheel works (can spin forward and or backward). power direct from the battery.
Tested HC-05 bluetooth moduled. The phone can paired the bluetooth module.
Tested out1 out2 out3 and out4 on L298N using direct power from the battery the wheel spinning (forward and or backward).
The code for the Bluetooth rc simple car used below as described.

The car failed to move (forward, backward, turn left/right). how to make the motor dc and or the motor stepper works remotely. thank you

    #include
    SoftwareSerial mySerial(12, 13); // RX, TX
    #define m1 3
    #define m2 5
    #define m3 9
    #define m4 10

int data=0,kec=0;
boolean forward=true;

int fast[11]={0,80,100,120,140,160,180,200,220,240,255};

void setup()
{
  pinMode(m1,OUTPUT);
  pinMode(m2,OUTPUT);
  pinMode(m3,OUTPUT);
  pinMode(m4,OUTPUT);

  mySerial.begin(9600);
 }

void motorOut(unsigned char lpwm, unsigned char rpwm, boolean arrow){
   if(arrow==false){
      digitalWrite(m3,HIGH);
      digitalWrite(m1,LOW);
      analogWrite(m4,255-lpwm);
      analogWrite(m2,rpwm);
   }
   else{
     digitalWrite(m3,LOW);
     digitalWrite(m1,HIGH);
     analogWrite(m4,lpwm);
     analogWrite(m2,255-rpwm);
  }
}

void loop(){
  if(mySerial.available()>0){
    data=mySerial.read();
    if (data =='0') { kec=0;}
      else if (data =='1') { kec=1;}
        else if (data =='2') { kec=2;}
          else if (data =='3') { kec=3;}
            else if (data =='4') { kec=4;}
             else if (data =='5') { kec=5;}
              else if (data =='6') { kec=6;}
                else if (data =='7') { kec=7;}
                  else if (data =='8') { kec=8;}
                    else if (data =='9') { kec=9;}
                      else if (data =='q') {kec=10;}

  //S= Stop
 if (data == 'S')
 { motorOut(0,0,false); }

//F=Forward
if (data=='F')
{ motorOut(fast[kec],fast[kec],true); }

//I=turn right forward
if (data=='I')
{ motorOut(fast[kec],((fast[kec])/2),true);}

//G=turn left forward
if (data=='G')
{ motorOut(((fast[kec])/2),fast[kec],true); }

//R=turn right
if(data=='R')
{ motorOut(fast[kec],0,true); }

//L=turn left
if(data=='L')
{ motorOut(0,fast[kec],true); }

//B=back
if(data=='B')
{ motorOut(fast[kec],fast[kec],false); }

//H=turn left back
 if (data=='H')
   { motorOut(((fast[kec])/2),fast[kec],false); }

//turn right back
   if (data=='J')
    { motorOut(fast[kec],((fast[kec])/2),false); }
  }
}

sorry for my careless. finaly its works....wrong pin assign the main problem....should be IN1, IN2, IN4 and IN3 not IN1, IN2, IN3 and IN4. thank you for all hands for help before


what will be the sampling frequecy of my arduino Mega 2560 code. How would I calculate it? void setup() {
    // initialize the serial communication:
    Serial.begin(9600);
    pinMode(10, INPUT); // Setup for leads off detection LO +
    pinMode(11, INPUT); // Setup for leads off detection LO -
}

void loop() {
    if ((digitalRead(10) == 1) || (digitalRead(11) == 1)) {
        Serial.println('!');
    }
    else {
        // send the value of analog input 0:
        Serial.println(analogRead(A0));
    }
    //Wait for a bit to keep serial data from saturating
    delay(1);
}

EDIT

This sketch is for plotting raw ECG signal having a baud rate of 9600. but when I use these data for calculating heart rate then I want sampling rate for calculation but I don't get the value by this sketch. How will I calculate the frequency from the coming raw data? As it does not show a clear picture.

On the Arduino Mega, the ADC is clocked at F_CPU/128 =
125 kHz (period = 8 µs). Except for the very first one,
each ADC conversion takes 13 ADC clock cycles, i.e. 104 µs. If
you run analogRead() in a tight loop, like

for (;;)
    analogRead(A0);

the CPU has to do some work in between the conversions, and since the
ADC always starts by waiting for a rising edge of the ADC clock, you
loose at least one full ADC cycle in between the conversions. You then
get one conversion every 14 ADC cycles, which results in a sampling
period of 112 µs, and the corresponding sampling frequency of about
8.93 kHz.

The code you showed does a little bit more than an analogRead() per
iteration: two digitalRead(), a test, and a Serial.println() that
involves a binary to decimal conversion. I am not sure the CPU will be
able to handle all that in a mere 8 µs. You might end up using
15 ADC clock cycles per iteration (13 for the conversion,
2 for the computation), which would result in 120 µs
(8.33 kHz) sampling period. Maybe even more. You will have to test
if you want to know for sure. The sampling period is not even guaranteed
to be constant: the code will take longer to run whenever it's
interrupted by the timer interrupt, which the Arduino core uses for
timekeeping purposes...

All this applies as long as the serial output buffer is not full. Once
you have 64 bytes waiting to be sent, the buffer will be full, and
Serial.println() will start delaying the output, effectively
throttling down your loop to the speed of the serial connection. C.f.
the busybee's answer for the details. Note that the sampling period is
still not constant, as sending a 1-to-4-digit number through the serial
port can take anywhere between 3.125 and 6.25 ms.

If you want a constant sampling period, you have to take control over
the timing yourself. A straightforward example would be:

const uint32_t SAMPLING_PERIOD = 6500;  // 6.5 ms

void loop() {
    static uint32_t last_sample;
    if (micros() - last_sample >= SAMPLING_PERIOD) {
        last_sample += SAMPLING_PERIOD;
        Serial.println(analogRead(A0));
    }
}

You could go faster with a higher baud rate, but you have to always keep
SAMPLING_PERIOD consistent with your chosen baud rate. The code above
will still produce some jitter in the sampling, mostly due to the timer
interrupt. If this is not acceptable for your application, you will have
to read the datasheet of the microcontroller and learn how to set the
ADC to be “auto-triggered” from a timer.


Connection of arduino to java Netbeans How to connect Arduino UNO to Netbeans (java)?
Because I want to input flood height taken using ultrasonic sensor to Netbeans.
Thanks for the help.

To do this, you essentially have to code up a version of the Arduino serial monitor within Java (i.e. write Java code to listen to a serial port and recieve bytes from it).

I found an example that might help you-https://playground.arduino.cc/Interfacing/Java


Use MQTT to update internal clock I write code to upload to ESP8266. I wish to use time stamp in order to log events. I found an NTP sketch, I can work with ( since it has a wifi connection ), but I wish to keep my code as simple as possible.

So I'm thinking to use my MQTT server to send time updates from time to time ( have a certain topic for that ), and in between updates, use millis() .

Since I'm new here, I want to know from experienced programmer if it makes sense ?
I would love to hear pros and cons ( before I start coding ).

Any help will be appreciated,

Guy

Use the Time library a.k.a. TimeLib.h. It will keep time between calls to your source of time, if it is your MQTT call or NTP server.

In your code you will use the Time library to get time and the source of the current time is independent from the rest of the code.

The TimeLib has a function setTime to set the current time and then it keeps the time using millis(). You can update the time by calling setTime again. The timestamp value for setTime is 'Unix Epoch' - number of seconds from "1970-01-01 00:00:00".

If you decide to add NTP to your project, you can use NtpClientLib. It sets the time to TimeLib with one simple line of code in setup(). Example NTP.begin("pool.ntp.org", 1, false);.


wire.h onReceive only triggering once I am writing a program to emulate a LCD driver chip (PCF8576) in a piece of equipment where I need to replace an unobtainable LCD display.

I have wire.h set up and the code in place to decode chip commands and load the segment data to an array.  That all works, and I can take that data and drive a new LCD just fine.

My problem is that the onReceive handler only triggers once.  To get it to be armed and trigger again I need to press the reset button on the Uno board.  I put code in to pulse an output pin and can verify with a scope that the onReceive only runs once.

When I just began the coding last week the handler would trigger each time the equipment would write to this particular I2C address, and I can tell the equipment is operating correctly since an Arduino reset will then result in the onReceive event triggering again.

Does anyone have any clue what's happening here?  I tried commenting out most of my code but it still won't trigger on each receive.  Obviously there's something subtle I changed that I'm missing, but what?

You are correct and that was the second part of the problem. The first part was that my code wasn't always retrieving every byte and this was hanging up the OnReceive function. Once I fixed that bug I found something very close to what you mentioned. On rapid device writes my handler routine didn't finish fast enough and thus could miss updates. What I did was to streamline the routine to take minimum time and that worked as the sending processor needed time between updates itself. In testing this works fine, what I did was to toggle a port pin and look at the I2C bus and that pin and could verify I was cleared out of the routine before the next update could come in. If it was close I would have gone to assembly for that routine but it turned out ok in this case. Thank you for your analysis!


Low-Pulse Occupancy and Voltage Divider I have a PPD42NS dust sensor I'd like to hook up to an ESP8266-01 microcontroller. The ESP8266 uses 3.3v logic, but the PPD42NS uses 5v. The PPD42NS uses low pulse occupancy as output.

I'd like to use parts I have on hand, and I was wondering if a simple voltage divider built from 2 resistors can reliably shift the voltage without distorting the signal.

If not, could an NPN transistor do the job instead?

While the PPD42NS has a 5-pin connector, it is shown at seeedstudio.com and howmuchsnow.com connected up with three wires: +5V, Ground, and an LPO or “Low Occupancy Output” signal, which goes low when a particle occludes an LED beam path.  LPO is used as an input to let sketches measure the fraction of time the beam's  occluded, which correlates with number of dust particles.

Yes, a resistive voltage divider will let you use the 0-to-5V occupancy signal as an input to your 3.3V-tolerant ESP8266.

What values of resistors should be used?  Because input pin capacitance is small (eg under 10 pF), signal "crispness" should be about the same over a broad range of resistances – say from a 100Ω+200Ω divider up past 1KΩ+2KΩ;  even 10KΩ+20KΩ might be ok.

The Grove_-_Dust_sensor.pdf data sheet at seeedstudio.com says:

  Output Method  Negative Logic, Digital output,
  Hi : over 4.0V(Rev.2) Lo : under 0.7V
  (As Input impedance : 200kΩ) OP-Amp output, Pull-up resistor : 10kΩ

This suggests (but doesn't clearly indicate) that some sort of open-drain output might be used.  If so, instead of using a voltage divider one could remove the 10kΩ pull-up on the sensor, and pull the output to 3.3 V instead of 5 V, via either an external resistor or using an INPUT_PULLUP pinmode setting (if available on the ESP8266).

Edit: Regarding the comment, “I'm considering use it in conjunction with an MCP23017 I/O expander IC. The GPIO pins on the chip appear to be rated at a max capacitance of 50 pF. Will that affect the range of resistors available? How does resistor choice affect the crispness of the signal, and how can I determine it for myself?”:

The “max capacitance of 50 pF” spec, which is parameter D101 in table 2.1 of the MCP23017 spec sheet, refers to “Capacitive Loading Specs on Output Pins”, ie, how much capacitance MCP23017 outputs can drive.  It doesn't refer to input pin capacitance, so isn't relevant here.

In general, when a signal edge (a rise or fall) arrives at an input pin, the input pin's voltage doesn't change instantaneously.  The input pin's capacitance needs to charge or discharge.  (It charges for a rising edge, discharges for a falling edge.)  The speed of change depends on the RC time constant of the circuit.  A delay occurs, probably 1–3 time constants long, before the pin starts to switch.  (The switch may take a few tens or hundreds of nanoseconds.)

For example, if input circuit capacitance is 10 pF and its effective resistance is 100kΩ, RC = 10 pF · 100kΩ = 10⁻¹¹·10⁵ = 10⁻⁶ seconds = 1 microsecond.  Whether that's large enough to matter for your measurements depends on how many time constants have to occur before the pin starts switching, and on how narrow the LPO signals are.

In short, compute RC, and if it's more than a few microseconds, use a smaller value of R.  Alternately, if you have access to an oscilloscope, attach it to the input and try various resistance values in the voltage divider, to get a feel for how the signals degrade as the resistors in the divider get bigger.

Note, using a voltage divider causes different RC values for falling edges than for rising edges.  For example, suppose an actively driven 0-5V signal enters a divider with 10KΩ in series with 20KΩ, and the 0-3.3 V signal is taken from the resistors' junction.  Then R is 10KΩ for a rising edge, and 20KΩ for a falling edge.  If the 0-5V signal weren't actively driven high, but instead pulled up via a pullup resistor R' when a transistor turns off, then the rising edge R value would be R'+10KΩ for this example.


/dev/cu port resource always busy on OS X 10.10 Is there any reason why is my /dev/cu port always busy? How can I fix that?

It happened on both Uno clone and Spark Core.

The problem is, I'm having issues doing serial communication. Where (as a programmer) I'm seeing something like dropped packets with /dev/tty port. I did a quick test running it on Win 7 (a loaner PC), it works fine...

The code for now is extremely simple. It waits for a command, and write a response.

String str = String(30);

void setup()
{
    Serial.begin(9600);
    str = "";
}

void loop()
{
    if (Serial.available() > 0) {
        char inChar = Serial.read();
        if ((inChar == '\n') || (inChar == '\r') || (inChar == 'z')) {
            str.trim();
            if(str == "READ") {
                String x = String(random(27, 45)) + "," + String(random(45, 300)) + "," + String(random(35, 250));
                Serial.println(x);
            }
            str = "";
        }
        else {
            if (str.length() < 30) {
                str += inChar;
            }
            else {
                str = "";
                str += inChar;
            }
        }
    }
}

Finally figured it out. I need to call Serial.flush().

  Waits for the transmission of outgoing serial data to complete.


Using millis(), in nested loops I am using millis() to flash some lights (neopixels) on an arduino pro mini. The problem is that I cannot flash the lights for the desired period. More specifically, the lights flash for ~250 ms, whereas I want to flash for 9 seconds! Here is a simplified version of what I am doing.

In loop(), I have a while loop (let's call it loop 1) that should run for 250 ms. Inside loop 1, I call a function flash(), that has to run for 9 seconds! I put another loop (loop 2) after loop 1, that would run for 3 seconds.

Here is the bigger picture...I actually want a radio to wake up for 250 ms. If in that time interval it receives anything, flash() will be called that will flash the lights for 9 secs. If it doesn't receive anything it will simply go to sleep for 3 secs, then come back alive for 250 ms, so on and so on

void loop() {
    previousMillis = millis();
    while (millis() - previousMillis < awake_interval) {  //awake_interval = 250 ms
        flash();  //flash for 9 seconds
    }

    previousMillis = millis();
    while (millis() - previousMillis < sleep_interval);  //sleep_interval = 3 secs
}

The flash() function looks like this,

void flash() {
    unsigned long x = millis();
    while(millis() - x < flash_time){  //flash_time = 9 secs
        lights_on();
        delay(t1);
        lights_off();
        delay(t2);
    }
}

I put loop 2 in there because without it the lights flash forever. This makes sense because all the code is in an infinite loop - void loop().

For debugging, I put serial prints after entering the loops. It seems that nesting two loops (in my case flash() inside loop 1), both of which uses millis() is the source of the problem. If that is true, how else should I do this? If that is not the problem, any ideas will be appreciated.

Edit: The suggestions made by @VE7JRO and @ratchet freak are neat but I was still having problems making my thing work. Turns out it was a problem with one my initializations. I am posting my whole code below (that uses LEDs). I guess I should post the correct code as an answer.

const long sleep_interval = 3000;
const long awake_interval = 250;
const int ledPin = 3;

const uint8_t flash_time = 9000;  //bug
const uint16_t t1 = 5;
const uint16_t t2 = 495;

void flash() {
    unsigned long x = millis();
    while(millis() - x < flash_time){
        digitalWrite(ledPin, HIGH);
        delay(t1);
        digitalWrite(ledPin, LOW);
        delay(t2);
    }
}

void setup() {
    Serial.begin(57600);
    pinMode(ledPin, OUTPUT);
}

void loop() {
    unsigned long x = millis();
    while(millis() - x < awake_interval){
        Serial.println("flash time!");
        flash();  //overflow will occur
    }

    unsigned long y = millis();;
    while (millis() - y < sleep_interval) {  //sleep_interval = 3 secs
        Serial.println("Sleep time!");
    }
}

Your logic is wrong. If you update previousMillis with millis() value in the first line, you are always subtracting the time difference between the the first and second lines of your code (which is the same you are doing in the loop inside flash()). If what you need is to get the time passed since the program started running, you need to have a fixed variable for that in setup() instead of updating it every time in loop().

Even so, I don't see why millis() is necessary in your case. Using delay() would be much more simple and still get the job done. Example:

void setup() {
delay(250);
}

void loop(){

    for(int i = 0; i < 9; i++){
        digitalWrite(LED, HIGH);
        delay(time);
        digitalWrite(LED, LOW);
        delay(time);

        delay(1000 - 2*time); //Delays the loop exactly one second per iteraction
    }

}


Notifications in constant loop (Blynk) trying to trigger along with serial function This is an extension from a previous thread that was getting lengthy and off the original topic. I have the following code which monitors the state of a float switch (high or low). I upload the sketch, turn on the serial monitor and manually move the float switch up and down. The serial monitor output represents what I'm doing with the switch. The issue is that I get a constant loop of blynk notifications, every 15 seconds or so. Furthermore, if i move the switch to it's low position, the first blynk notification i get is correct reading "low", the following notifications are "high" thereafter. When the switch is moved to the high position, blynk just loops stating it's "high". I know it's weird and took quite a while to even establish what is going on here. but the biggest issue is the loop of notifications every 15 seconds.

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

char auth[] = "710a4af9b1d82412fa477705bf642c634";
char ssid[] = "ssid";
char pass[] = "pwd";
int flag=0;
int floatSavedState = -1;      // initial float low state indicates not yet known

void notifyOnButtonPress()
{
  // pin D1 will be 1 if float has dropped due to low water level
  // pin D1 will be 0 if water level is high enough
  int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

  if (floatLevelLow && floatLevelLow != floatSavedState) {
       // send notification if this is first time or if the float level has
       // changed since the last notification.
       Serial.println("Resevoir Water is Low!");
       Blynk.notify("Alert : Water Level low.");
       floatSavedState = floatLevelLow;
  } else if (floatLevelLow != floatSavedState)
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;

}
void setup()
{
  // Debug console
  Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
  // Setup notification button on pin D1
  pinMode(D1,INPUT_PULLUP);
 timer.setInterval(16000L,notifyOnButtonPress);

}
void loop()
{
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
}

Your code:

timer.setInterval(16000L,notifyOnButtonPress);

Is calling this function every 16s.

This code:

if (floatLevelLow && floatLevelLow != floatSavedState) {

needs some parentheses to force your desired order-of-operations. As it stands now, you are asking the result of floatLevelLow && floatLevelLow and comparing if that is not equal to floatSavedState. That's likely not what you want.

Did you mean:

if (floatLevelLow && (floatLevelLow != floatSavedState)) {

EDIT:

Also, your if/else is missing brackets around the 2nd clause and should be:

} else if (floatLevelLow != floatSavedState) {
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;
}


Cheap weatherproof ultrasonic range sensor? What's an inexpensive ultrasonic range sensor that's reasonable waterproof or weatherproof that also interfaces easily with an Arduino?

I've used these kinds of ultrasonic range sensors, which are cheap and trivial to wire to an Arduino, but they're not very robust and are easily damaged since you can't cover them without that covering obstructing the soundwave.

Maxbotix sells a "Weather-Resistant" ultrasonic range sensor, but it's around $100, which is a little out of my price range.

I've researched those "parking sensors" used on cars, but I haven't seen anyone successfully interface them with an Arduino. It's also hard to tell how they're controlled. Some sites sell batches of the sensor for $3/each, but I don't think this includes the control electronics. Ebay listings that include what appears to be a bulky controller board seem to go for around $50-$100, which makes them a little pricey.

Those modules are just the ultrasonic transducers. You can see the two pin connector. You can probably get those cheap boards, de-solder the two transducers, and connect the wires from two of the water-proof ones.


Cannot access SD card on WINC1500 I have a WINC1500 shield and have the Wi-Fi side working fine. I want to do some datalogging to the SD card and am having trouble getting it running. I have bought a 16 GB Sandisk card and inserted it. I have added the SD library, SD.h is included. However SD.begin() fails. I have a Mega2560 card (from Elegoo) so should be able to run the SD and wifi at the same time? Do I need to pass a parameter to SD.begin()?

The code below always prints "Card failed to initialise, or not present".

if(!SD.begin())
{
    Serial.println("Card failed to initialise, or not present");
}
else
{
    Serial.println("Card initialised ok");
}

Do I need to pass a parameter to SD.begin()?

Yes, you need to pass the Chip-Select (CS/SS) pin number. What number depends on how you have it hooked up, the default is 10. (yours might be 4)

n.b. according to the docs a standard arduino can't use the WiFi, and the SD at the same time; presumably the mega has enough memory.


Coding for a stop button I'll like to code for a game, and it'll come with a stop option that allows the player to exit/restart the game.

How should I code for that stop button? Do I put it in a separate while loop under the void loop?

One of the easiest ways to restart your game is to use the inbuilt reset line. The Arduino Uno/Due/M0/101 has a physical reset button next to the USB connector. For some of the other baords like the Arduino Mega, it is closer to the chip in the middle of the board.

The reset line is held high by a pull up resistor. This button shorts the reset pin to Gnd, resetting the microcontroller.

Once reset, the microcontroller starts up again as if it has just been powered on. This has the advantage of saving on adding code to handle the game being reset.


Convert comma-delimited Arduino String of hex values to array of bytes My apologies if this is a naive question. How do I convert a String which has hex values to a byte array that has those hex values?
This:
String s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

Needs to be converted to this:
char test[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

I used the following procedure. It does convert it, however, each character is saved as a character as opposed to hex value:
unsigned int str_len = s.length() + 1;
char charArray[str_len];
s.toCharArray(charArray, str_len);

Any help will be appreciated. Thank you!

You only convert the String object to a char array. It need to further split the char array into substring, and then convert it to number.
To split the char array, you can use strtok() function in c++ to do the job.
There is no str conversion function that can convert "0xff" into uint8_t directly. However, as @rubemnobre mentioned strtol() can be used to convert a c string to a long (in Arduino, it is 4-byte number) and further cast into a uint8_t and store in a byte array.
String s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

// Convert String object to char array
unsigned int str_len = s.length()+1;
char charArray[str_len];
s.toCharArray(charArray, str_len);

uint8_t byteArray[7];
int i=0;

// split charArray at each ',' and convert to uint8_t
char *p = strtok(charArray, ",");
while(p != NULL) {
  byteArray[i++] = strtoul(p, NULL, 16);
  p = strtok(NULL, ",");
}

// Print the byteArray
for (i=0; i<sizeof(byteArray)/sizeof(char); i++) {
  Serial.print(byteArray[i]);
  Serial.println(", ");
}
Serial.println();


What is happening in this basic push-button circuit? In the example circuit below (Arduino Uno R3), what would the equation be to identify the amperage going into pin 2 when the button is pressed? What if I used the 3.3v on the arduino or a 9v battery instead?
What is happening to the input pin when the button is not being pressed? (I assume it's a guaranteed LOW state due to any current being sapped by the GND, yes?)
What would happen without the pull down resistor? A short when the button is pressed? What would happen without the ground being connected at all? Anything?
A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.
Sorry for so many little questions in this one question, but these are the kinds of things I'm not seeing addressed in most tutorials.

what would the equation be to identify the amperage going into pin 2 when the button is pressed?

Once the button has been pressed for more than a few nanoseconds the current will be 0 (or as near as).

Immediately the button is pressed the formula is  I(t) = dQ(t) / dt since the input pin is a MOSFET gate and as such is seen (in simple terms) as a capacitor.

  What if I used the 3.3v on the arduino or a 9v battery instead?

The same.

  What is happening to the input pin when the button is not being pressed? (I assume it's a guarangeed LOW state due to any current being sapped by the GND, yes?)

It is pulled down to ground by the resistor.

  What would happen without the pull down resistor? A short when the button is pressed? What would happen without the ground being connected at all? Anything?

The input will be HIGH when the button is pressed, and floating (initially HIGH) when released.

  A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.

The main concern with a pullup or pulldown resistor is the current it demands from the power supply when the button is pressed. If it's too low then you will be wasting current. If it's too high then the input may take a while to turn off when you release the button.  10K is a "good" value since it is a good balance between those two factors.

The current from the supply is calculated as I=V/R, so 5/10000 = 0.5mA.  Low power systems may choose a higher value (100kΩ, say) to reduce the current.


How to add the previous value to current value from sensor const byte interruptPin = 4;
void ICACHE_RAM_ATTR count();
void setup() {
  Serial.begin(115200);

  // Set up our digital pin as an interrupt
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), count, RISING);
}

void loop() {

}

void count() {
  volatile float rainrate = 3;
  volatile float rate;
  volatile float total;

  rate = rainrate * 0.1;
  Serial.println(rate);

Every time it tips, it returns 0.3.  How do I add the previous value(0.3) to a new tip, to make it 0.6, and save it into a variable.
Thanks!

Btw, you can make the volatile variables global, by putting them above void Setup.
To put the total (new) value, use:
total += <sensorValue>;

where <sensorValue> is a call to get the sensorValue (or the value that has the sensor value stored in it), but I cannot see that in your sketch.
total += 0.3;

is the same as writing:
total = total + 0.3;

The value right of the '='sign is copied (assigned) to the left part of the '=' sign.


Use MOSFET to Change Voltage With PWM Ok so forgive me for being an amateur but I'm having a situation that's driving me nuts.

I have a sensor that I have to cycle between +5VDC and +1.4VDC every 60 seconds. I'm using an ATTiny85 with the 8Mhz internal clock fuse set.

What I was hoping was to use a 2N7000 N-Channel MOSFET to control the cycling of the voltage. So my thought is to have +5VDC on the Drain and a PWM signal on the Gate with the + side of the sensor connected to the Source. I am thinking that using PWM and adjusting the duty cycle on the Gate will allow me to adjust the voltage that is seen at the Source but what I'm seeing is a variation of +1.4VDC @28% duty cycle and +3.6VDC at 100% duty cycle.

I can't figure out why +3.6VDC is the best I can do. The PWM is coming from PB1 on the ATTiny85 and the +5VDC is coming from the main voltage source that also feeds the ATTiny85. The current draw of the sensor is 140mA max.

Ok so I haven't had any luck using a BJT or a single component to perform this voltage change so I started on a different approach using two 1N7000, with one being in an inverter configuration.  My though is the pin from the MCU will go high, which will turn on both FET's, with one supplying 5V and the other sinking to ground.  When the MCU pin goes low, both FET's turn off, which stops the 5V flow and the sink to ground, which then will allow the path through a voltage divider into my sensor at 1.4V.  The issue I am having is the second FET is smoking, and by that I mean the sucker heats up like crazy and one even let the smoke out!  I cannot for the life of me figure out WTF I am missing in this configuration.  Here is the new schematic and Q1 is the FET that is smokin.

Using a N-type transistor as a high-side switch is inefficient unless you have some way of driving the gate above the positive rail. The most you can reasonably expect at the source is the gate voltage minus the gate threshold voltage, VGS(th). The typical threshold voltage of the 2N7000 as given in the datasheet is 2.1V, which means that it is a bit remarkable that you are able to get a voltage as high as you have (5V - 2.1V = 2.9V).

The way to fix this is to switch to a P-type transistor (and flip it around) since its threshold voltage is negative.


How do I connect Arduino to a Bluegiga112? I am a new user of Arduino (I have a Arduino Due) and also I am a new user of BLE112 (Bluegiga module 112)

My teacher told me to make the BLE112 advertisable and furthermore he told me to look for information about UART@115K. (The Ble112 he gave me came with wires already soldered to the selected pins: I'm assuming I only need to use those.)

PIN NUMBER [PIN NAME] for BLE112

    2         AVDD                    (Supply voltage 2-3.6V)
    3         AVDD                    (Supply voltage 2-3.6V)
    4        [P2_2]  DC- Debug clock  (DIGITAL I/O)
    5        [P2_1]  DD- Debug data   (DIGITAL I/O)
    9        VDD_USB                  (Supply voltage 2-3.6V)
    20        DVDD                    (Supply voltage 2-3.6V)
    23       [P0_5]  RXD(Rx)          (DIGITAL I/O)
    24       [P0_4]  TXD(TX)          (DIGITAL I/O)
    25       [P0_3]  RTS              (DIGITAL I/O)
    26       [P0_2]  CTS              (DIGITAL I/O)
    29        RESET
    30         GND

I put:

BLE pins [2,3,9,20]    to     3.3v pin of Arduino
BLE pin  [30]          to     GND pin of Arduino

Then I found a picture (attached at the bottom of this post) that describes that I should put CTS of BLE on RTS of Arduino and vice versa. Where is the CTS on an Arduino board? I think I have to program one of the Digital pins.

I tried some other connections. I put:

BLE pin 26(CTS)   to    Arduino random digital pin 32, and
BLE pin 25(RTS)         Arduino random digital pin 34.

BLE pin 24(TX)          Arduino RX pin 0
BLE pin 23(RX)          Arduino TX pin 1

I didn't connect DC(Debug clock), DD(Debug data) and Reset on the BLE112.

So then I found some more info on the web that if I use USART than I should use a wake up pin which is by the default P0_0(??) more about that in this PDF. (Search wake_up)

Now I should mention sleep mode Ble112 (there are three kinds of it) and I believe that the one I am after is MODE 3 (that means that it consumes the minimum (power) of them all)

I found some example named UART@115K

  UART@115k
  This example configures the BLE112 or BLE113 Bluetooth Smart module to expose the BGAPI protocol over UART interface with the following settings: 115200 bps, 8n1 and hardware flow control enabled. The power mode 3 is enabled in this example and the wake-up pin is configured to P0_0 pin (P0_0 button on DKBLE112
  and DKBLE113). When the power mode 3 is enabled the device will not be able to receive commands or data over UART unless the wake-up pin is asserted.

  The example uses UART in the pin configuration channel 1 and alternate 1, which is the configuration used in the DKBLE112 and DKBLE113 development kits.
  If you try this example with DKBLE112 or DKBLE113 make sure the UART interface is enabled and the device is NOT powered with a CR2032 battery as it’s not able to power up the level shifter or UART to USB converter.

  This is also the factory default configuration for BLE112 and BLE113 Bluetooth Smart Modules.

Source: https://bluegiga.zendesk.com/entries/22412436

The most popular way to establish communication between an Arduino (I've used a Duemilanove) and a BLE module (I've used BLE113 that's on a DKBLE113) is through UART.

UART is a two wire interface (don't forget the common GND) with one RX and one TX.
You can use the SoftwareSerial library to define your communication object on the Arduino.
In contrast, the BLE113 uses four. The additional two are RTS and CTS (Request To Send and Clear To Send).

However, you can configure the UART in two ways using hardware.xml:

Go to the <usart > tag and set flow = "false". This "disengages" the RTS and CTS allowing a traditional two wire interface.
Had you set flow = "true", you need to connect the RTS and CTS as well, which I had a big problem with, though the two are both digital.

Further, in hardware.xml, you need to disable sleep mode by including <sleep enable="false" /> within the <hardware> tag. This will solve all your problems.
If you intend to use sleep mode, you need to skip the previous step and instead govern the module's mode through the P0_0 pin. Moreover, there are additional definitions to be included in hardware.xml, which are documented by BG. These work nicely for the BLE112 too.

In my exercise, I'd established communication at 9600 baud. It worked the same way when I increased it to 115200 baud (this is a plus in the BLE113).


Copy one SD card to another I want to copy an SD card to another.

What is the best way to attack this problem?

Should i get two sd card shields?
If yes, is it possible to stack two together, or will there be problems with the interface protocols (SPI/I2C)?

It should be perfectly possible to do it. As long as the SD cards and shields play ball then there should be no problem from a hardware perspective.

From a hardware perspective you should be able to share the MOSI, MISO and SCK lines and just have separate CS pins per card.

However some SD card shields employ level translation that doesn't properly release the SPI bus when idle, and some cheap SD cards don't release the bus in a timely manner too.

From a software perspective though it may be a different matter. I am not sure how well you can run two instances of the SD classes at once on an Arduino.  You may be better off looking at FatFS instead which is far more flexible.

You have two strategies when copying cards, each of which has a different way of programming it.

Block copy the entire card: this involves reading a 512 byte block from one card and writing it to the other one.  This would be the most efficient from a resource perspective (you don't need to care about the contents of the card, so don't need any filesystem code), but if the card is not close to full it will be very inefficient from a runtime perspective. Also the two cards have to be the same size for it to work well.
File copy. For this you need much more complex code, but it you only copy each file from one card to the other. It's much better though if the cards don't have much data on them - also the cards can be different sizes.