text:
Need my code to do multiple commands when inputs are pressed
Hello all I am back again with another issue concerning a code for my job. The code I have been working on is meant to connect to a IP server where some options are listed and I can control the servo motor through there. The options listed are FORWARD, BACKWARD, STEP, and STOP. Each command makes the servo motor move a certain way but the problem I need help with is I need the edited the code to work with three input switches which when pressed in real time they allow the motor to make turns without the need of pressing any button on the server and so far the code is not working. They work with some LED lights which when the input switches are pressed also light up each input is paired with an output (LED) respectively and I tried to create a marker that when the input is pressed also says on the server that "LED1 is on" for example. Each input corresponds to an INPUT switch and each output corresponds to an LED light. The Pin variable corresponds to the motor. Here is the code in question:
#include <ESP8266WiFi.h>
#include <Servo.h>

const char* ssid = "RETProject";
const char* password = "mporfiri";

WiFiServer server(80);

int Pin = 16; // GPIO13
int var = 0;
int D1 = 5;
int D2 = 4;
int D4 = 2;
int D5 = 14;
int D6 = 12;
int D7 = 13;
int temp1 = 0;
int temp2 = 0;
int temp3 = 0;

Servo servoMotor;

void setup() {
  Serial.begin(115200);
  delay(10);

  pinMode(D1, INPUT);
  pinMode(D2, OUTPUT);
  pinMode(D4, INPUT);
  pinMode(D5, OUTPUT);
  pinMode(D6, INPUT);
  pinMode(D7, OUTPUT);
  pinMode(Pin,INPUT);
  //pinMode(LED_BUILTIN, OUTPUT);
  //digitalWrite(LED_BUILTIN, LOW);

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

  WiFi.begin(ssid, password);

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

  //servoMotor.attach(Pin);

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  temp1 = digitalRead(D1);
  temp2 = digitalRead(D4);
  temp3 = digitalRead(D6);
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request
  if(temp1 == HIGH) {
    digitalWrite(D2,HIGH);
    servoMotor.attach(Pin);
    servoMotor.write(90);
  }
  else{
    digitalWrite(D2,LOW);
  }

  if(temp2 == HIGH) {
    digitalWrite(D5,HIGH);
    servoMotor.attach(Pin);
    servoMotor.write(-90);
}
  else {
    digitalWrite(D5,LOW);
}

  if(temp3 == HIGH) {
    digitalWrite(D7,HIGH);
}
  else{
    digitalWrite(D7,LOW);
}

  int value = LOW;
  while (value = LOW); {
  if (request.indexOf("/LED=ON") != -1)  {
    //digitalWrite(LED_BUILTIN, HIGH);
    value = HIGH;
    servoMotor.attach(Pin);
    servoMotor.write(0);
    delay(1000);

  }
  if (request.indexOf("/LED=OFF") != -1)  {
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.attach(Pin);
    servoMotor.write(180);
    delay(1000);

  }
  if (request.indexOf("/LED=STP") != -1){
      var = 1;
      while(var < 10){
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.attach(Pin);
    servoMotor.write(90);
    delay(200);
    servoMotor.write(-90);
    delay(200);
    var=var+1;
    }
  }
  if (request.indexOf("/LED=STOP") != -1)  {
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.detach();
    delay(1000);
  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.print("Robot is now: ");

  if(value == HIGH) {
    client.print("Moving Forward");
  } else if(value == LOW) {
    client.print("Moving Backward");
  } else if(request.indexOf("/LED=STP") != -1) {
    client.print("Moving in Step");
  }else {
    client.print("Stopped");
  }

  if(temp1 == HIGH) {
    client.print("Led_1 is on");
  }else if (temp1 == LOW);{
    client.print("Led_1 is off");
  }

  if(temp2 == HIGH) {
    client.print("Led_2 is on");
  }else if (temp2 == LOW);{
    client.print("Led_2 is off");
  }

  if(temp3 == HIGH) {
    client.print("Led_3 is on");
  }else if (temp3 == LOW);{
    client.print("Led_3 is off");
  }

  client.println("

");
  client.println("<button>Move Forward </button>");
  client.println("<button>Step </button>");
  client.println("<button>Move Backward </button>
");
  client.println("<button>STOP </button>
");
  client.println("<Input>LED_1 ON </Input>
");
  client.println("<Input>LED_2 ON </Input>
");
  client.println("<Input>LED_3 ON </Input>
");
  client.println("");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
  }
}

P.S. I just edited the code to do the turns when the input is pressed for the third input it is supposed to make a random turn (either left or right the machine needs to decide on its own) and I am not sure how to write that in the code.

https://www.arduino.cc/reference/en/language/functions/random-numbers/random/

rewrite your code so that received commands and button presses are separated from actions being performed ... right now you use something like if received motorON then run motor and if buttonPressed then run motor ............ instead use something like if received motorON then set flag and if buttonPressed then set flag then take action depending on state of the flag if flagIsSet then run motor

@jsotola how would i write that in the form of code?

Your code will only do anything if a client has connected to it because of this line
if (!client) {
    return;
  }

Your physical button will never do anything on their own unless a client has connected and has sent some data.
For the random direction you use a line like the following to randomly pick a direction
int direction = random(0,2) ? 1 : 0 ;

your direction variable will be with either 1 or 0 randomly

random(0,2) ? 1 : 0 is a convoluted way to write random(0, 2).

Wow, you're right. hehe.


text:
Can I put a T-mobile sim card into the SIM800L Module?
I am trying to connect my SIM800L module to my arduino, but am confused what kinds of sim cards work. My phone currently is an IPhone XS, and I would like to take my tmobile sim card from there and put it into the module. I talked to a tmobile rep and they said my card could handle 2G devices. Would this work? Thanks!

why don't you try it first, then post a question if you have problems .... what does your question have to do with gps?

It might work but you'd be better off getting a 2G dedicated card.  Hologram.io has a developer card that is $5 and free 1MB / month or something.

Exactly what I am looking for, the cost looks great too. thanks!

source: Stack Exchange

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

sort: votes


text:
UPDATE: Fault in processing code - doesn't receive correct data from Arduino
I am receiving data from an LDR which I am inputting into processing. The data seems to be received to Arduino correctly and I have looked at the data being sent via the serial monitor and it all seems correct. However, the data that is being received in processing doesn't reflect the data received by the LDR so I think I have done something wrong here but not sure what as I am fairly new to this all. (Please see image for what is printing in the processing serial monitor).
Any help identifying where I have gone wrong would be so so helpful!
ARDUINO CODE
int rval=0;
int lightval;

//Recorded minimum and maximum values
int minval=0;
int maxval=950;

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

void loop()
{
  rval = analogRead(1);
  //Serial.println(rval);
  rval=constrain(rval,minval,maxval);
  lightval=map(rval,minval,maxval,0,255);
  //Serial.println(lightval);
  Serial.write(lightval);
}

PROCESSING CODE
import processing.serial.*;

Splash paintsplash;
Serial port;

float value=0;

void setup()
{
  size(600,600);
  smooth();
  background(255);
  paintsplash= new Splash();
  port=new Serial(this, Serial.list()[6],9600);
  //printArray(Serial.list());
}

void draw()
{
  paintsplash.display();
  paintsplash.splash();
  delay(200);

  if(0<port.available())
  {
    value=port.read();
  }

  println(value);

  if(value<=75)
  {
    fill(255,137,132);
  }

  else if(value>75 && value<=125)
  {
    fill(32,78,95);
  }

  else
  {
    fill(183,215,216);
  }
}

PROCESSING CLASS - PAINT_SPLASH
class Splash
{
  float x;
  float y;
  float size;

  Splash()
  {
    x=0;
    y=0;
    size=int(random(35));
  }

  void display()
  {
    //fill(255,137,132);
    noStroke();
    ellipse(x,y,size,size);
  }

  void splash()
  {
  float xcord=int(random(600));
  float ycord=int(random(600));
  pushMatrix();
  translate(xcord,ycord);

     for ( float i =3; i < 29; i ++)
     {
       float splashX = x + random(100);
       float splashY = y + random(100);

       ellipse(splashX,splashY,size-i,(size-i+random(3)));
     }

   popMatrix();
  }
}

Make sure the output you show belongs to the code you show. I doubt you have Serial.println(lightval); in the version whose output we see.

Sorry yes I had commented out Serial.println(lightval) when I ran the script and the letters are still there

Then edit the question to comment out that line. At the risk of repeating myself, please make sure the output you show belongs to the code you show.

You're sending your lightval twice - once as a textual representation of the number, and once as a character representing the lower 8 bits:
Serial.println(lightval);
Serial.write(lightval);

For example:
Q308
R304
Q306

If you take the 308 and AND it with 255 you get 52.  52 as an ASCII character is R.
So you print 308, including a newline, then you print "R".  Then you print 304, which would be 48 after ANDing with 255 - which of course is a Q.

Thank you so much for this! You were correct, I am now getting the correct values in the Arduino serial monitor!
I am now having trouble with the processing side of the code. If you can lend any more of your genius I would be very grateful!

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


text:
Plant irrigation system
I'm very new to the Arduino game I wanted to make a small auto watering system for my plants. I bought these items

5V 1 CHANNEL RELAY MODULE FOR ARDUINO PIC AVR DSP ARMB
9 VOLT BATTERY SNAP CONNECTOR B
ARDUINO UNO R3
CAMELION 9V BATTERY SUPER HEAVY DUTY
PIN TO HOLE DUPONT 40 PIN 30CM ARDUINO JUMPER WIRE 12 INCH
SOIL MOISTURE METER FOR ARDUINO.

I followed a video on youtube I attached the guys circuit diagram as well. After following instructions my pump wont turn on I also programmed it as well. Please help if anyone can show me how to rewire the device and codes or if I'm doing something wrong. Please help.
int Relay = 13;
int sensor = 8;
int val;
void setup() {
  pinMode(13,OUTPUT); //Set pin 13 as OUTPUT pin, to send signal to relay
  pinMode(8,INPUT); //Set pin 8 as input pin, to receive data from Soil moisture sensor.
}

void loop() {
  val = digitalRead(8);
  if(val == LOW)
  {
    digitalWrite(13,LOW); //if soil moisture sensor provides LOW value send LOW value to relay
  }
  else
  {
    digitalWrite(13,HIGH); //if soil moisture sensor provides HIGH value send HIGH value to relay
  }
  delay(400);
}

Those 9V batteries aren't ideal. They are low in capacity (don't last long), and can provide that much current. My guess is that the battery can't supply enough current to turn on the relay. Try removing the relay, and see if the led on pin 13 ('L' on the Uno) turns on/off based on the moisture on the sensor.

Hey thanks for replying. The 9v battery is for powering the uno. The lights turn on when i turn it on. The relay also shows the moisture sensor is working as the lights on it turn on and off when I dip it into a cup of water. I'll try removing the relay and see if that helps thanks alot. If you could share a circuit diagram I will happily follow it :)

It sounds like everything on the Arduino side is working. It might be that you wired to water pump/valve the wrong way.

How did you wire the output side of relay for the pump? You do know you have to supply power to it, right?-) If you have a volt-meter, check that the power to the pump is switching properly. If you don't have a volt-meter, get one.

@haresfur I figured that out this morning thanks tbo :) I had wired the relay with the pump wrong. Everything is working well now.

I've seen so much fake projects from "Viral science". I'm not sure whether he/she simply don't know what he/she does or if he/she simply tries to trap people. This project is a race condition itself ;-).
Besides your battery is empty. I don't think it is a big problem to use a 9V block battery, but Gerben is right, it won't do its job for very long. Have you thought about using a LiPo or LiOn Accu and a Solar loader?
There are worse things I see:
The sensor is powered by 3.3V but you read the ON/OFF signal with a 5-Volt Pin. That could be a problem, if there are other voltage drops that lead to a signal the PIN can not recognize as HIGH. Check the documentation of the moisture sensor and if it allows 5V use 5V to power it. All sensors I have found on Google have at least a range from 3.3 Volt to 5 Volt.
Check the current consumption of the relay. It must not draw more current than the Arduino PIN can provide (40mA for the UNO). And, don't use PIN13 to switch the relay. There are so many others and PIN 13 is connected to the onboard LED, which draws 10 - 20 mA on its own.

Note that it's supposed to be a relay module, which includes the driving transistor.

@EdgarBonet Yes, that's right. That's why I wrote "Check the current consumption of the relay." I don't know whether it is a MOSFET or a NPN, so the impedence might not be enough for a PIN13 that has to drive the on board LED also. And you are complete right: If it is a MOSFET even PIN13 would work.

@Peter Paul Kiefer thanks for replying! well that sucks lol I am thinking of using these batteries but i dont know how to connect them the 9v block battery is only for powering the uno device but I still haven't figured out how to connect the lion or lipo to the motor is there a way I could use rechargeable batteries and plug the uno directly into a dc power source without the use of any batteries. Or if you can help with a new circuit diagram and codes? I would appreciate it. Note all of the products I bought are Chinese apart from the uno.

@Nizammulk Important note: I recommend powering the sensor only during the measurement and then disconnecting the power supply (eg using a transistor). This significantly extends the life of the electrodes.


text:
How to integrate nRF24L01 to esp8266 nodeMCU?
I can't seem to integrate an nRF module to my nodeMCU.
I just want to verify my code but an error message keeps popping up
Below is the sketch:
#include <SPI_Class.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <ESP8266WiFi.h>
#define PIN_CE D4
#define PIN_CSN D3
RF24 radio(PIN_CE, PIN_CSN);

struct package{
  int id = 1;
  int location = 1;
  char timeStamp = "date/time"
};

typedef struct package Package;
Package data;

public int data1=data.id;
public int data2=data.location;
public char data3=data.timeStamp;

byte  address[][6] = "00001"

const char* ssid = "Jino";
const char* pass = "myinternet";

char server[] = "cdgresearch.000webhostapp.com";

WiFiClient client;

int led = 2;

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid,pass);
  pinMode(led,OUTPUT);
  digitalWrite(led, HIGH);
  delay(500);
  Serial.println("Connecting to: ");
  Serial.println(ssid);
  Serial.print("Connecting");
  while(WiFi.status() != WL_CONNECTED)
  {

    delay(1000);
    Serial.print(".");
  }

  delay(300);
  digitalWrite(led, LOW);
  Serial.println();
  Serial.println("Successfully connected to the network");
  Serial.print("NodeMCU IP Address: ");
  Serial.println(WiFi.localIP());

  delay(1000);

  radio.begin();
  radio.setChannel(115);
  radio.setPALevel(RF24_PA_LOW);
  radio.openWritingPipe(address[0]);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(9000);
  sendData();
}

void sendData(){
  Serial.println("Sending Data...");
  delay(1000);
  if (client.connect(server, 80)){
    WiFi.printDiag(Serial);
    Serial.println("Connected to server");
    client.print("GET /tag2.php?");
    client.print("incoming=Id ");
    client.print(data1);
    client.print("&incoming2=Loc");
    client.print(data2);
    client.println(" HTTP/1.1");
    client.println("Host: cdgresearch.000webhostapp.com");
    client.println("Connection: close");
    client.println();
    Serial.println();

    while(client.connected()){
      while(client.available()){
        Serial.write(client.read());
       }
      }
    radio.write(&data,sizeof(data));

    Serial.print("\nPackage: ");
    Serial.println(data1);
    Serial.print("Location: ")
    Serial.println(data2)
    Serial.println(data3)
    data1+=1;
    data2+=1;
    delay(1000);

  }

  else{
    Serial.println("Failed to Connect to server...");
    }

  client.stop();
  Serial.println("Disconnected from Server");
  while(client.status()!=0){
    delay (10);
   }
  }

and this error comes up in the console:

even if I use the #include, still this pops out

The library you're currently using probably doesn't support ESP8266, try using https://github.com/nRF24/RF24. Just as a preemptive measure to avoid issues: 1. Make sure you decouple the 3.3V output - an 1000uF electrolytic capacitor - to GND and + to 3.3V. 2. Do not use ribbon cables, duponts should be okay, soldered is best. 3. When in high noise environment (electric motors etc.) also add a ceramic capacitor to the power rail.

The error is because you don't have that library on your computer.  Correct?

@Avamander I edited the post, still, doesn't seem to work

@JeanoDuhaylungsod Use only one of the libraries at once. Open Examples->RF24->PingPair and build on that.

You also have to make sure your ESP8266 core is up to date. Boards manager allows you to do that.

Your error is: .../packages/esp8266/hardware/esp8266/2.4.2/libraries/SPI/src/SPI.h:1:23: fatal error: SPI_Class.h: No such file or directory...
You have some wrong SPI library there. The original folder packages/esp8266/hardware/esp8266/2.4.2/libraries/SPI doesn't contain src subfolder.

I reinstalled Arduino IDE and the libraries that I need, it works fine now. It must be because someone used my laptop and installed some rfid libraries which caused some problems in the libraries folders.


text:
Why is char being "extended" to an int?
I know I'm missing something so simple here, but I can't figure it out.
If I do char letter = 'A'; then letter = letter << 8, letter = 0, as one should expect, since we are shifting the bits "off the shelf" to the left.
But, if we do this:
char letter = 'A';

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

  int twoBytes = letter << 8;
  Serial.println(twoBytes, BIN);

}

void loop() {}

The result is 100000100000000, but why? << has precedence over =, so it should be bitshifting letter left by 8 first, then assigning that value (which should be 0) to twoBytes.

Isn't there an implication that it will work (for some definition of "work")? If you were expecting zero why not just write: int twoBytes = 0; - the fact that you didn't implies that you expect letter to be treated as 16 bits.

I just want to point out that although you posted it here, this is entirely a C++ question. The Arduino compiler is the GNU C++ compiler. Nothing "Arduino" about the way it treats code you write, with the exception of some pre-processing that the IDE does. See here for more details about that.

@NickGammon .....because I need letter to be in high byte of twoBytes, and I'm putting another char into the low byte of twoBytes. Even though the code I wrote worked, being the inquisitive person I am I realized it didn't make sense, hence the question.

This is a funny, non-intuitive rule of the C++ language called “integral
promotion”. Simply stated, it says that no computation is ever performed
on a type smaller than int: anything smaller gets implicitly promoted
to int as soon as it appears in an arithmetic or logic expression.
See Implicit conversions in cppreference.com (warnings: it's
hairy).

Thank you, I'll take it on faith! Would it be good practice to say int twoBytes = letter; twoBytes << 8; instead for clarity, or does it even matter?

I would say that, for an experienced C or C++ programmer, it may not really matter. For someone unfamiliar with these rules, anything that can make the code clearer is a good thing. You may also write int twoBytes = int(letter) << 8;, or you may stick with letter << 8 and add a comment.

In this sort of case, where you only want the right-most 8 bits I would personally "and" it, like this: int twoBytes = (letter << 8) & 0xFF;  Since you want the low-order byte, make it explicit.

I'm not sure how what you're saying is connected to what they're saying, but int twoBytes = (letter << 8) & 0xFF; is either complicated way of putting zero in twoBytes or potentially undefined behavior, depending on the value and system.

The OP was surprised that the result wasn't zero, so I was pointing out that if you are doing a shift (left or right) and you aren't sure how many bits are being retained in the result, then anding it would make it clear. I don't see how the results could possibly be undefined.


text:
Cannot instantiate a parameterized object inside of another class
I'm having troubles understanding the inner workings of classes and such.
I have a class called Attributes that contains parameters. In my .ino, I can simply instantiate an object with Attributes greenBark(1, 2); and everything is hunkey dorey.
Problem: Now I need to create a Attributes object in my other class, called Tree. I figured out if my constructor doesn't have parameters, I can create an object within another class just fine. However, my attributes class constructor has parameters. When I try to create an parameterized object within another class, the compiler tosses an error. How can I create an attributes object within my tree class? I'm sorry if I got some of these terms mixed up, I'm trying to keep up!
Here are my current files (made for this example:)
The .ino file
#include "attributes.h"
#include "tree.h"

Attributes greenBark(1, 2);

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

void loop()

{
  greenBark.printAttributes();
}

attributes.cpp
#include "attributes.h"
Attributes::Attributes(int size, int texture)

{
  _size = size;
  _texture = texture;
}

void Attributes::printAttributes()
{
  Serial.print("GreenBark Attributes: ");
  Serial.print("Size = ");
  Serial.print(_size);
  Serial.print(" Texure = ");
  Serial.print(_texture);
  Serial.println();
}

attributes.h
#pragma once
#include <Arduino.h>

class Attributes
{
  public:
    Attributes(int size, int texture); // constructor
    void printAttributes(); // method

  private:
    int _size = 0;
    int _texture = 0;
};

tree.cpp
#include "attributes.h"
#include "tree.h"

Tree::Tree()
{

}

tree.h
#pragma once
#include <Arduino.h>
#include "attributes.h"

class Tree
{
  public:

    Tree(); // constructor

    void makeTree(); // method

    // I want to create an attributes class object in my current class, so naturally I'd try to
    // create the object just like I did in my .ino sketch, but the below line doesn't work.

    //Attributes redBark(1, 2);

  private:
};

The error provided is this:
In file included from C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\ParameterizedConstructor.ino:2:0:
C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected identifier before numeric constant
     Attributes redBark(1, 2);
                        ^
C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected ',' or '...' before numeric constant
In file included from C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.cpp:2:0:
C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected identifier before numeric constant
     Attributes redBark(1, 2);
                        ^
C:\Users\ajrob\Dropbox\Projects\Electronics\Arduino Sketchbook\ParameterizedConstructor\tree.h:16:24: error: expected ',' or '...' before numeric constant

exit status 1

Compilation error: expected identifier before numeric constant

https://en.cppreference.com/w/cpp/language/constructor

@Juraj I read that page over a few times understanding what I could and I'm not seeing how it helps my situation

I don't understand much of it either, so I tried Attributes redBark {1, 2}; and it did not throw an error ... I have no idea if it does what you are expecting ... Attributes redBark {1}; and Attributes redBark {1, 2, 3}; both throw an error, so it might be what you want

@AJ_Smoothie your post is not Arduino specific, and really is a general programming question ... it belongs at https://stackoverflow.com/questions

@jsotola I tried the braces in my actual code (the parameters are input pins and default pin states) and it worked out just great. Thank you

I see two options here:
You might follow jsotola's comment and initialize redBark with braces:
Attributes redBark{1, 2};

For some reason, the syntax with parentheses is not allowed when
initializing an object in a class declaration, but the syntax with
braces is OK.
The other option is to initialize redBark in the Tree's constructor
(and not in the class declaration) using an initializer list:
// In the class declaration:
Attributes redBark;

// The constructor:
Tree::Tree() : redBark(1, 2) {}

Using the curly braces worked out just fine! Thank you!


text:
How many transistors can be connected to Arduino pins?
How many TIP122 transistors can I connect to the Arduino digital pins? The Atmega328p datasheet states that the pins can source a total of 200 mA, while other documents state 40 mA per pin.
In the following circuit layout, I connected six TIP122 transistors with 2.2  kΩ  base resistors. I used an LM338 regulator to power the Arduino IC and other functions.

I would use a N-channel MOSFET instead of the TIPwhatever.
AOD514 from Digikey has really low Rds, somewhere around 0.01 ohm, and can be driven from an Arduino pin, say thru a  150 ohm resistor to protect against the gate input capacitance of the MOSFET. A 10K pulldown resistor on the gate will hold the MOSFET off until the Arduino sketch starts up and controls the pin.
AOD514 is surface mount, but tab and pins are pretty good size and can be manually soldered.
AOD508 and AOD510 are even lower Rds, but cost a bit more at Digikey.

"In datasheet atmega 328p total arduino pin can source 200 ma of current or some saying 40ma current per pin."
Datasheet says 200mA per VCC and GND pin.  I personally confirmed that with Atmel Tech Support (before they were bought by MicroChip).
Absolute max per IO pin is 40mA, more than that and you risk damaging the pin.
Further, above 20mA a High output will begin outputting lower voltage, and a Low output will begin outputting a higher voltage. See Section 32 of the latest datasheet:
"Note: Stresses beyond those listed under “Absolute Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and functional operation of the device at these or other
conditions beyond those indicated in the operational sections of this specification is not implied. Exposure
to absolute maximum rating conditions for extended periods may affect device reliability."
and notes 3 and 4 under table 32.2:
"If IIOH exceeds the test condition (20mA at VCC = 5V, 10mA at VCC =
3V), VOH may exceed the related specification. Pins are not
guaranteed to source current greater than the listed test condition."
"If IOL exceeds the test condition (20mA at VCC = 5V, 10mA at VCC =
3V), VOL may exceed the related specification. Pins are not guaranteed
to sink current greater than the listed test condition."

I meant what I said. A higher load (more than 20mA) and a low output will start rising, and a high output will start dropping. Pretty sure that is caused by voltage created from current x Rds of the output transistors.

The TIP122 is a 100V, 5A, Hfe at least 1000, darlington NPN transistor. With the base resistor of 2k2, that is about 1 or 2 mA per pin. You don't have to worry about a few mA.
To answer your question: "How many transistor can be connected to arduino pins?", that will be about 100.
Why do you use TIP122 ? They have a voltage drop. Logic level mosfets have a very little voltage drop and thus they stay a lot cooler.
Mosfets leak at a higher voltage. If you need to operate near 100V, there are IGBT transistors for that.
Make sure that the high current through the TIP122 at the emitter does not disturb the GND of the ATmega chip. You have to design your circuit board to avoid such troubles.

Thank for your answers,in my design i want to switch 24v 200mA fans only. I think thisll not disturb gnd of atmega, is it right?? Or not..and what to do if ive to switch large current thru transistor?? Do you have any notes or web link of this,,plz share..

@NikhilP, I don't know a website. As far as I know, that is a common design rule. If you use a single power connector for both the atmega chip and the transistors, then you could keep those ground paths seperatated and only connect them at the connector.

Can you plz recheck my circuit diagram ,and suggest me where i can seperate ground line with atmega(highlighted line is ground line is GND line for mosfet as well as microcontroller)..Also plz check for other errors.  I am new in this field dont know desiging rules.i ve uploded complete circuit diagram above.

The emitter/ground current of the TIP122 can raise the ground level, and that will directly influence the working of the Atmega chip. The ground path of the Atmega chip is not going to the connector, but connects to the ground path which has the large currents from the TIP122 transistors. It will probably work. A grounding problem is more serious with high frequences. Just to be sure, I would split the ground from the connector into two paths, one for the Atmega chip and one for the TIP122 transistors.

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


text:
Need assistance with serial data between PC and Arduino Mega 2560
With help from a friend I have written a sketch for my Mega2560 that talks to a PC application via serial at 9600 baud.  The PC application send an S which instructs the mega to send variable values without any delimiters.  The PC application then creates a string from the data which is split to fill text boxes.  Some elements of these text boxes can then be changed and clicking a button makes the PC application build a string, prefixed by R# and using <> as delimiters.  It then tags an S on the end.  This string is then sent to the Mega, which as it detects the R and # reads the delimited data into a 43 element array. Once it reads the S it then runs the send function again to confirm the changes.
As a stand alone program this works -
I then added in functions for reading four Ds18B20's, four DHT11's an RTC and displaying this on a TFT.  These routines were added as separate contained voids and called in order from the main loop.  When testing the serial it nolonger works.  I either have to click on the get data button multiple times for it to read and display the info.  Sending updated information back gets lost in transit (I've used a com port sniffer and it shows data passing out to the mega).  Lastly, it's no longer accepting the updates when it does work - and having sent data back a second time it still reads the same as before the values were changed.  When the coms fails the mega seems to have locked up, so it's stuck in the comms section, presumably as one of the IF/Then conditions hasn't been met because it's run out of data.  But the routine wasn't changed from the standalone code which worked fine.
Hopefully this is as concise as you need but still has enough information to help diagnose the possible issue.  I've tried extending delays in the PC application to see if it was that which was the cause, but even setting them to 5 seconds it still errors as described
Thanks
Malcolm
Main loop from working standalone code
void loop ()
 {

loopcount = 0;

// Serial.println ("in main loop ");   // to show then program is looping the main code
// delay(3000);

 // your other 5seconds of code etc

 if(Serial.available()){             // test is S or R on comms

 int tbyte = Serial.read();

 if (tbyte == 'S'){
//  Serial.println ("send data");      // S received so Send data
  transmit ();
//   sendarray ();
   }

  if (tbyte == 'R'){                 // R received  so readstream of data
//    Serial.println ("recive data");
   readstream ();
    }
  }
 // sendarray ();
 }

 // end of main loop

Subroutines from the standalone code
// Subroutines --------------------------------------------------

 void readstream ()  {

  while (loopcount < 2000){
    if(Serial.available() > 0){

if  (serialFlag == 0) {

   inByte = Serial.read();

  if (inByte == 0X23 ){
    serialFlag = 1;
//    Serial.println ("# receieved so delimited data follows  ");
  }
}

  if  (serialFlag == 1) {
   processInput ();
    }
   }
  }
 }

// ProcessNumber-----------------

void processNumber (const long n)
 {
// Serial.println (n);

 dataIn[i]  = n;

 //Serial.println (i);
// Serial.print (dataIn[i]);

 i++;

// Serial.println (i);

 if ( i >= 43) {
//  Serial.println (" end of data....... return to main loop");
  serialFlag = 0;     // set flag back to zero
  i = 0;

 loopcount = 2222;   // stops the Serial While Loop, though better replaced by a timer
 }
 sendarray ();
 }

 // End of ProcessNumber-----------

 // ProcessInput--------------------

void processInput ()
 {
 static long receivedNumber = 0;
 static boolean negative = false;

 byte c = Serial.read ();

 switch (c)
   {

   case endOfNumberDelimiter:
     if (negative)
       processNumber (- receivedNumber);
     else
       processNumber (receivedNumber);

   // fall through to start a new number
   case startOfNumberDelimiter:
     receivedNumber = 0;
     negative = false;
     break;

   case '0' ... '9':
     receivedNumber *= 10;
     receivedNumber += c - '0';
     break;

   case '-':
     negative = true;
     break;

   } // end of switch
 }

 // End of ProcessInput------------------

And the input to array
void sendarray ()
{
daytemp1 = (dataIn[0]);
daytemp1=daytemp1/10;
daytemp2 = (dataIn[1]);
daytemp2=daytemp2/10;
daytemp3 = (dataIn[2]);
daytemp3=daytemp3/10;
daytemp4 = (dataIn[3]);
daytemp4=daytemp4/10;

<snip>

reduce the code to minimum required to demonstrate the error that you are getting .... remove all the useless fluff in the code and reduce it to receiving and recognizing the Q and S ... once recognized, have the code indicate which of the two was recognized .... do not do anything else until that part works

When you contacted me elsewhere you gave the impression your problem was simply how to convert incoming serial data into a variable rather than printing it. Please confine your question to this. In particular you need a Minimal, Complete, and Verifiable Example (MCVE).

But if I copy and paste the code into my code it keeps failing. Most often it fails to compile with error messages that might as well be in Klingon - maybe, but we can understand error messages. Please post them.

Please read How do I ask a good question?.

@MalcC - Is it possible to expand on what the timing issue was with the PC a bit more, if you think its something others might benefit from in the future.  (I think you should post an answer to this if you can)

@CodeGorilla not a problem.  My friend informed me that the code on the mega was taking around 4-5 seconds to complete the loop, so I added a 500ms delay between sending the R and the # in the PC application, and then added a 5 second delay after the string had been sent to the mega before the PC application sent the request to the Mega to receive data to confirm the values had been updated.  This prevents the PC application reading the buffer mid loop when the mega hadn't sent data to the com port

Prior I had used a PIC18F4620 running at 40 Mhz and didn't need such delays - maybe PICs handle communications differently, because on both projects the com port speed is set to 9600 baud, so data transmission is the same.

I'm sorry, I know you are new, but this is not a very easy to understand question, please keep reading though, I am trying to help.  Your description of what you want your code to do is like trying to eat a dinner plate.  Remember no one reading this has the knowledge of the problem that you do and a diagram or three speak a million words.
If it is failing to compile you need to post the source code and the compilation error.  Without that information there is no point posting the question.  The information on what is wrong is there, unfortunately you haven't used Google's Klingon to English translator.  Seriously paste the compile errors into Google and you will get a stack of results, some of which will tell you what you have done wrong.
Your friend's code is not great.  If that really is the code (rather than a space enforced edit), then I suspect it won't compile either, because its not valid C++.  Also there are logic errors in it, you can make a number negative, but once you have you can't go positive.
So, what can you do about it?
Rule 1: You have to learn how to walk before running around the globe.  Part of your requirement is to read Q or S from the serial line.  So write a program of YOU OWN that does just that (I mean don't copy one of a web site/friend).

Write a program that reads the serial line.
When you press Q it prints "You pressed Q!"
When you press S it prints "You pressed S!"
When you press any other key it prints "You pressed something else"
What happens when you press s or q?

Then build up step by step, keep back ups of everything, because you will break it at some point.
Other rules, which will contradict rule 1, will be available once you have mastered number one :)
Good luck and if you get stuck again, please post here again
 (small example code + error messages + output + expectations) = good post

How do I reply to a reply... other than hit the answer button, I have an update, but still have an issue - sorry for posting loads of info in previous post - Can't win as most forums ask for the full code and detailed explanation rather than just the bit where an error occurs

You can edit your question to clarify it. We don't want snippets of code, however your private email to me said I'm looking for a means of taking the numbers between the two delimiters and placing them into variables.. That sounds simple enough. Your posted question far exceeds that problem.

OK - I'll edit the original post

Problem resolved  by increasing delay in the PC application - please close / delete this post

@MalcC - I would keep open, because it makes a good point that  the Arduino isn't quite as quick as a PC and sometimes you can encounter issues because you forget that the Arduinos are running at <1% of the PCs speed.  (Well I never considered speed might be an issue anyway)

@CodeGorilla - that's a fair point.  If Nick or the other admin team feel the same then by all means leave it open.  As explained above when using a PIC at 40Mhz, the main loop is probably shorter and processing subroutines are quicker, which might have thrown me whilst porting it to the mega.  Anyway, I hope that it helps others who are writing PC applications to send and receive data from an arduino device.

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


text:
Preventing relay switch-off crashing Ethernet controller
I have an Arduino Uno with Ethernet Shield controlling some relays. Initially everything works fine but then when switching the relay off, the Ethernet controller frequently 'crashes'. Ethernet stops responding to pings, although the Arduino Uno keeps running. Pressing the reset button brings the Ethernet controller back to life.
I am using three relays to control:

The 'Call for Heat' contact on the boiler (normally connected to a thermostat)
A Honeywell V4043 zone valve (6W / 0.42A)
A Grundfos UPS2 underfloor heating pump (0.06A - 0.42A)

This is my setup:

I am using 2N7002 MOSFETs to drive the relays
I have 1N4004 diodes across the coils

There is a circuit diagram for the 'Relay Driver Shield' part of the circuit here:
https://github.com/njh/relay-driver-shield
This is what I have done to attempt to solve the problem:

I have moved the Arduino + Ethernet further away from the relays
I switched to higher quality Omron Relays (G2R-1-S-DC12)
I have tried both Wiznet W5100 and ENC28J60 Ethernet controllers

But so far nothing has solved the problem.
Of the three relays, it appears to be the Honeywell V4043 zone valve that is causing the problem. While testing with no loads connected to the relays, it was working fine. My assumption is that the problem is related to discharges across the contacts, partly due to the inductive loads. But I am not sure what to do to fix it.
Thanks,
nick.

I'd start with optocoupler and separate power supply for the relay.

Sounds like you want some relay snubber circuits. And opto-isolation can't hurt either.

I have added a Block Diagram inline and a link to the relay driver circuit diagram on GitHub.

a 3300uf 10v "motherboard"capacitor "shorting" your 5v to ground might help.

I would suggest two things:

Use opto-isolators instead of (or as well as) the MOSFETs to control the relays, and
Add RC snubber circuits across the contacts.

The latter is the most important, since the spark across the contacts when they open will cause massive amounts of EMI.
The simplest circuit is a simple series resistor and capacitor placed across the contacts:

simulate this circuit – Schematic created using CircuitLab
Of course, ensure that the resistor and capacitor are rated for at least the voltage you are switching, preferably double.
Selecting the right values for the components depends very much on the load being switched and how much energy needs to be absorbed. I have shown ball-park figures that are usually "ok" for many situations.

No. Those are to absorb the back-EMF from the collapsing magnetic field in the relay coil. The snubber circuit is for the back-EMF from the inductive load that makes a massive spark across the relay contacts, both shortening the life of the relay, and making a massive EMI spike.

Thank you very much, I will give the RC snubber circuit a go.
In a previous version of the circuit, a cheap eBay 4-channel relay board, it did have an opto-isolater, but it doesn't seem to help. Would isolating the power lines (DC-DC isolated converter) help?

Note that you need a mains rated capacitor. I think they are called class X capacitors, but please don't trust me on that one.

I bought some encapsulated RC RE12001 snubbers on eBay to protect the contacts on each of the relays. They are 0.01uF / 120Ω. Since fitting them, it hasn't crashed once :-) Thanks! I have uploaded a photo of it to GitHub.


text:
Creating a timer using a Real Time Clock with start and stop times
I have an Arduino Uno with a motor shield, as well as a DS1307 RTC that I am using to control 2 pumps.
Ideally I would like to set a start time (startHour + startMinute) and end time (endHour + endMinute) for each pump.
I have had luck using if statements to control my timer like below (adapted from Iain Foulds):
byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

byte startHour2=22
byte startMinute2=30
byte endHour2= 2
byte endMinute2= 45

void loop() {
  byte checkStartTime1() {
    DateTime now = RTC.now();
    // Read in what our current datestamp is from RTC
    if (now.hour() == startHour && now.minute() == startMinute) {
      validStart1 = 1;
    } else {
      validStart1 = 0;
    }
    return validStart1;
    // Return the status for powering up
  }
}

But my concern is that this only checks for equivalency at the moment, and if I lost power when my start time came up my pump would not come on. So I was hoping to set up an if statement that can deal with ">=" as opposed to just "==".
Which I can use if I only deal with the hour section:
if (now.hour() >= startHour && <= endHour)

But things get complicated when I try to add in minutes to the control structure. I end up with a series of nested for loops that do not work.
I'm hoping someone can help me write an if statement (or switch case) that can accommodate hours and minutes. So that any time between 8:15-14:20
validStart1=1

and anytime other time
validStart1=0

And please note the addition of the second set for this timer (StartHour2)- which I threw as my second pump will need to deal with the switch over past midnight.

May I know how to change this code working for midnight time range?
As an example, 23.30 to 01.30. byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20 void loop()
{ DateTime now = RTC.now(); // Read in what our current datestamp is from RTC if ( ( (now.hour()==startHour && now.minute()>= startMinute) || (now.hour()>startHour) && ( (now.hour()==endHour && now.minute()< endMinute) || (now.hour()<endHour) ) { validStart1 = 1; } else { validStart1 = 0; // }

I had a similar problem when i tried to control some heating source here at home.This was how I made my steps to get it working.
First I will assume you are using the library time.h and DS1307RTC.h (check here for info: https://www.pjrc.com/teensy/td_libs_Time.html).
Assuming that you will need 3 variables of the type tmElements_t.
tm will store your current time( the one you get from DS1307). The other two are auxiliary for defining time you start and time you stop the pump.
In similar way, you will need 3 variables of type time_t for the same reasons.
time_t variables store a the timestamps since 01/01/1970 (Unix epoch) which are easier to work with but tmElements structures are more human friendly.
tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

Now in your loop you need to get the current time from rtc:
time_t now = RTC.get();

after, use the breaktime funtion to convert the timestamp value to tmElements struture:
breakTime(now, tm);

Next step is to copy contents of tm to the other auxiliary structures, use the memcpy function:
memcpy(&tm_hour_start, &tm, sizeof(tm));
memcpy(&tm_hour_end, &tm, sizeof(tm));

after, change the the auxiliaries vars to meet your correct schedule of start and stop (are seconds important? if so, do similar way):
tm_hour_start.Hour = startHour;
tm_hour_start.Minute = startMinute;
tm_hour_start.Second = 0;
tm_hour_end.Hour = endHour;
tm_hour_end.Minute = endMinute;
tm_hour_end.Second = 0;

Ok, we have the more human friendly start and end structures, lets get the timestamps from them. To do soo we use the makeTime function that converts tmElements_t structures to time_t:
t_hour_start = makeTime(tm_hour_start);
t_hour_end = makeTime(tm_hour_end);

All you need to do now, is check if your current timestamp (now) is between this newly created timestamps:
if ((t_hour_start <= now) && (now <= t_hour_end)){
   //do something is soo...
}else{
   // do something if not...
}

Extra tip: In case your stop hour goes past midnight, add one more day to the timestamp:
if (startHour > endHour) //past midnight correction
   t_hour_end = t_hour_end + SECS_PER_DAY;

clean code:
#include <time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

// setup function and other needed things...

void loop(){
  //get current timestamp
  time_t now = RTC.get();
  // make current date and time structure
  breakTime(now, tm);
  // make auxiliary structures to be more human editable and friendly
  memcpy(&tm_hour_start, &tm, sizeof(tm));
  memcpy(&tm_hour_end, &tm, sizeof(tm));
  // change auxiliary structures to meet your start and end schedule
  tm_hour_start.Hour = startHour;
  tm_hour_start.Minute = startMinute;
  tm_hour_start.Second = 0;
  tm_hour_end.Hour = endHour;
  tm_hour_end.Minute = endMinute;
  tm_hour_end.Second = 0;
  // reverse process to get timestamps
  t_hour_start = makeTime(tm_hour_start);
  t_hour_end = makeTime(tm_hour_end);
  // check if end time is past midnight and correct if needed
  if (startHour > endHour) //past midnight correction
       t_hour_end = t_hour_end + SECS_PER_DAY;

  //final part
  if ((t_hour_start <= now) && (now <= t_hour_end)){
          //do something is soo...
  }else{
          // do something if not...
  }

}

EDIT: to correct the thing about midnight checks spotted in comments. New code:
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour = 8;
byte startMinute = 15;
byte endHour = 14;
byte endMinute = 20;

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now_, t_hour_start, t_hour_end;
boolean update_tm = 1;

// setup function and other needed things...
void setup(){};

void loop(){
  //get current timestamp
  time_t now_ = RTC.get();
  // make current date and time structure
  breakTime(now_, tm);
  // make auxiliary structures to be more human editable and friendly
  if(update_tm){
    memcpy(&tm_hour_start, &tm, sizeof(tm));
    memcpy(&tm_hour_end, &tm, sizeof(tm));
    // change auxiliary structures to meet your start and end schedule
    tm_hour_start.Hour = startHour;
    tm_hour_start.Minute = startMinute;
    tm_hour_start.Second = 0;
    tm_hour_end.Hour = endHour;
    tm_hour_end.Minute = endMinute;
    tm_hour_end.Second = 0;
    // reverse process to get timestamps
    t_hour_start = makeTime(tm_hour_start);
    t_hour_end = makeTime(tm_hour_end);

    // check if end time is past midnight and correct if needed
    if (startHour > endHour) //past midnight correction
      t_hour_end = t_hour_end + SECS_PER_DAY;
  }
  //final part
  if ((t_hour_start <= now_) && (now_ <= t_hour_end)){
    /* if we got a valid schedule, don't change the tm_hour structures and the
    respective t_hour_start and t_hour_end timestamps. They should be updated
    after exiting the valid schedule */
    if(update_tm)
      update_tm = 0;

    //do something is soo...
  }else{
    if(update_tm == 0)
      update_tm = 1;
    // do something if not...
  }

}

Thanks so much for such a well thought out, well explained, and well complemented code. But I do seem to be having an issue with the midnight correction. When I use the above code, when the clock strikes midnight my pumps stop. There seems to be some funky math going on when at midnight, so I even tried (SECS_PER_DAY*2) to make sure I'm well into the next day. But my pump is still shutting down at midnight. But other than this issue, the code works well

try to replace SEC_PER_DAY with the real number (24hours * 3600 sec per hour = 86400) to see if there is no buggy problem with that macro or something. The macro itself is defined in time.h (https://github.com/PaulStoffregen/Time/blob/master/Time.h).
Have you printed time_t variables t_hour_start, t_hour_end and now? Are they correct?

@Vinterwoo ignore my last comment, I think I figured it out, however I can not test it at the moment. I think the problem is we are constantly refreshing the 'tmElements_t' structures of 'tm_hour_start' and in 'tm_hour_end'. Once we past over midnight, this structures also will change and cause the failure (because the 'tm_hour_start.day' will reflect the change over new day). Once we get a valid start, we must fix this structures until turn off hour is passed. Check the edit

Gerben, thanks for your code. I took it and added seconds to the check, and tidied up a few typos. This isn't as sophisticated as other methods, but might be good for beginners to follow logic. hope it helps
#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

int openHH = 9;
int openMM = 10;
int openSS = 0;
int closeHH = 9;
int closeMM = 40;
int closeSS = 0;

bool isOpenTime()
{
  time_t t = now(); // Read in what our current datestamp is from RTC
//  DateTime now = RTC.now();  // if using timeRTC lib, i think

  int nowHH = hour(t); int nowMM = minute(t); int nowSS = second(t);  // put into local variables for easier read

  if ((
        (nowHH>openHH)                        // check hours first
        || ((nowHH==openHH) && (nowMM>openMM))             // check minutes if in same hour
        || ((nowHH==openHH) && (nowMM==openMM) && (nowSS>=openSS))    // check seconds if in same hour & minute
      )
      &&                                  // both conditions must be valid
      (
        (nowHH<closeHH)                       // check hours first
        || ((nowHH==closeHH) && (nowMM<closeMM)))             // check minutes if in same hour
        || ((nowHH==closeHH) && (nowMM==closeMM) && (nowSS<=closeSS)) // check seconds if in same hour & minute
      )
  { return true; } else { return false; }
}

  // usage
  if (isOpenTime) {
    // ... do something, eg open door
  } else {
    // ... do something, eg close door
  }

What you need to do is convert the time into some standard single number and then compare those numbers.
A popular method is to calculate the number of seconds since an epoch.  An epoch is an arbitrary point in time that you measure time since.  Microsoft chose 01/01/0000 for their epoch - Unix chose 01/01/1970.
The Time.h library contains functions for manipulating time values - one of the functions in it can convert a full date and time specification into the number of seconds since 01/01/1970 (Unix epoch).  If you want ideas then look at the source code for that.
A similar approach can be used to just work on the hours and minutes within a day.  One hour is 60 minutes, so you can create a number that is the number of hours multiplied by 60 plus the number of minutes in the current hour.  That will give you the number of minutes since midnight.  You can even add in the seconds if you want even more accuracy.
Once you have that single value it's very easy to compare it with a >=.

byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

byte startHour2=22
byte startMinute2=30
byte endHour2= 2
byte endMinute2= 45

void loop()
{
  DateTime now = RTC.now();  // Read in what our current datestamp is from RTC

  if (
    ( (now.hour()==startHour && now.minute()>= startMinute) || (now.hour()>startHour)
    && ( (now.hour()==endHour && now.minute()< endMinute) || (now.hour()<endHour) ) {
    validStart1 = 1;

  } else {
    validStart1 = 0;  //
  }

return validStart1; // Return the status for powering up
 }
}

Use the time in number of seconds total.
ontime=((sethour*60)+(setmin*60)+setsec);
offtime=((ofsethour*60)+(ofsetmin*60)+ofsetsec);
currenttime=((t.hour*60)+(t.min*60)+(t.sec);
if ((currenttime>ontime)&&(currenttime<offtime));
  {
  pumpon();
  }
else
  {
  pumpoff();
  }
delay(1000);

small correction ... one hour has 3600 seconds ... so ontime=((sethour3600)+(setmin60)+setsec);
offtime=((ofsethour3600)+(ofsetmin60)+ofsetsec);
currenttime=((t.hour3600)+(t.min60)+(t.sec);

A simple and effecient way is to use relative days and make use of the fact that the days, hours, minutes, and seconds are byte-sized data types that can fit into a single 32-bit data type.

byte 3
byte 2
byte 1
byte 0

Day
Hour
Minute
Second

This can be achieved with the following function:
constexpr uint32_t MakeTimestamp(const byte day, const byte hour, const byte minute, const byte second)
{
  // Pack the 4 individual bytes into a single 4-byte data type in order of precedence.
  return uint32_t(day) << 24 | uint32_t(hour) << 16 | uint32_t(minute) << 8 | uint32_t(second);
}

This 32-bit timestamp can be easily compared with other ones to test whether a timestamp is within a timespan:
bool WithinTimespan(const uint32_t& timestamp, const uint32_t& begin, const uint32_t& end)
{
  if (end < begin)
  {
    // Crossing midnight.
    return timestamp >= begin || timestamp <= end;
  }
  // Single day.
  return timestamp >= begin && timestamp <= end;
}

By using relative days to declare the motor start and stop times, the comparison takes care of the rollover to tomorrow:
const byte motor1_start_hour = 8;
const byte motor1_start_minute = 15;
const byte motor1_stop_hour = 14;
const byte motor1_stop_minute = 20;

const byte motor2_start_hour = 22;
const byte motor2_start_minute = 30;
const byte motor2_stop_hour = 2;
const byte motor2_stop_minute = 45;

const uint32_t motor1_start_time = MakeTimestamp(0, motor1_start_hour, motor1_start_minute, 0);
const uint32_t motor1_stop_time = MakeTimestamp(0, motor1_stop_hour, motor1_stop_minute, 0);

const uint32_t motor2_start_time = MakeTimestamp(0, motor2_start_hour, motor2_start_minute, 0);
const uint32_t motor2_stop_time = MakeTimestamp(0, motor2_stop_hour, motor2_stop_minute, 0);

Then the loop() is simply something like this:
void loop()
{
  const DateTime now = rtc.now();
  const uint32_t timestamp = MakeTimestamp(0, now.hour(), now.minute(), now.second());

  bool motor1_on = WithinTimespan(timestamp, motor1_start_time, motor1_stop_time);
  bool motor2_on = WithinTimespan(timestamp, motor2_start_time, motor2_stop_time);

  UpdateMotor1(motor1_on);
  UpdateMotor2(motor2_on);
}

I recommend you to read Majenko's answer


text:
Enabling pins of Arduino Due with direct port manipulation
I want to enable pin 13 on my SAM3X8E using direct port manipulation. On this chip the pin is bit 27 in port B, so I used PIOB->PIO_PER = 1<<27; to enable this pin, but it doesn't work. This pin keeps at 3.08V, the default value of non-initialized pins.
Here's my complete code:
#include <asf.h>

int main (void) {
  // Insert system clock initialization code here (sysclk_init()).
  board_init();
  sysclk_init();
  delay_init(sysclk_get_cpu_hz());
  PIOB->PIO_PER = 1<<27;
  PIOB->PIO_OER = 1<<27;
  while(1) {
    REG_PIOB_ODSR = 1<<27;
    delay_ms(1000);
    REG_PIOB_ODSR = 0<<27;
    delay_ms(1000);
  }
}

Can anyone tell me how I can get this to work?

I suggest the following test:  Use REG_PIOB_SODR = 1<<27; to set the bit, and  REG_PIOB_CODR = 1<<27; to clear it.  If that works ok, see about enabling synchronous data output via the port's PIO_OWSR register.  (If it doesn't work ok, perhaps review section 31.6, “I/O Lines Programming Example”, on page 629 of Atmel document 11057, the Cortex datasheet.)
Section 31.5.5, “Synchronous Data Output”, on page 623 says in part:

After reset, the synchronous data output is disabled on all the I/O lines as PIO_OWSR resets at 0x0.

I imagine that writes to REG_PIOB_SODR and  REG_PIOB_CODR should have effect after you enabled output by setting bits in PIOB->PIO_PER and PIOB->PIO_OER, which you did.  However, with the bit in PIO_OWSR being clear, synchronous data output isn't available, so writes to REG_PIOB_ODSR have no effect.

    #define Led_ON  REG_PIOB_ODSR |= 0x8000000
    #define Led_OFF REG_PIOB_ODSR &= ~0x8000000
    //for Arduino Due
    PIOB->PIO_PER |= 0x8000000;//led
    PIOB->PIO_OER |= 0x8000000;//led

And then call Led_ON and Led_OFF


text:
while(1) loop blocks program to enter interrupt
I want to build a program in C that enables / disables a passive matrix display. But my problem occurs before I can even implement one function of this display.
I have a simple switch connected to Port C pin 24, which is configured as INPUT with a pull-up resistor and debouncing input filter. When I toggle the switch the code enters an interrupt and toggles the "display" on or of depending on the state of the switch.
Everything works fine until I introduce a simple while(1) loop, which should handle everything I want to do. But every time I write the function called run, which only contains one while(1) loop and a single dummy operation __asm__("nop"), the while loop prevents the code from entering the interrupt.
This is my code:
void display_init(void) {
    sysclk_init();
    delay_init(sysclk_get_cpu_hz());
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk(ID_PIOC);
    NVIC_EnableIRQ(PIOC_IRQn);
    REG_PIOC_PER = SWITCH;
    REG_PIOC_ODR = SWITCH;
    REG_PIOC_OWDR = SWITCH;
    REG_PIOC_PUER = SWITCH;
    REG_PIOC_IFER = SWITCH;
    REG_PIOC_DIFSR = SWITCH;
    REG_PIOC_LSR = SWITCH;
    REG_PIOC_REHLSR = SWITCH;

    //Clear input change register to avoid immediate interrupt
    REG_PIOC_ISR;
    REG_PIOC_IER = SWITCH;
    run();
}

void run() {
    while(1) {
        __asm__("nop"); //Dummy operation for debugging
    }
}

void PIOC_Handler(void) {
    REG_PIOC_ISR;
    if(REG_PIOC_PDSR & PIO_PC24) {
        __asm__("nop"); //Breakpoint
    } else {
        __asm__("nop"); //Breakpoint
    }
}

As far as I know, an interrupt stops everything executed at the current time and starts working on the interrupt code. My question is now: Why is the interrupt not stopping the while loop?
Before I recognized this problem, I had a simple condition in the while loop that checks whether 1 or 0 to equals 1 when I set this state to 0, so the condition was 1 == 0 which should equal false. The loop did not stop and continued to run even if the condition for this loop was false... Is it possible that while loops do not like to be used in parallel with interrupts?
EDIT:
void main(void) {
    board_init();
    display_init();
}

I don't have an Arduino setup() function because I'm using Atmel Studio to ensure working at low Level, to avoid unnecessary code and to keep memory usage as low as possible.

This is not an Arduino question - you are not using the Arduino software framework or tools, and you are not using classic Arduino hardware.  Essentially what you have here is a software problem, in a more generic microcontroller context.

How do you even know if the interrupt is hit or not?   Also, consider the possibility that the interrupt was not being hit in the previous case, but the execution was falling through to it.

Is it possible that while loops do not like to be used in parallel with interrupts? Of course not. Do you think if you use interrupts you can't use while loops? You may as well not use for loops. It is impossible to answer without seeing all of your code. Please make a minimal example that demonstrates what you are talking about.

The while loop should have no effect on interrupts. Where does run() get called? We'll need to see the code that sets up and calls the code you've shown. But as a sanity check, you could try replacing the entire contents of run() with a ;, that is make it an empty function. Then add in an empty while loop (contains only a ;, no __asm__ code) and try again. Then replace the body of the while loop with __asm("nop")__ and try again. At which of the above steps does your interrupt fail? That should lead you in the right direction.
Update:
What does your main() function do after display_init() returns? Because that won't ever happen when run() runs forever.
The job of main() is to create the C/C++ run-time environment. That may not have been completed (enabling interrupts, for instance) when display_init() and run() get called, but gets completed shortly after they returns - if run() is allowed to end.
Without seeing your main(), we can't know enough to be more specific, but I'd suggest you move all of your code out of main() and down into the Arduino setup() function because, by the time it gets called, the run-time environment will be complete.
Update 2:

to avoid unnecessary code

If that is your entire main() function, you've left out the run-time environment setup and it's little wonder that your code behaves strangely. You've asked for help and we've made some suggestions: to show your entire code, not just selected pieces of it; and run your code in a standard way and let us know the result. Then you can optimize your code if you feel it's worth it to you. When you've done that test, and you still have questions, ask again. Until then, you're just asking us to guess. We did that. Once.

I call the run()method in the display_init() function at the top of my code. The init function is called by the main() function of the code. I tried it with an empty run() method. The interrupt worked as expected. But at the moment where I placed any type of while loop the interrupt fails. Even with an empty loop. Only if I replaced it with a while(0) loop it worked but with this the code is not working because it is not a loop anymore.

Sounds like interrupts aren't enabled. Bear in mind that an empty run() method is likely to be optimized away by the compiler.


text:
Basketball board arduino endlessly transmitting shot scored
I've been working on trying to get this arduino project I found to work but I've been encountering some problems.
The project was designed for an Arduino mega 2560 but I've been using my UNO and breadboard for it along with the Software Serial library. I'm very, very new to working with Arduinos so if there are any basic things I might be missing please do mention them.
Components:

Arduino UNO
Bluetooth HC-05 module
E18-D80NK Proximity Sensor
Saeed Grove 420 Proximity Sensor
10k Ohm resistor
Breadboard
The included app in the above link

The issues I'm facing are
a)Initially, the proximity sensor would detect if I e.g. moved my hand infront of it and send the data to the app and it would increment the score and play the sound.
However, if I tried flicking the vibration sensor and not moving my hand infront of the proximity sensor, a miss wouldn't be recorded. Initially, even just flicking the proximity sensor would record a score as well, but later it would just do nothing.
b)I'm not sure what is the problem, but now nothing happens at all. The wiring and everything is all connected in the same way as before, but now even though the proximity sensor lights up if I move my hand infront of it, no scores are transmitted by the HC-05 module or anything. I have tried keeping the Serial Monitor open but nothing is printed on it.
Also, the code I've pasted below is after including the SerialSoftware library header and after deleting all the code for setting the LED lights which is still available in the link above. Problem B started occurring before I did this, so I don't think that has anything to do with it. Just didn't want to include the LEDs in my project.
Any help would be really appreciated, thank you!! If there's any information I've missed out on, please let me know.
Edit: Okay, so I had the RX and TX wires of the module in the incorrect sockets. The RXD of the hc-05 module is now in pin 11 and the TXD in pin 10. Data is being transmitted, but it just endlessly keeps incrementing the shots even if the proximity sensor isn't detecting anything. :/ Any suggestions?
Edit2: Alright, issue resolved. I hadn't set the correct baud rate in the Bluetooth setup portion. Should've been 9600.
#include <SoftwareSerial.h>
SoftwareSerial Serial1(10, 11); // RX, TX

//----------------------------------------------------------------------------//
// Filename    : Scoreboard.ino                                               //
// Description : Smart Basketball Scoreboard                                  //
// Version     : 1.1.0                                                        //
// Author      : Marcelo Avila de Oliveira <marceloavilaoliveira@gmail.com>   //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// DEFINITIONS                                                                //
//----------------------------------------------------------------------------//

// TURN ON DEBUG MODE
// #define DEBUG
// #define DEBUG_PROX
// #define DEBUG_VIBR

//----------------------------------------------------------------------------//
// CONSTANTS                                                                  //
//----------------------------------------------------------------------------//

// PINS
const int prox_pin = 2;
const int vibr_pin = 3;

// TIME
const unsigned long wait_interval = 3000;

//----------------------------------------------------------------------------//
// VARIABLES                                                                  //
//----------------------------------------------------------------------------//

// TIME
unsigned long wait_time;

// STATUS
boolean prox = false;
boolean vibr = false;
boolean wait = false;

//----------------------------------------------------------------------------//
// FUNCTIONS (SETTINGS)                                                       //
//----------------------------------------------------------------------------//

void setup() {
    // INITIATE PINS
    pinMode(prox_pin, INPUT);
    pinMode(vibr_pin, INPUT);

    // INITIATE SERIAL COMMUNICATION
    Serial.begin(9600);

    // INITIATE BLUETOOTH COMMUNICATION
    setup_bluetooth();

    #ifdef DEBUG
        Serial.println("Board is alive");
        Serial.println();
    #endif
}

void setup_bluetooth() {
    #ifdef DEBUG
        Serial.println("Setting Bluetooth");
        Serial.println();
    #endif

    Serial1.begin(38400);                   // Set baud rate
    Serial1.print("\r\n+STWMOD=0\r\n");     // Set to work in slave mode
    Serial1.print("\r\n+STNA=Arduino\r\n"); // Set name
    Serial1.print("\r\n+STOAUT=1\r\n");     // Permit Paired device to connect me
    Serial1.print("\r\n+STAUTO=0\r\n");     // Auto-connection should be forbidden here
    delay(2000);                            // This delay is required.
    Serial1.print("\r\n+INQ=1\r\n");        // Make the slave inquirable
    delay(2000);                            // This delay is required.
    while (Serial1.available()) {           // Clear data
        delay(50);
        Serial1.read();
    }
}

//----------------------------------------------------------------------------//
// FUNCTIONS (CHECK)                                                          //
//----------------------------------------------------------------------------//

void check_prox() {
    if (!prox) {
        if(digitalRead(prox_pin) == LOW) {
            #ifdef DEBUG_PROX
                Serial.println("Proximity detected");
                Serial.println();
            #endif

            prox = true;
            if (!vibr) {
                wait = true;
                wait_time = millis() + wait_interval;
            }
            set_shot(1);
        }
    }
}

void check_vibr() {
    if (!prox && !vibr) {
        if(digitalRead(vibr_pin) == HIGH) {
            #ifdef DEBUG_PROX
                Serial.println("Vibration detected");
                Serial.println();
            #endif

            vibr = true;
            wait = true;
            wait_time = millis() + wait_interval;
        }
    }
}

void check_wait() {
    if (wait && millis() > wait_time) {
        if (!prox) {
            set_shot(0);
        }
        reset();
    }
}

//----------------------------------------------------------------------------//
// FUNCTIONS (MIS)                                                            //
//----------------------------------------------------------------------------//

void set_shot(int mode) {
    // MODE:
    // 0 = WRONG SHOT (MISS)
    // 1 = RIGHT SHOT (SCORE)

    Serial1.print(mode);
    delay(1000);
}

void reset() {
    vibr = false;
    prox = false;
    wait = false;
}

//----------------------------------------------------------------------------//
// MAIN                                                                       //
//----------------------------------------------------------------------------//

void loop() {
    check_prox();
    check_vibr();
    check_wait();
}

Alright, issue resolved. I hadn't set the correct baud rate in the Bluetooth setup portion. Should've been 9600.


text:
Generate number
I wanna make some sketch to generate number to represent sensor value, with range from high (900) to low (670), that number decrease with range between 1-10 and with some delay of switching number with range from 5-15 seconds:
    void setup() {
      Serial.begin(9600);
    }

    void number(){
      int sensor = 0;                  //sensor variable
      int a = random(0, 10);           //range subtraction sensor value
      int delay = random(5000, 15000); //range delay switching value
      for(sensor = 900; sensor >= 670; sensor -=a){ //iteration sensor value with range 670-900
        Serial.println(sensor);
        delay(delay);}
    }

    void loop() {
    number();
    }

with output:

900 (delay 7 sec)
894 (delay 3 sec)
988 (delay 5 sec)
979 (delay 9 sec)

The sketch above was work as well, but i still can't using variable "sensor" result after iteration "for" in void loop.
I hope you can help me, thanks.

upvote for well presented question ... this is a programming question, so the c++ tag is valid, but the other 4 tags are not valid ... it is not completely clear what you are asking, but that appears to be because of language difference

i just wanna generate random number, with range, maybe had another alternative sketch?

To use the for() loop iteration variable after the end of the loop, it has to be defined outside of the loop. Defining a variable in the loop is a convenience for when you only need it inside the loop.

how to upvote? so i need to make variable utside the loop?

int sensor = 900;                 //variabel sensor

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

int number() {
  int a = random(0, 10);          //range pengurang nilai sensor
  int d = random(500, 1500); //range delay perubahan nilai
  if (sensor < 670) {
    sensor = 900;
  }
  sensor -= a;
  delay(d);
  return sensor;
}

void loop() {
  int val = number();
  Serial.println(val);
}

I modified the delay for test.
randomSeed ensures different random values at every run
EDIT: a not blocking version which returns the same values for random interval:
int sensor = 900;                 //variabel sensor
unsigned long nextChangeMillis = 0;

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

int number() {

  if (millis() < nextChangeMillis)
    return sensor;

  int a = random(0, 10);          //range pengurang nilai sensor
  int d = random(500, 1500); //range delay perubahan nilai
  if (sensor < 670) {
    sensor = 900;
  }
  sensor -= a;
  nextChangeMillis += d;
  return sensor;
}

void loop() {
  int val = number();
  Serial.println(val);
}

@Juraj Why did you kind of copied my answer? Btw, you don't need to return sensor in number(), since it's a global variable anyway.

@MichelKeijzers, your function returns only the last value. the function number() should simulate values returned from a sensor

@Juraj ... thanks ... I thought that was the intention, but I guess the question was not so clear. Upvoted!

@UlinnuhaLuthfi (I removed my answer, this answer should answer your question already.

and when in practical, analog port A0 was used actual sensor, can i switch value from random seed with constant value?

@UlinnuhaLuthfi, not constant. you would get always the same 'random' sequence

sorry everyone, i just realize how to upvote

To "hide" the variable sensor you could put it inside number() and make it static. This way it's clear that no-one is allowed to access it.

@thebusybee, yes I know. but then I would have to explain it

thanks a lot guys, that sketch was work well, but i get some problem again, when sketch running, range delay 5 sec-15 sec its way too big, and interrupt all system, is there any alternative ways to replace "delay" function?

@Juraj, thank you

you're so fast responed dude, awesome

@UlinnuhaLuthfi, I realized that a sensor would not block but return the same value so I added the improved version some hours ago before your request


text:
Unreliable communication with low baudrate on Leonardo
I am using an Arduino Leonardo (more precisely this product), to communicate with servo-motors) using RS485.
Everything works fine as long as I don't go below a baud rate or 115200bps. If I go below, as 57600 or 9600, I start to get ill-formed packets from my motors: the 4 first bytes are usually correct, but the end of the packet contains incoherent data, and the checksum is obviously wrong.
I am using IndustrialShields (my PLC/Arduino vendor) library for RS485, and I don't see any mention of this problem.
I am using Half-duplex communication, with U2X if I correcly understand the source code of the library.
Note that the documentation of the servo-motors mentions there is a small error margin on the clock for low baud rates, but since it works with 115200bps, which has the highest error margin, it shouldn't be a problem.
Also the motors seems to understand the packet I send, but I do not receive their packet correctly.
Is there an edge-case I am not aware of? Sorry for the lack of details, I am not sure what else I can say.

Are you using half or full duplex mode?

Half-duplex with U2X. Edited to add some details.

115200 has the lowest error margin. You see the minus sign before it? ;-) Ok, now seriously: How do you setup the servos for the lower baud rates? How do you write into the baud rate register? How many servos do you use? Do you set the BR register on all of them? Did you daisy chain them or do you use a controller per motor? Your code would also be helpful. And, if you daisy chained them, how did you realize the feedback connection? A picture of your setup could also show us the connections you have made.  Switching the direction fur halve duplex could be problematic  ( @Majenko ! ).

I use 3 daisy-chained motors and 1 controller. I can write to the baud rate register using the servos protocol (http://emanual.robotis.com/docs/en/dxl/protocol1/). Fortunately they still get my packets right, so I can switch them back to an higher baud rate.
As far as I understand, the feedback is handled by timing, I wait 2 milliseconds every time I expect the servos to reply. They are configured to wait 200µs after the end of a packet before replying.
I could link my code, but there is a lot of code between my Arduino setup() and loop() and the library I am using to communicate.

Ah, now I got an idea of what is going on. The Direction is set by the servo itself. You mentioned that you use U2X with halve duplex. I know U2X as a mode where the transmission speed is doubled. Could it be possible that the baud rate is double when the servo answers to your communication but not when you send to the servo. I've not found out where you can switch of the U2X behavior and I'm also not sure that U2X means what I assume. But the theory would fit perfectly to your observations. Sending works, but you received weird data (like the wrong baud rate).

Of cause you can say, why does it work with 115200 baud. I don't know. Perhaps U2X is switched off from 115200 and above. ?? Have you an Oscilloscope to check if I'm wrong or not?

I do not have an oscilloscope with me. I'll try to turn off the U2X in the source code of the library if I find where (probably in avr/cores/industrialshields/HardwareSerial.cpp, in the library http://apps.industrialshields.com/main/arduino/boards/industrialshields-boards-avr-1.0.0.tar.bz2). I just switched to another topic, so I cannot test before a few days :/
Thank you for your attention!

I suspect that the RS-485 interface in your servo is what is at fault.  Nothing to do with the Arduino or your communication, or software.
Without knowing more about the servos and how they are wired internally it's hard to be certain, but I can assume:

The servo has some kind of controller in it which communicates over the bus
That controller may or may not directly control the direction pin on its interface

It's the latter that is critical. There is a way of wiring up a MAX485 that automatically controls the direction pin - immediately you start sending data it asserts it into TX mode. The trouble comes when switching back to RX mode - there's a few ways of doing that:

Shortly after the last bit of a certain value (0 or 1) has been sent (the bit stream keeps a capacitor charged)
A certain time after the start of communication.

The first method is usually more reliable across multiple baud rates, but can be sensitive to the values of the bytes sent - if it relies on a 1 being sent to keep the capacitor charged and a number of 0 bytes are being sent it won't see the 1 that keeps the transmit mode open, and it can close prematurely.
The second method is more reliable for fixed length packets, but will only work for a certain (or small range) of baud rates. If sending a packet takes longer than the allotted window then it will truncate regardless.
However if the controller in the servo is itself directly controlling the data direction pin then it could be that there is a bug in its firmware. Maybe it's working on a delay principle and they got the time calculations wrong.  Maybe it's working on a "queue being empty" principle and they forgot about there being a hardware buffer that also needs to empty, but high baud rates just manage to squeeze through in time.
It's impossible to be sure, but going by the symptoms you describe those seem to be the most logical scenarios.


text:
Esp8266 -12E v3
So I have this ESP 8266 v3 board that has a program. Running on it currently, it’s the example scan Network Program. No matter what program I send to it now I get a error complaining for board NodeMCU 1.0 (ESP-12E).
I have checked to assure that the com port is correct and is showing upload 11500 , cpu 80 MHz, flash size 4M, debug disabled. Debug level - none, iwip v2 low memory
Viable”flash”, exception enable, erase flash only sketch
Port 6 .
   Arduino 1.8.8 Windows 10
In error box print in red
Board nodemcuv2. (platform, esp8266, package edp8266 is Unknown.
Error compiling for board NodeMCU 1.0 (ESP-12E Module)

Used this board a few times without an issue, now no matter what I try it maintains the current scan program and I am unanticipated compile or upload to the board. Is it stuck in some sort of loop or what? Any help would be appreciated, thanks

Sorry for typos here, should read I am unable to compile or upload any program. I tried and when I opened the serial window it showed my network being scanned. Thanks

go to Board Manager in IDE and reinstall the esp8266 boards package

why are you posting a comment about the typos, instead of correcting the typos?

I am unable to compile - then the issue is not with the hardware ... package edp8266 is Unknown ... what is this package edp8266 - looks like an obvious typo, but is that typo yours (i.e. you typed it wrong here) or is that the actual message you are getting


text:
IF statement inside of a function call? Code help
I was browsing a library for steppers motors when I ran across this line of foreign-looking code:
digitalWrite(enable_pin, (enable_active_state == HIGH) ? LOW : HIGH);

Is this some kind of shortcut to tossing an if statement into a function call? I've never seen this before. What exactly does it do, and what is this particular arrangement of code called?
Thanks!

Google something like "C++ ternary operator". There are many good explanations for that operator online

It could probably have been shortened to this instead:
digitalWrite(enable_pin, ! enable_active_state ) ;

You could look at this as an "if expression", the correct term is "conditional operator" (C++ standard chapter 8.16). Many know it as "ternary operator" because it has three operands. You might already know the "unary operator" with one operand like the negation sign -x, or the "binary operator" with two operands like the addition a + b.
This expression consists of:

the first operand
the operator ?
the second operand
the operator :
the third operand

The first operator is evaluated and converted (if necessary) into a boolean.
If the result is true, the second operand is evaluated and gives the value of the expression.
If the result is false, the third operand is evaluated and gives the value of the expression.
Only one of the second and third operands is evaluated. This is important, if you use operands with side effects, like function calls can have.
This operator is often frowned upon. If used excessively, the source becomes easily unreadable. Many professional code style guide prohibit its use for this reason.
In your case it could have been written more clearly as
if (enable_active_state == HIGH) {
    digitalWrite(enable_pin, LOW);
} else {
    digitalWrite(enable_pin, HIGH);
}

It outputs the inverted value of the variable enable_active_state at the pin enable_pin.
Experienced Arduino users know that HIGH and LOW are represented in a way that are compatible with boolean values. Boolean inversions can be simpler expressed with the logical negation operator:
digitalWrite(enable_pin, !enable_active_state);

Anyway, the current compilers are commonly smart enough to generate the same machine code for each of the variants. Therefore, please write your source in the best way to express your intention. Anything else is "premature optimization", which is a bad thing. But this is a completely other topic.


text:
Arduino Modbus Master code to read data using arduino uno from EB meter
I am using DC energy meter as slave.When I am testing DC energy meter using Modbus tester tool,its showing value from 1 to 24 register.I am using my own atmega328P with on board RS485 as a master device.I have connected A,B from slave to mater board.Now,I want to read slave outputs using my master.For that I have written below mentioned code.when I am serially printing array,its showing 00000000000000000000000000000000769.I am not getting full data on my master.
#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[64];
uint8_t u8state;

int i;

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0,0,1); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram;

unsigned long u32wait;

void setup() {
  master.begin( 9600 ); // baud-rate at 19200
  master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
  u32wait = millis() + 1000;
  u8state = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    telegram.u8id = 1; // slave address
    telegram.u8fct = 3; // function code (this one is registers read)
    telegram.u16RegAdd = 1; // start address in slave
    telegram.u16CoilsNo = 24; // number of elements (coils or registers) to read
    telegram.au16reg = au16data; // pointer to a memory array in the Arduino

    master.query( telegram ); // send query (only once)
    u8state++;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 100;
    }
    break;
  }
 //au16data[4] = analogRead( 0 );

 for(i=0;i<=64;i++)
 {
  Serial.print(au16data[i]);
 }
 Serial.println("\n");
 Serial.println("\n");
 delay(1000);
 }

source of the library? shouldn't you print the data only if it is received in case 2?

source of the library means #include <ModbusRtu.h> right?.So how to receive the polling data on master.

there is no ModbusRtu library in Library Manager. so from where do you have the library?

I have downloaded this source code with library from Github .I have mentioned URL on below. https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino/blob/master/examples/advanced_master/advanced_master.ino

Modbus (0,0,0)  last argument I have changed as 1,because we are usin RS485 and My slave device of A,B is connected on my Master controller of MAX485 and Max is communicated with Atmega328P with the help of software serial.Pin is 8,9

when I am measuring voltage on my MAX485 IC on pin A ,it giving 1.09V and B its showing 3.89 V

in simple_master example the author forgot to print the received data, but in the software serial example he prints them in if (master.getState() == COM_IDLE) {

Now I have uploaded software serial master example code on my master controller.I am using external Rs485(D+,D-,Gnd) to TTL board(RX,Tx) for communicating the slave device.I have changed only the software serial pins 8(Rx),9(Tx).I have connected my TTL output on software serial pins (rx-rx,tx-rx viceversa).Even though its printing  '0' on serial terminal.I have tested RS485 to TTL its working fine and when I am testing the salve device in Mtester ,it contains 5453 value on 40001.So how to resolve

can you check the function code on software serial master example.They have mentioned 4 instead of 3.

I have changed the function code as 3,software serial pins,no of register need to read .I can able to read all slave response serially on my modbus master controller.Thank you

The response is received when ModbusRtu library object is again in the IDLE state after a request was sent. In your code based on the example from the library, the response is ready in state 2 which follows state 1 where the request was sent. If in state 2 when the master object state changes to IDLE, you can use the response in array au16data.


text:
Using Modbus TCP server on Arduino
I have a scd30 sensor wired to an Arduino Uno. The scd30 works on the I2C protocol. I am able to read data live on the serial monitor on the Arduino IDE. I have an ethernet shield on my Arduino. I would like the Arduino to communicate with a field agent which will upload the data to the internet.
I have tried numerous modbus TCP libraries and dont seem to be getting anywhere. I can connect my arduino to the field agent but whenever it sends data I get a 0x02 exception code - Illegal data address. This is the library I'm using https://github.com/andresarmento/modbus-arduino/tree/master/libraries/ModbusIP/examples
I believe the right way to go about it is through holding registers but im not sure how to do this when using I2C. The connection is fine, the problem is the format. Any help is appreciated thanks.
/*
  Reading CO2, humidity and temperature from the SCD30
  This example prints the current CO2 level, relative humidity, and temperature in C.
*/
#include <SPI.h>
#include <Ethernet.h>
#include <Modbus.h>
#include <ModbusIP.h>
#include <Wire.h>
#include <Streaming.h>
#include "SparkFun_SCD30_Arduino_Library.h"

SCD30 airSensor;
//Modbus Registers Offsets (0-9999)
const int SENSOR_ISTS = 100;
//ModbusIP object
ModbusIP mb;
long ts;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  Serial.println("SCD30 Example");

 // The media access control (ethernet hardware) address for the shield
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    // The IP address for the shield
    byte ip[] = { 000 , 00,0, 00  };
    byte gateway[] = { 0, 0, 0, 0 };
    byte subnet[] = { 255, 255, 255, 0 };
    //Config Modbus IP
    mb.config(mac, ip,gateway,subnet);
    // Add SWITCH_ISTS register - Use addIsts() for digital inputs
    mb.addHreg(SENSOR_ISTS);
  airSensor.begin(); //This will cause readings to occur every two seconds

}

void loop()
{

mb.task();
   mb.Hreg(SENSOR_ISTS, digitalRead(airSensor.getTemperature()));

}

Don't cross post. You already asked this on SO.

The ModbusIP library expects from you that you supply the value of the register. The AirSensor library gives you that value.
Set the register value to Hreg:
mb.Hreg(SENSOR_ISTS, airSensor.getTemperature());

I tested your sketch without the sensor library and it is working. Client was my java test client I use to test access to Modbus TCP registers of my photovoltaic system.
Make sure that the client calls "0x03 - Read Holding Registers" and test address 100 and 101 because some modbus clients offsets are 1-based.

It doesnt seem to work. The code compiles well but I dont think it actually stores them. Do you know of any other libraries that can store in registers to modbus tcp?

and how do you reed it? what is your Modbus TCP client?

Its a field agent that does this. The field agent reads the registers of the arduino or should read it if the arduino is configured properly

what software is used by field agent? some modbus clients offsets are 1-based, so a register configured as 100 in library should be 101 in this software.https://github.com/andresarmento/modbus-arduino/blob/master/README.md

its a modbus slave. dont know the exact software. Tried changing it to 101 and still get the same error. ILLEGAL DATA ADDRESS

and it is configured to call "0x03 - Read Holding Registers"?

im not sure how to do this

You could try "0x04 - Read Input Registers" with Ireg.


text:
Touch Sensor and Potentiometer - Need some help
I'm using an Arduino Nano with a capacitive touch sensor and a potentiometer. I'm trying to get my code to differentiate between three different program states.

One is when my touch sensor is NOT being touched.
Two is when my touch sensor IS being touched.
And three is when my touch sensor is being touched AND a potentiometer is being moved at the same time.

I'm having trouble picking up the second program state, when I'm simply touching the fader but not moving the potentiometer. Program state 1 works great, but program state 3 activates even when there's no data coming in from the potentioeter.
Here's the code. And ideas?
#include <CapacitiveSensor.h>
#define rxPin 4
#define txPin 1

const byte touchSend = 2;
const byte touchReceive = 7;

byte minimumCp = 200; // Raise if the fader is too sensitive (0-16383)

bool touched = false; //Is the fader currently being touched?

CapacitiveSensor touchSensor = CapacitiveSensor(touchReceive, touchSend);

void setup() {
  touchSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);
  pinMode(rxPin, INPUT );
  pinMode(txPin, OUTPUT);
  Serial.begin(57600);
}
void loop() {
  int faderPos = analogRead(A7);
  int lastfaderValue;
  int totalCp =  touchSensor.capacitiveSensor(30);
  if (totalCp <= minimumCp) {  // Not Touching Fader
      touched = false;
      Serial.println("Not Touching Fader");
      delay(15);}
  if ((faderPos == lastfaderValue) && (totalCp > minimumCp)) { // Touching Fader
      touched = true;
      Serial.println("Touching Fader, NOT Moving");
      delay(15);}
  if ((faderPos != lastfaderValue) && (totalCp > minimumCp)) { // Touching Fader and Moving
      touched = true;
      Serial.println("Touching Fader, Moving");
      delay(15);}
  lastfaderValue = faderPos; }

Your lastfaderValue is always equal to faderPos.

Every time you enter loop you’re comparing the pot input with an arbitrary value that you think is the last pot value, but since it’s local to loop, it isn’t. You may have not intended that to be a local variable. I’d add that you’ll probably want a minimum pot delta as well since simultaneous reads may not report the same value even if it’s not being moved.

Figured it out.
I had the lastfaderValue integer in the wrong spot. It works when I put it at the beginning of the code (before the setup).
I also added a tolerance, so that the potentiometer can still fluctuate slightly when I'm not touching it.
Works well now.


text:
Question about MIDI library
I'm trying to replace this code with something that uses the Arduino MIDI library:
#include <SoftwareSerial.h>

#define rxPin 2
#define txPin 1

SoftwareSerial midiSerial (rxPin,txPin);

void setup() {
  midiSerial.begin(31250); }

while ( midiSerial.available()) {
    incomingCommand = midiSerial.read();
    incomingNote = midiSerial.read();
    incomingVelocity = midiSerial.read()*8.05511811024;
  if (incomingVelocity <=1023) {
    midiSerial.write(incomingCommand);
    midiSerial.write(incomingNote);
    midiSerial.write(incomingVelocity); } }

Here's what I came up with:
#include <MIDI.h> // MIDI Output
MIDI_CREATE_DEFAULT_INSTANCE();

byte MIDIChannel;
byte programByte1;
byte controlByte1;
byte controlByte2;

void setup() {
  MIDI.begin();
}

void loop() {
 if (MIDI.read()) switch (MIDI.getType()) {
      MIDIChannel = MIDI.getChannel();
    case midi::ProgramChange:
      programByte1 = MIDI.getData1();
      break;
    case midi::ControlChange:
      controlByte1 = MIDI.getData1();
      controlByte2 = MIDI.getData2();
      break;
    default: break;
    }
}

Does that look correct? It doesn't function as smoothly as the version that uses SoftwareSerial

what exactly is your question?

"Does that look correct?" It doesn't seem to take in any MIDI input data

how do you know this?

I've updated the code above and added the rest of the commands to my switch-case setup, so I'll keep searching for the data I'm looking for, which is specifically the 'command' data. Should be straightforward with some digging

The first code transmits MIDI data, and the second receives it, so they are not having the same functionality, actually opposite functionality. Also, do not use software serial for MIDI. It works ok for single notes, but if you start using e.g. CC data, you sometimes miss data, which is very problematic when these are MIDI Note Off messages.

The second piece of code doesn't do anything useful. I think it will not even compile (instruction after switch without case)