text:
How to converte EPOCH time into time and date on Arduino?
I have a question on how to convert EPOCH timestamps, which I receive as char*, into DD.MM.YYYY and HH:MM:SS format separately?
Here is more information on my Arduino project: The Arduino is receiving through an ESP8266 module three different EPOCH timestamps from the OpenWeatherMap API for sunrise, sunset and the current date. I want these 3 pieces of information to be displayed on a 1,3" OLED display, the date in DD.MM.YYYY and the other two timestamps in HH:MM format.
I was looking in several time libraries like TimeLib and RTC for a solution, but I wasn't able to find one.
That's my code fragment on receiving the timestamps:
DynamicJsonBuffer jsonBuffer(4096);
JsonObject& root = jsonBuffer.parseObject(client);

const char* date = root["dt"];
const char* sunrise = root["sys"]["sunrise"];
const char* sunset = root["sys"]["sunset"];

How to convert those timestamps?

Epoch are seconds from 1970-01-01. Get it from JSON as unsigned long. They are a number in the returned JSON (no ")
from https://openweathermap.org/ doc:
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},

to convert it to string with TimeLib.h:
#include <TimeLib.h>
#include <ArduinoJson.h>

void setup() {

  Serial.begin(115200);

  const char* json = "{\"country\":\"JP\",\"sunrise\":1369769524,\"sunset\":1369821049}";

  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(json);

  unsigned long t = root["sunrise"];

  char buff[32];
  sprintf(buff, "%02d.%02d.%02d %02d:%02d:%02d", day(t), month(t), year(t), hour(t), minute(t), second(t));

  Serial.println(buff);
}

void loop() {
}

note you might need to divide the timestamp by 1000 if it includes ms, like JS's Dates for example.

@dandavis, I took the sample JSON from the openweathermap site

For sure, I'm just pointing out that there's two "epoc"s to be aware of from web services, in general.

For this example, it's not necessary to divide by 1000. Thank you very much for the help :)

@Juraj I have one more question to this topic: Can TimeLib also convert EPOCH timestamps to day names?(Monday, etc.)

dayStr(weekday(t)); or dayShortStr http://playground.arduino.cc/code/time

I'm was having a similar challenge with my custom Wifi library m_wifi..cpp for the ESP32 ( see here )
After reading and googling I ended up coding the solution below:
ESP32Time rtc(0);
long int epochTime;
...

rtc.setTime( epochTime  );
Serial.println( rtc.getDateTime(true) );

can it be used on a non esp32 Arduino as in the question?

yes. you can replicate the code to use on other than ESP32. Just need to find the compatible library for your specific MCU.


text:
Accelstepper run stepper backward
Update:
Below I implemented how I understood your suggestions. And it still does only turn in one direction (forward). Curiously if I entered M_DEST in the stepperOneForward() function it turned forward very long but smooth. The code below made it rotate as usual very jittery. Is this the acceleration part and if so how can I change that ? Ideally I would be able to tell the stepper go to position X and return to start and that in constant speed.
 #include <AccelStepper.h>

const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;

unsigned int DEST = 800;
unsigned int M_DEST = -800;
unsigned int SPD = 1600;
unsigned int ACCEL = 800;

AccelStepper stepper1(1,stepPin,dirPin);

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);

  stepper1.setEnablePin(enPin);
  stepper1.setPinsInverted(false, false, true);
  Serial.begin(9600);  // Start Serial
}

void loop() {

stepperOneForward();
Serial.println("Stepper1 turned forward.");
delay(1000);
stepperOneBackward();
Serial.println("Stepper1 turned backward.");
}

void stepperOneForward() {

  stepper1.enableOutputs();
  stepper1.setMaxSpeed(SPD);
  stepper1.setAcceleration(ACCEL);
  stepper1.move(DEST);
  if (DEST > 0) {
    while ( stepper1.distanceToGo() > 0) {
      stepper1.run();
      }
  //stepper1.disableOutputs();
  }
 }

 void stepperOneBackward() {

  stepper1.enableOutputs();
  stepper1.setMaxSpeed(SPD);
  stepper1.setAcceleration(ACCEL);
  stepper1.move(M_DEST);
  if (M_DEST < 0) {
    while ( stepper1.distanceToGo() > 0) {
      stepper1.run();
      }
  //stepper1.disableOutputs();
  }
 }

I have multiple steppers that I would like to run forward until they hit a microswitch and backwards to the initial position. But to simplify things I would like to control one stepper going forward and then backward. The code below always just turns clockwise.
I tried to set the dirPin to low, which did not work.
I tried to reverse the setMaxSpeed (by putting a minus in front of it).
I found the "enum AccelStepper::Direction" class in Accelstepper that did not explain how to to set DIRECTION_CCW or DIRECTION_CW.
What I would like to achieve is control these steppers so they move smoothly forward, wait and then backwards. This should be very easy, but has frustrated me now for too long. I would use any library at this point that can do this and control more than 1 stepper.
The SPD and ACCEL values are so high because I use microstepping (6400 is a full cycle).
#include <AccelStepper.h>

const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;

unsigned int DEST = 6400;
unsigned int SPD = 1600;
unsigned int ACCEL = 800;

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  Serial.begin(9600);  // Start Serial
}

void loop() {

stepperOneForward();
Serial.println("Stepper1 turned forward.");
stepperOneBackward();
Serial.println("Stepper1 turned backward.");
}

void stepperOneForward() {

  AccelStepper stepper1(1,stepPin,dirPin);
  digitalWrite(enPin,LOW);
  stepper1.setMaxSpeed(SPD);
  stepper1.setAcceleration(ACCEL);
  stepper1.move(DEST);
  if (DEST > 0) {
    while ( stepper1.distanceToGo() > 0) {
      stepper1.run();
      }
  digitalWrite(enPin,HIGH);
  }
 }

 void stepperOneBackward() {

  AccelStepper stepper1(1,stepPin,dirPin);
  digitalWrite(enPin,LOW);
  stepper1.setMaxSpeed(-SPD);
  stepper1.setAcceleration(ACCEL);
  stepper1.move(DEST);
  if (DEST < 0) {
    while ( stepper1.distanceToGo() > 0) {
      stepper1.run();
      }
  digitalWrite(enPin,HIGH);
  }
 }

I think the way to do this is to use stepper1.move(-DEST). PS I'd suggest creating the stepper1 object only once, as a global variable. And then use that global stepper1 in the two functions, instead of re-creating the object every time you call the two function.

First, you are creating/destroying the AccelStepper stepper1() object at every call. This is not right, as the library can no longer keep track of the stepper position and state.
The stepper object should be created in the global scope (that is, outside of setup() or loop()).
Second, you can call stepper1.setEnablePin(enPin) and stepper1.setPinsInverted(false, false, true) after you create the object to have the AccelStepper library control the enable pin and to set the enable pin to operate active-low. Then the driver is enabled or disabled with calls to stepper1.enableOutputs() and stepper1.disableOutputs(). In practice, you would not disable the driver except for power saving, as the stepper can no longer hold it's position when the outputs are not enabled. It will lose it's position.
Third, do not set the speed to a negative value. The direction of the stepper is determined by the library based on the current position and the desired end position. When the library is created, the position is zero. You can set the new position in several ways:

stepper1.move(): Set the target position relative to the current position. This means to go backwards you pass this function a negative value. It will add this (negative) number to the internal target position, and then run() will work to get it there.
stepper1.moveTo(): Set a new absolute position. If you initially set the position to 100 and move there, then set it to 50, the stepper will run in reverse to be able to reach position 50. If you start in position 0 and run to 50, it will run forward. If you start at 0 and set to -50, it will run in reverse to get there, and so on.

Thank you very much for your answer, above my update.

@digit You may want to look into what the Acceleration and Speed values mean. The docs (https://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#ae79c49ad69d5ccc9da0ee691fa4ca235) say that speeds over 1000 are unreliable. Try lowering the speed and accel values to something in 200 range. 1600 steps per second is too fast for the physical rotor to respond to the coil changes.

Well this is because I am microstepping and if I set the Speed to 200, but the Stepper has to run for 800 steps, it becomes very slow. I read this part of the Accelstepper. But all of this still does not solve the problem that never ran backwards. Only forwards.

If it runs forward and not backward with a stepper driver, then double-check your wiring... With AccelStepper using a driver, it only pulls the direction pin high or low and the driver handles the coil sequencing.

If I use a different driver and code (but same wiring) it works like a charm, so it can't be the wiring (or am I missing something here). I would like to just have one example code that turns the stepper backward with Accelstepper and ideally in a dedicated void that only enables the motor when needed (and thus keep the stepper cool for continuous running. Still could not find a solution for that after 5 days :)

You say different driver and code, same wiring. What about same code, but different driver, or different driver but same code? To eliminate the driver or the wiring as the culprit, you must change only one thing at a time.

If the wiring would be wrong, would it be able to rotate forward ?

It might. Is this a 4-wire bipolar stepper? Measure the resistance between set of the 6 combinations (A+B, A+C, A+D, B+C, B+D, C+D) of wires. The 2 coils will be the pair with about the same resistance. If it runs erratically, switch the polarity of one of the coils.

source: Stack Exchange

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

sort: votes


text:
Why does a 4 digit 7 segment cathode display wired to an Arduino not need to be connected to ground?
As a circuit neophyte I thought for a circuit to conduct current it had to be grounded.

Who says it's not connected to ground? https://majenko.co.uk/blog/what-exactly-gpio-pin

Inside the Arduino there are transistors that connect the pin to ground, when calling dititalWrite(<pinNr>, LOW).

The Uno is grounded. Current flows into the A-G and DP pins (that is: D2, D3, D4, D5, D6, D6, D8, and D9 on the Uno) when one of those pins is LOW and one of the display's digit pins is also low.
There is one "Common" pin for each of the 4 digits, labeled D1, D2, D3, and D4 on the display. Those common pins are connected to the Anodes (positive pin) of all segments in the specified digit. When 5V is applied to the base of the transistor, the NPN transistor is off. When 0V is applied to the base of the NPN transistor, current flows from the 5V source, through the transistor, and into the Anode of the digit.
When a segment pin (A-G, DP) is HIGH, it is at 5V. The Anode is also at 5V, so no current flows. When a segment pin in LOW, it s at 0V, and current flows from the Anode to Ground through the segment pin into the Uno.
This kind of display is meant to be multiplexed by digit. To light the first digit, The D1 transistor is turned on, and the segments to light up are set to LOW. All other transistors are off. Then, the first digit transistor is turned off and the 2nd digit transistor is turned on, and the segment pins are re-adjusted so that the desired output on the 2nd digit is displayed. Each digit is only on for a fraction of a second, but they are rotated through all 4 so quickly, that it gives the appearance of all 4 digits being on at the same time, without requiring 8x4=32 IO pins. Multiplexing means you only need 8+4=12 IO pins.
Search "multiplexed common anode 7-segment display" for more info.

Wonderful.  Thank you for answering my question in such detail.  You have added to my understanding on how the 4 digit seven segment display interfaces with the Arduino.

Current limit resistors are needed, one for each segment (A-G, DP) to avoid burning out the LEDs or uC IO pins:
(5V - Vce of transistor - Vf of the LED)/current = resistor value

So making some assumptions:
Vce = 0.7V in saturation (full on)

Vf = 2.5V (approx. for Red, check your datasheet)

10mA (so not blinding bright to start)

Then
(5V - 0.7V - 2.5V)/.01 = 180 ohm

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


text:
Connecting STM32F103C through USB as well as external power supply
What will happen if I connect a STM32F103C board to a USB as well as an external power supply? Will it work? Does the STM32 decide which power source to consider?

At least I know, you never should connect USB and the SWD VCC pin simultaneously. Do you have a datasheet/picture of your model? Since I cannot recall any STM32F103 board with external power supply (except normal supply via USB or SWD).

I don't have a picture of the model. With arduino boards you can have external and USB supply simultaneously. I'm using stm board now, so I just wanted to make sure if it's possible or not before I end up doing somthing I'll regret later on.

Without a link/datasheet I don't think anyone can answer. A picture is the least important, a link (on internet) or datasheet would help more. Arduino boards normally have an external power supplies, STM32 boards don't (unless shown otherwise).

you can test to see if there's a diode between the usb's 5 volt line and the devkit's 5V pin. If there is, you should be fine. If not, it will probably smoke something.


text:
Do all pins of Arduino Uno output 5V?
I am currently working on a project which uses PIR motion sensor and 5V relay.
Since you might be familiar that both the motion sensor and the relay requires a 5V connection.
My problem is, I don't want messy connections (parallel and series) and want to use any other pin for power and ground.
Also, can you suggest which resistor I might require for the motion sensor and relay?
Thanks for any help.

You might get away with powering a PIR sensor from a logic line. Check the specs. If it draws less ≤20mA you'd be fine. If you nee to drive more current than that you can use a CMOS TTL Driver or a properly selected N-channel MOSFET. Adafruit sells these, for example.
A relay is another matter. If you this is one of those optically isolated relays and all you're driving is the optioisolator then you might get away with that too if you only need ≤20mA. If you're looking to actually power the relay coils with your Arduino, forget it. it's a bad idea to even have the relay driven from the 5V line on the Arduino. Relays take quite a bit of current, and their load is quite "dirty" and likely to cause problems.
As to "which resistor I might require for the motion sensor & relay", I'm not sure what you mean. You shouldn't need any resistors. If the relay draws more current than the Arduino can supply, a current limiting resistor might protect the Arduino from damage but the relay won't work correctly.
What resistors are you referring to?

In the last para I am talking about the resistance value 1omhs or 100 ohms etc

I know what resistors are. I don't think you need any in this application, but you need to determine how much current your devices draw.

"(On most Arduino models the absolute max current for each pin is 40mA but the recommendation is to stay at half that, or ≤20mA."  Actually, the datasheet says Vout with Vcc = 5V is guaranteed to be >= 4.2V for up to 20mA, and may drop above that "If IOH exceeds the test condition [20mA at VCC = 5V], VOH may exceed the related specification. Pins are not guaranteed to source current greater than the listed test condition."

@CrossRoads that will teach me to trust things posted by other people on these boards as truth without validating for myself. Thanks for correcting me. I've deleted that part of my answer.


text:
Wemos D1 mini not being shown when connected to macbook
I have multiple Wemos d1 mini lying around, but can't seem to get them connected to my macbook, to they do not show up in my /dev/tty?
I tried updating the driver, both using home-brew and installing the driver manually -  as suggested here
https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
but nothing seem to work?
I tried different cables? no way to connect to it?

I finally had success following the removal instructions, but NOT installing anything.

@josecanuc, what removal instructions?

In the link you give in your question, steps 1-3.

All of the cables I tried don't have a data line

Oops! Well, that would definitely cause the problem! Glad you got them to connect.

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

@MichelKeijzers - the answer is written by the author of the question - so it does answer the question

I tried different cables? seems like you have multiple power only cables, so technically, the answer should've been "All of the cables I tried don't have a data line"

@anita it would be great if you could expand on your answer making it clear for others who have the same problem. Perhaps you could add diagrams or tests to perform to determine if the data line is there.


text:
Multiple .ino files in the same sketch
Yeah yeah, I know people ask this type of thing a lot, but I couldn't find an answer anywhere.
I understand that you can have multiple .ino files in one sketch, but I don't just want functions and variables separated, I want functionality.
I am writing a Braille program for the NodeMCU -- It takes a message from a served website and moves servos to emulate the appropriate Braille. I want to have 2 files: one to serve the website and get input from it (website.ino), and the other one to manipulate the servos(braille.ino). The only problem is, I can't figure out where to declare/attach the servos.
I plan to have a list of servos in braille.ino that will be looped over with each servo being set to a different value. If I declare them  in website.ino (my "main" file, ie, with a setup and loop), I will have to pass them to my braille function every time. On the other hand, if I choose to declare them as globals in my braille.ino, where would I attach them? Can I have another setup in braille.ino?

I wanted the same and my solution was to use MS Visual Studio with Arduino IDE from Visual Micro.
It makes using multiple files easy and has lots of additional advantages.

just have code in the "main" .ino call a function you define in any subsequent .ino

You can use VS Code with the extension "vscode-arduino". It will allow you to manage multiple .ino files as Tabs as in the Arduino IDE does. Plus the advantages of intellisense.
Checkout the Maker.pro website for a how to: https://maker.pro/arduino/tutorial/how-to-use-visual-studio-code-for-arduino

What isn't obvious is that with Arduino, you can have normal C and C++ files in the same directory as the .ino file. These can have functions and variables inside them, and Arduino will link them into the main program too. You only need one .ino file - all the rest can be in modules with a .c or .cpp (for C++) extension.
That way, you can group "helper" functions in different files by category - for example, a BrailleServo.c file. These contain the functions and variables for just that category.
If you haven't programmed native C/C++:

Put the functions and variables in the BrailleServo.c file, and then repeat the functions' header in the BrailleServo.h file.
Inside the BrailleServo.c file, at the top, put the following line:
#include "BrailleServo.h"

Note the quotes (" "), not angle brackets (< >)
Inside the .ino file, put the same #include line. That tells the module that "there are other functions elsewhere, and these are their definitions".

The only problem? Getting the silly Arduino environment to let you add .c and .h files to that directory. You could just use Notepad, but there's a trick (if you're using Windows):

Choose File|Open…
Right-click the pane with the files in it, and choose New >|Text Document
Give it a complete name, and make sure you replace the .txt part of the name too with .c or .h. You may get the "If you change the extension, the file may be unusable" warning - just click OK.
Select the new (blank) file in the file pane, and a new tab will appear.

Note that 3. above assumes that you've told Windows File Explorer to NOT hide the extensions of known file types. I always do that - if you haven't, you'll need to. With:

Windows 10:
  In any folder's View tab, tick the File name extensions checkbox;
Windows 7:
  In Control Panel | Appearance and Personalization | Folder Options' View tab, untick Hide extensions for known file types

Here are three examples:
BrailleServo.h
//
// BrailleServo.h
//

// Call this function once in setup()
void BrailleInit();

// This function activates the six servos to form the passed-in pattern.
void BrailleShow(byte pattern);

BrailleServo.c
//
// BrailleServo.c
//

#include "BrailleServo.h"

// The number of servos
const byte NumServos = 6;

// These are the pins for the six servos
const byte servo[NumServos] = { 3, 4, 6, 7, 9, 10 };

// This initialises the six servos
void BrailleInit() {
   for (byte i=0; i<NumServos; ++i) {
      pinMode(servo[i], OUTPUT);
      // Do what else you need to do with servo[i]
   } // for
} // BrailleInit()

// This is how to use the six servos to form the passed-in pattern
void BrailleShow(byte pattern) {
   // … Complicated code here …
} // BrailleShow(pattern)

Main.ino
//
// Main.ino
//

#include "BrailleServo.h"

void setup() {
   BrailleInit();
   // Other stuff
} // setup()

void loop() {
   BrailleShow('A');
   delay(1000);
   BrailleShow('B');
   delay(1000);
} // loop()

Incidentally, for ideas you may want to check out my answer to a more generic Braille question.

Thanks so much! I guess I wasn't really thinking about having the servos do things until they were attached, but i guess that's what happens when you work overtime. I don't think I'll bother re-encoding the letters, since I already have arrays of true-false, but thanks anyway!

It is important to know that the tabs/ino files are concatenate into one by the builder. The order of the concatenation is the same as the order of tabs in IDE. First is the main ino file with the same name as the project. The rest of the files is concatenated in alphabetical order.
The concatenated ino file determines the visibility of variables. All ino files 'see' the variables in the main ino file, but variables in other ino files are visible only in ino file with names later in alphabetical order.
For functions the builder generates function prototypes to the beginning of the resulting cpp file, so as usual all functions are visible everywhere in all ino files.
One way to work with additional tabs is group is to write xySetup() and xyLoop() functions in the xy.ino file and then call this functions from the main setup() and loop(). My main Arduino project is created this way, so it is a big and complex example of this approach.
To illustrate, this is the resulting cpp file entering the cpp part of the build toolchain (scroll it to end):
#include "Arduino.h"
#define I2C_ADC121         0x50
#include <Wire.h>
extern const unsigned long EVENTS_SAVE_INTERVAL_SEC;
extern const char eventLabels[];
extern const char* eventLongLabels[];
extern const char* eventLongLabels[];
#define EVENTS_FILENAME "EVENTS.DAT"
#include <Grove_LED_Bar.h>
#include <StreamLib.h>
#include <TimeLib.h>
#include <MemoryFree.h>
#include <UIPEthernet.h>
#define ETHERNET
#include <ArduinoOTA.h>
#include <SD.h>
#define FS SD
#define Serial SerialUSB
#include "consts.h"
#define BLYNK_PRINT Serial
#define BLYNK_NO_BUILTIN // Blynk doesn't handle pins
#include <BlynkSimpleUIPEthernet.h>
#include <RTCZero.h>
#define STATS_FILENAME "STATS.DAT"

void balboaSetup() ;
void balboaReset() ;
void balboaLoop() ;
void battSettLoop() ;
boolean battSettRead(FormattedPrint& out) ;
const char* bit2s(int value, byte mask) ;
int battSettControl(boolean chargeControlOn, boolean dischargeControlOn) ;
int battSettSetLimit(byte reg, int limit) ;
void beeperLoop() ;
void alarmSound() ;
void beep() ;
void beeperTone(int freq, uint32_t time) ;
void blynkSetup() ;
void blynkLoop() ;
void updateWidgets() ;
void buttonSetup() ;
void buttonLoop() ;
void csvLogSetup() ;
void csvLogLoop() ;
void csvLogPrintJson(FormattedPrint& out) ;
void elsensSetup() ;
void elsensLoop() ;
boolean elsensCheckPump() ;
byte overheatedSecondsLeft() ;
int readElSens() ;
unsigned short elsensAnalogRead() ;
void eventsSetup() ;
void eventsLoop() ;
void eventsWrite(int newEvent, int value1, int value2) ;
boolean eventsSaved() ;
void eventsSave() ;
byte eventsRealCount() ;
void eventsPrint(FormattedPrint& stream) ;
void eventsPrint(FormattedPrint& s, int ix) ;
void eventsPrintJson(FormattedPrint& stream) ;
void eventsPrintJson(FormattedPrint& stream, int ix) ;
void eventsBlynk() ;
int eventsCompare(const void * elem1, const void * elem2) ;
void ledBarSetup() ;
void ledBarLoop() ;
void manualRunLoop() ;
byte manualRunMinutesLeft() ;
void modbusSetup() ;
boolean modbusLoop() ;
void modbusClearData() ;
boolean requestSymoRTC() ;
boolean requestInverter() ;
boolean requestMeter() ;
boolean requestBattery() ;
boolean modbusError(int err) ;
int modbusRequest(byte uid, unsigned int addr, byte len, short *regs) ;
int modbusWriteSingle(unsigned int address, int val) ;
int modbusConnection() ;
void pilotLoop() ;
unsigned short power2pwm(int power) ;
void setup() ;
void loop() ;
void shutdown() ;
void handleSuspendAndOff() ;
void clearData() ;
boolean handleAlarm() ;
boolean restHours() ;
boolean turnMainRelayOn() ;
boolean networkConnected() ;
void statsSetup() ;
void statsLoop() ;
int statsEvalCurrentPower() ;
void statsAddMilliwats() ;
void statsSave() ;
int statsConsumedPowerToday() ;
void statsPrint(FormattedPrint& out) ;
void statsPrint(FormattedPrint& out, const char *label, Stats &stats) ;
void statsPrintJson(FormattedPrint& out) ;
void statusLedSetup() ;
void statusLedLopp() ;
void statusLedShortBlink() ;
void susCalibLoop() ;
void telnetSetup() ;
void telnetLoop(boolean log) ;
void valvesBackSetup() ;
void valvesBackReset() ;
void valvesBackLoop() ;
void valvesBackStart(int v) ;
boolean valvesBackExecuted() ;
unsigned short valvesBackTempSensRead() ;
void watchdogSetup() ;
void watchdogLoop() ;
void WDT_Handler(void) ;
void webServerSetup() ;
void webServerLoop() ;
void webServerRestRequest(char cmd, ChunkedPrint& chunked) ;
void webServerServeFile(const char *fn, BufferedPrint& bp) ;
void printValuesJson(FormattedPrint& client) ;
void printAlarmJson(FormattedPrint& client) ;
const char* getContentType(const char* ext);
void wemoLoop() ;
boolean wemoPowerUsage() ;
int wemoRequest(const char* service, const char* action, const char* param, const char* value, char* response, size_t size) ;

#include "Regulator.ino"

#include "Balboa.ino"
#include "BattSett.ino"
#include "Beeper.ino"
#include "Blynk.ino"
#include "Button.ino"
#include "CsvLog.ino"
#include "ElSens.ino"
#include "Events.ino"
#include "LedBar.ino"
#include "ManualRun.ino"
#include "Modbus.ino"
#include "PowerPilot.ino"
#include "Stats.ino"
#include "StatusLed.ino"
#include "SusCalib.ino"
#include "Telnet.ino"
#include "ValvesBack.ino"
#include "Watchdog.ino"
#include "WebServer.ino"
#include "WemoInsight.ino"


text:
Using Sleep AND LowPower.h
I am trying to set up the low power module for an instance case,
I have installed the low power library but when I am using the
line
LowPower.powerDown (SlEEP_5S, ADC_OFF, BOD_OFF) ;

It is throwing an error stating that the 'SLEEP' was not declared in the scope.
Any suggestion for that ? Do I have to include a library for sleep too ?
#include "LowPower.h"
  /// DON' t worry about the setup and loop, i have defined all those.

This set of code is in
  void Loop()
    ...
    else
    {
       LowPower.powerDown (SLEEP_10S, ADC_OFF, BOD_OFF) ;

SlEEP_5S ... should that be SLEEP_5S ?

Sorry ! I didnt get you

you can't see the difference between SlEEP and SLEEP?

nope i tried that, doesn't work.

i defined along with the package #include "LowPower.h"  #define SlEEP_5S, this leads me to an error that expected primary-expression before ','token

Void instead of void? An else without an if?  Your program will have many more problems right now. Note that the language is case sensitive.

I updated your code assuming that you typed it over (so changed void / else.

There is no 5 or 10 second sleep. You can't just arbitrarily choose how long to sleep for. The watchdog timer only has specific periods (defined by dividing the clock by a set amount) that it can sleep for:
enum period_t
{
    SLEEP_15MS,
    SLEEP_30MS,
    SLEEP_60MS,
    SLEEP_120MS,
    SLEEP_250MS,
    SLEEP_500MS,
    SLEEP_1S,
    SLEEP_2S,
    SLEEP_4S,
    SLEEP_8S,
    SLEEP_FOREVER
};

To sleep for 5 seconds you would need to sleep first for 4 seconds, then wake up, and then sleep for a further 1 second after that. For 10 seconds sleep for 8 seconds followed by 2 seconds.
Note that they aren't exact values, however, since the watchdog oscillator is very crude and varies wildly in frequency with both temperature and power supply voltage.


text:
Transmit/Receive data Nodemcu(V3) + Bluetooth Module HC-05
I am trying to communicate with the HC-05 Bluetooth module for quite long time now, but with no success.
I am using the Nodemcu(V3) ESP8266 module.
I connect the HC-05 to Nodemcu in following sequence:
HC-05             Nodemcu
-----             -----------
RX       -->      Pin 1 (Tx)
TX       -->      Pin 3 (RX)
Vcc      -->      +3.3V
GND      -->      GND

For starters, i want to check if my Nodemcu is communicating properly with my HC-05 module.
I have written the following code to read the response of AT commands:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(3, 1); // RX | TX
char Bluetooth_Name = ' ';

void setup()
{
    // Arduino IDE serial monitor
    Serial.begin(115200);

    // HC-05 default serial speed for AT mode is 38400
    BTserial.begin(38400);

    // Wait for hardware to initialize
    delay(1000);

    // Print debug string
}

void loop()
{

   // Keep reading from HC-05 and send to Arduino Serial Monitor
   if (BTserial.available())
   {
      reading = BTserial.read();
      Serial.println(reading);
   }

   // Keep reading from Arduino Serial Monitor and send to HC-05
   if (Serial.available())
   {
      reading = Serial.read();
      BTserial.write(reading);
   }
}

However, i do not get response for any AT command at all. The serial monitor just shows blank.
Thanks in advance
EDIT:- I connected the "EN" pin on the HC-05 to Vcc. Now, the led on the HC-05 blinks slowly, which means that the HC-05 is configured in command mode. However, i am still not able to receive the response for any AT commands. I have also selected "Both NL & CR" in the serial monitor, configured the baud rate correctly and double-checked the hardware connections.
Everything seems to be correct except that i don't get response for the AT commands.
Please help!!!

what output do you get, if any

No, i did not get any output on the serial monitor

I just modified the question to check the basic step if HC-05 is working with Nodemcu or not?

I changed the line
SoftwareSerial BTserial(3, 1); // RX, TX

to
SoftwareSerial BTserial(D4, D3); // RX, TX

And got it to work!

I had the exact same problem and got it to work doing these changes:
I had to add this under my library include statements
#ifndef D5
#if defined(ESP8266)
#define D5 (14)
#define D6 (12)
#define D7 (13)
#define D8 (15)
#define TX (1)
#endif
#endif

and changed
SoftwareSerial BTserial(3, 1); // RX, TX
to
SoftwareSerial BTserial(D5,D6);
I used D5 and D6 on my esp8266 instead of D1 and D3 but shouldn't matter


text:
Arduino for loop
I am a beginner in Arduino programming. This is my program for 5 LEDs and 1 Button. The LEDs are supposed to light before I press the button. But the LEDs start immediately, even without pressing the button. How is it possible?
int sw7=7;
int timer=500;
int start=0;
int stopp=100;
void setup()
{
  for (int opin=1;opin<6;opin++)
  {
    pinMode(opin,OUTPUT);
    pinMode(sw7,INPUT);
  }
}

void loop()
{
  if (digitalRead (sw7)==LOW)
  {
    while (start<=stopp);
  }
  {
    for (int opin=1;opin<=5;opin++)
    {
      digitalWrite(opin,HIGH);
      delay(timer);
      digitalWrite(opin,LOW);
     }
  }
}

how did you wire the button? has it pull-down?

It's a large tack switch. 1 foot is on pin 7 in series with the other foot connected to 5v and the foot beside the foot that is connected in pin 7 is connected to ground. Is there nothing wrong with the program? Thank you.

I aligned your code. do you see how the for loop is outside of the if for the button?

no resistor? wire it this way and use mode INPUT_PULLUP https://www.arduino.cc/en/Tutorial/InputPullupSerial

try putting an else between }   {

@Juraj there is a resistor. I think it's there something wrong with the code.

@Juraj okay I'll wire it. I'll get back to you, thanks a lot!

@Gerben. void loop()
{
if (digitalRead (sw7)==LOW)
{
while (start<=stopp);
}
else
{
for (int opin=1;opin<=5;opin++)
{
like this?

How are the LEDs wired? +5 to anode, cathode to resistor, resistor to pin?  If so, then they turn on with a low output, and probably turn on right after the pinMode command.  Try a test - add a noticeable delay after the pinMode, see if that's when turn on. If so, then drive the outputs high after the pinMode to 'initialize' them, and change your code to turn them on with a Low instead of High.   Also, using INPUT_PULLUP on the switch and testing for a Low instead of a High will keep the switch input from floating around when it is not pressed.

why are you running this 5 times? pinMode(sw7,INPUT);

these two are the same thing The LEDs are supposed to light before I press the button. and LEDs start immediately ...... i think that you need to edit your question

Your line  while (start<=stopp); will put your sketch into an infinite loop. start will always be less than stopp, so that loop will never end and your program will freeze once it begins executing that while loop.

Several things:
You need to explicitly set your output pins to LOW in your setup method.
The code to set the sw7 to input should not be inside the loop.
You should probably connect your switch between sw7 and ground and use INPUT_PULLUP mode (in INPUT_PULLUP mode the line is connected to +5V through a "pull-up resistor" so that it reads HIGH until you press the button, and then it reads LOW. If you don't use either an input pull-up or pull-down resistor then the input tends to "float" and give bad readings.)
You say "The LEDs are supposed to light before I press the button. But the LEDs start immediately, even without pressing the button."
I'm not sure what you mean. What do you want to happen, exactly? Do you want the LEDs to be lit steadily, and then turn off or flash when you press the button?
The code below will turn off all the LEDs initially, then toggle between off and flashing on each (debounced) button press. Switch the value of idleLEDState to HIGH if you want the LEDs to be lit when they are not flashing.
#define flashDelay 50 //Delay between on and off state for LEDs
#define switchBounceDelay 100

uint8_t idleLEDState = LOW; //Change to HIGH
                            //if you want the LEDs to be lit when not flashing
bool flashLEDs = false;
bool ledsOn = false;
unsigned long nextFlashTime = 0;
unsigned long nextSwitchCheckTime = 0;

void setup() {
  pinMode(sw7, INPUT_PULLUP); //Connect the switch between sw7 and ground
  for (int opin=1;opin<6;opin++)
  {
    pinMode(opin,OUTPUT);
    digitalWrite(opin, idleLEDState);
  }
}

void loop() {

  //If it's time to check the switch, and it's being pulled LOW, toggle flashLEDs
  if (mills() > nextSwitchCheckTime && digitalRead(sw7) == LOW) {
    flashLEDs = !flashLEDs;
    nextSwitchCheckTime = millis() + switchBounceDelay;
  }

  if (!flashLEDs) {
    //IF we're not supposed to flash the LEDs, set them to their idle state
    for (int opin=1;opin<6;opin++) {
        digitalWrite(opin, idleLEDState);
     }
  } else if millis() > nextFlashTime {
    nextTime = millis() + flashDelay;
    ledsOn = !ledsOn;
    for (int opin=1;opin<6;opin++) {
        uint8_t newState = ledsOn ? HIGH : LOW;
        digitalWrite(opin, newState);
     }
}

I banged out the code above in the Stack Exchange editor. It likely contains a few typos. Please exert some effort to fix it and adapt it to your needs before posting back "Your code didn't work. I got error XYZ."

This is a sketch according to your requirements:
// pin mapping
int pin_map[] = {
  1,  // 0: led in pin 1
  2,  // 1: led in pin 2
  3,  // 2: led in pin 3
  4,  // 3: led in pin 4
  5,  // 4: led in pin 5
  7   // 5: button (pull-up)
};

int timeout_ms = 500;
int blink_ms = 100;

void setup()
{
  // setup pins
  for (int opin = 0; opin < 5; opin++) pinMode(pin_map[opin], OUTPUT);
  pinMode(pin_map[5], INPUT_PULLUP);

  // wait for activation
  while (millis() < timeout_ms)
  {
    // activate by button (off:pull-up on:GND)
    if (digitalRead (pin_map[5]) == LOW) break;
  }
}

void loop()
{
  for (int opin = 0; opin < 5; opin++)
  {
    // toggle LED
    int pin = pin_map[opin];
    pinMode(pin, !digitalRead(pin));
  }

  delay(blink_ms);
}

You will need avoid delay() usage if you need asynchronous tasks. Probably, you should study C language and practice with some hundred of sketchs to improve your code skills.

Putting the LED pins and the switch pins into the same array seems confusing. They do different things. I do see the value in using an array to store the LED pin assignments though. That way you can use any pins for the LEDs, even discontinuous pin numbers.


text:
Replace digitalWrite with a selective bitwise operation
I have the following code with digitalWrite I aim to write with bitwise operation only.
No portability concerns here whatsoever. (for atmega328p here)
#define DATAOUT 11//MOSI
byte commandbits = B11000000;
for (int i = 7; i >= 3; i--) {
    digitalWrite(DATAOUT, commandbits & (1 << i));
}

I came up with something like this below which works.
#define DATAOUT 11//MOSI
byte commandbits = B11000000;
for (int i = 7; i >= 3; i--) {
    PORTB = (PORTB &(~(1<<3))) | (((commandbits &(1 << i))>>i) << 3);
}

Is this the most concise way. Is there a way to simplify it?

You do know that your code makes no real sense, don't you? Outputting data from a single pin like that can never do anything useful. You need a clock signal (synchronous serial) or for both ends of the connection to agree fairly precise timing (asynchronous serial). Or have you just omitted that part of your code for brevity?

I have omitted lots of it for brevity. obviously...

That's OK then. I'll let you off.

Personally I'd expand it out a little:
if (commandbits & (1 << i)) {
    PORTB |= (1<<3);
} else {
    PORTB &= ~(1<<3);
}

It's far more readable, and there are less shifts to mess around with. Plus the AVR has bit set and bit clear operations which that will make use of, especially since it's now using literal values. You could actually replace those values with literals:
if (commandbits & (1 << i)) {
    PORTB |= 0x08;
} else {
    PORTB &= 0xF7;
}

That was my first idea of it. I did not mention it but the faster the better in my case. I'll have to do a timing test of the one liner vs if else.

if you want fastest you need to look at the assembly code the compiler produces. I think the if statement would actually be faster than your code. AVRs can only do single bitshifts, so <<3 would be three instructions. Note that compilers are pretty smart. So don't bother replacing (1<<3) with 0x08 thinking it will be faster.

I confirm the if else is much faster. Thanks for your input Majenko and Gerben.

If you like both portability, readability and performance there are a few libraries (for instance Arduino-GPIO):
#include "GPIO.h"

GPIO<BOARD::D11> data;

// Setup
data.output();

// Manual loop unrolling for speed. Could ask the compiler to do this
// Member function write()
data.write(commandbits & 0x80);
data.write(commandbits & 0x40);
data.write(commandbits & 0x20);
data.write(commandbits & 0x10);
data.write(commandbits & 0x08);

// Or using the assignment operator
data = commandbits & 0x80;
data = commandbits & 0x40;
data = commandbits & 0x20;
data = commandbits & 0x10;
data = commandbits & 0x08;

And it is as fast as manually written direct port access.

Interesting. Your example get me thinking I should better get rid of the for loop and replace the (1<<i) with their value.


text:
Arduino Uno: external power supply +5V and serial communication with pc over USB
I have connected to my Arduino Uno outputs relay module. Relay module has 16 relays (5VDC) which are controlled by transoptors pins (HIGH from Arduino = specific relay is off).
Link to relay module (lang: polish): https://botland.com.pl/pl/przekazniki/6940-modul-przekaznikow-16-kanalow-z-optoizolacja-styki-7a240vac-cewka-5v.html?search_query=modul+przekazniko&results=75 (SRD-05VDC-SL-C relays).
Arduino is supplied by +5V pin and GND pins with external power supply MDR-5-10. Relay module is supplied with the same power supply.
I control Arduino from PC using serial communication over USB (I send a command eg. 1;1;1;1;1;1;, then 6 outputs goes to HIGH). And now there is a problem. When I disconnect relay module control pins from Arduino outputs everything works fine. But when it is connected, I get serial com. error "device not found" (after some switches: sometimes it works for about 20 output switches, sometimes for 1 output switch) and I have to open serial communication again. Probably error appears only when I'm switching outputs.
I think the problem is because my external power supply +5V drops for a while when switching and then Arduino switches to +5V from USB (which doesn't drop), which has not enough power and then error occurs.
Am I right? Any suggestions to fix the problem?
EDIT #1:
Thank you for help. Answers:
@Jot, after disconnecting +5V Arduino pin, but with connected relay module, I get serial error immediately with first relay switch. If i dosconnect both +5V pin and relay module control pin, my application works fine.
My wires: external power supply - Arduino: 0,5 mm2; Arduino - relay module control pins: 23 AWG (~0,25 mm2); external power supply - relay module +5V and GND: 1,5 mm2. It flows through relays: 24VDC <30W or 230VAC ~20mA.
@CrossRoads, no I use A0-A4 and Q3-Q12 (for relay module: Q3-Q7, Q9-Q11, Q13).
@Duncan C: Currently, I use only 9 relays, other control pins are disconnected and off. Here - http://botland.com.pl/index.php?controller=attachment&id_attachment=244 (power consumption per relay - 0,36W 5VDC) - you can see relay datasheet. Relays are isolated from Arduino with opto-isolators (signal HIGH from Arduino = relay is off).
I never switch them all at once. In specific function I never use more then 5 relays together.
@Majenko, thank you, I'll give it a try in Tuesday!
Further informations:

Probably problems occur more often when I connect wires to relays pins (I use them all as NO: 7x 30W 24VDC - coils, 2x 230VAC ~20mA - contactor).
Serial communication error can occur during both reading or writing to serial.

2A output should be more than enough. You can try adding a large electrolytic capacitor across the 5V and GND pins on the Arduino though to see if that helps.

The arduino uno does not switch between the power supplies. Everything stays connected. Only when the barrel jack or the vin pin is used, then the usb power is switched off at about 7.5v. What happens if you disconnect the relay module and keep the gnd connected (arduino gnd to relay module gnd to external power gnd)? How thin are the wires that you use from the external power supply and between the arduino and the relay module?

Do you have D0, D1 connected to the relay module? If so, try using two other pins instead.

I can't make much sense of the Polish language specs on that relay module. What's the max current the relay module will draw? 16 relays are likely to use a WHOLE LOT of current if you activate them all at once. I thought I remembered each relay in mine as drawing about .2 amps, so 16 relays would be 3.2 amps.

I have a similar rig using a 4-channel optically isolated relay, but I use different power supplies for the Arduino and for the relay. (It works perfectly.) My guess is that the relays are causing the voltage on your arduino to droop when they switch on. I suggest using separate power supplies.
As @Majenko suggests, you might try adding a filtering cap (capacitor) between +5V and ground very near the Arduino. The cap should slow the drop in voltage to the Arduino long enough for the power supply to recover, but separate power supplies is the surest fix.


text:
WaveShare EPaper Display and Adafruit HUZZAH32 ESP32 Feather Board
I'm trying to understand how I could use WaveShare EPaper Display with Adafruit HUZZAH32 ESP32 Feather Board.
With these connections
SDI/SCK -> MOSI
SCK/SCLK -> SCK
CS -> 15
DC -> 33
RST/Reset -> 27
Busy -> 32

and this code
#include <GxEPD.h>
#include <GxGDEP015OC1/GxGDEP015OC1.cpp>    // 1.54" b/w
#include <GxIO/GxIO_SPI/GxIO_SPI.cpp>
#include <GxIO/GxIO.cpp>
#include <Fonts/FreeSansBold24pt7b.h>

GxIO_Class io(SPI, 15, 33, 27);
GxEPD_Class display(io, 27, 32);

const char* name = "FreeSansBold24pt7b";
const GFXfont* f = &FreeSansBold24pt7b;

void setup() {
  randomSeed(analogRead(0));
  Serial.begin(9600);
  Serial.println("Starting...");
  display.init(9600);
  //display.setRotation(1);
  display.fillScreen(GxEPD_BLACK);
  display.setFont(f);
  display.update();
  delay(2000);
}

void loop() {
  Serial.println("showing randon number...");
  showRandomNumber();
  delay(2000);
}

void showRandomNumber() {
  String randomString = String(random(1, 60));

  uint16_t box_x = 60;
  uint16_t box_y = 60;
  uint16_t box_w = 90;
  uint16_t box_h = 100;
  uint16_t cursor_y = box_y + 16;

  display.setRotation(45);
  display.setFont(f);
  display.setTextColor(GxEPD_BLACK);

  display.fillRect(box_x, box_y, box_w, box_h, GxEPD_WHITE);
  display.setCursor(box_x, cursor_y+38);
  display.print(randomString);
  display.updateWindow(box_x, box_y, box_w, box_h, true);

}

but I don't get any reaction from the display, do you see something wrong in the code or the connections?
thanks a lot for your help
References

https://github.com/dgarrett/BasicEPaperReader
https://danthegeek.com/2019/02/04/iot-calendar-creating-a-custom-featherwing/
https://github.com/juanpabloaj/esp32_waveshare/blob/master/01_update_window/01_update_window.ino

have you tried an example sketch? .... there should be one included with the e-paper library

I tried a similar code with esp32 nodemcu and it works, my problem is with Adafruit HUZZAH32 ESP32
https://github.com/juanpabloaj/esp32_waveshare/blob/master/01_update_window/01_update_window.ino


text:
ESP8266 Flash - Maximize SPIFFS size
the board i use has 1MB Flash Size. My program however downloads 512K+ of data for processing.
Arduino Options i see are:

Ideally i would like to use 1MB of SPIFFS, is this even possible?
I don't use OTA, and compile with:

To minimise the footprint of the main sketch.
Thanks in advance.

You need to get a ESP with more flash for this project.

No.
Even if you don't use OTA, your program is stored in flash. If you have 1MB of flash, there's no way you can use all 1MB for SPIFFS; that would leave no space for your program.
Here's a page showing how flash is divided up in an Arduino environment.
Even if you eliminate space for OTA images and the EEPROM, the Arduino environment will still reserve space for the sketch itself and for its wifi config and possibly a little more data.
You can never use 100% of the flash storage for SPIFFS.


text:
How ro re-enable 32u4 USB controller after sleep mode?
I've run into quite the problem with my 32u4, I can't get it to reconnect to the computer upon wakeup from a sleep mode!
So I have an Arduino Pro Micro featuring the 32u4, and I'm also designing a project with a standalone 32u4 (I'm using the Pro Micro as a test platform before I begin building my project). It is a battery operated device with a soft-start, so I need power consumption to be a miniscule as possible (hence the sleep modes).
After learning about the registers and brushing up on some binary, putting the chip to sleep was fairly straight forward, however, I cannot get the USB interface internal to the 32u4 to 'wake back up' or reconnect to the computer. I've attached my code below. I also tested this code on my Arduino Nano and it works just fine, however with added USB features of the 32u4, I cannot get it to reconnect to the computer, and I have to reset the chip a million times to get the IDE to finally recognise it and upload something else to it.
Here is my lovely code below. All it does it upon startup, go sleep, and when interrupt on pin 2 goes low, wake the chip back up and run the blink sketch. It goes to sleep, and wakes up and runs the sketch, it just won't ever reconnect to my computer, until I do a hardware reset.
int btn1Pin = 2;
int led1 = 9;

// these are the 'standard' register configurations
byte _SMCR = 0; // disable sleep mode
byte _ADCSRA = 0b10000111; // re-enable ADC

int interval = 500;
int ledState = true;
unsigned long ct1 = 0;
unsigned long pt1 = 0;

void setup()
{
  pinMode(led1, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(btn1Pin), wakeUp, FALLING);
  sleep();
}

void loop()
{
  ct1 = millis(); // blink something so I know you're working
  if (ct1 - pt1 >= interval)
   {
     digitalWrite(led1, ledState);
     ledState = !ledState;
     pt1 = ct1;
   }
}

void wakeUp()
{
  SMCR = _SMCR; // disable sleep mode
  ADCSRA = _ADCSRA; // re-enable ADC
}

void sleep()
{
  ADCSRA &= ~(1 << 7); // disable ADC
  SMCR |= ( 1<<2 );    // power down mode
  SMCR |= 1;           // enable sleep
  __asm__ __volatile__("sleep"); // hypnotist snaps fingers, chip is out cold!
}

Inside AJ's brain (more research):
32u4 Datasheet for quick reference
I added a quick led turn on in the wakeUp() ISR to ensure it was actually getting executed, and indeed it was.
The description of the USBCON register (Page 267 - 21.13.1) claims that clearing bit 7 disables and resets the USB controller. I tried another iteration of code where in sleep() I cleared bit 7, hoping that reset the controller, and in wakeUp() I set the bit to turn it back on after reset, but that didn't work. In fact, it gave me a really tough time when trying to reprogram (even though I KNOW that the wakeUp() ISR is executing and the bit had to have been reset).
After some more reading, I saw (Page 262 - 21.7.2) says that in power down mode (the sleep mode I'm using),  "the oscillator is stopped and halts all the clocks (CPU and peripherals). The USB controller 'wakes
up' when:

the WAKEUPI interrupt is triggered
the VBUSTI interrupt is triggered."

Okay so this makes sense, in power down mode the USB controller is stopped due to the lack of an oscillator, cool! I understand that to mean I need to trigger one of those interrupts to re-enable the USB controller. So I searched around for the first interrupt "WAKEUPI", and it appears this bit is set by hardware (Page 282), I'm guessing this means when you plug in the USB cable? I wrote a sketch to read that register, and it returned with 00010000, so I'm assumed the above statement is true. It also says setting it with software has no effect, so I left this one to explore the next interrupt, VBUSTI, which seems to be part of the automatic USB plug in detection based off of the VBUS pad. Maybe something here needs to be changed but I can't tell.
Page 266 - 21.12 talks about software USB operating modes, and the last one is "Resuming the USB interface." The 4 bullets provide to wake up are as such:

Enable PLL
Wait PLL lock
Unfreeze USB clock
Clear Resume information

I tried to do all of the above by adding this code to the wakeUp() ISR. It still didn't work :(. I know it's brutal and ISRs should be as short as possible but I gave it a go anyways.
  PLLCSR = _PLLCSR; // enable PLL clock
  var = bitRead(PLLCSR, 0);
  while (var != 1) {} // wait for clock to lock

  USBCON = _USBCON; // unfreeze USB clock
  UDINT = 0; // clear resume flag

Maybe I'm making all of this more complicated than it needs to be, I don't know! I can't get this thing to reconnect.

You're making it too hard on yourself.
There is a method to re-start the USB, but it only works if the USB has been properly stopped - and the method that is supposed to do that is empty.
This is a little sketch that works on my Leonardo:
#include <LowPower.h>

void setup() {
}

void loop() {
    USBCON = 0;
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

    USBDevice.attach();

    pinMode(13, OUTPUT);
    digitalWrite(13, HIGH);

    delay(10000);
    digitalWrite(13, LOW);
}

It disables the USB (USBCON = 0;), sleeps for 8 seconds, then starts the USB up again from scratch (USBDevice.attach();).  10 seconds later it sleeps again.
At the computer end, you get (on Linux):
[1242489.000014] usb 2-1.5.2: Product: USB IO Board
[1242489.000015] usb 2-1.5.2: Manufacturer: Arduino LLC
[1242489.000316] cdc_acm 2-1.5.2:1.0: ttyACM0: USB ACM device
[1242498.631563] usb 2-1.5.2: USB disconnect, device number 69
[1242507.068078] usb 2-1.5.2: new full-speed USB device number 70 using ehci-pci
[1242507.199628] usb 2-1.5.2: New USB device found, idVendor=2341, idProduct=0036
[1242507.199630] usb 2-1.5.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[1242507.199631] usb 2-1.5.2: Product: USB IO Board
[1242507.199633] usb 2-1.5.2: Manufacturer: Arduino LLC
[1242507.200256] cdc_acm 2-1.5.2:1.0: ttyACM0: USB ACM device
[1242517.063425] usb 2-1.5.2: USB disconnect, device number 70
[1242525.495729] usb 2-1.5.2: new full-speed USB device number 71 using ehci-pci
[1242525.627634] usb 2-1.5.2: New USB device found, idVendor=2341, idProduct=0036
.... etc ....

Initially I was trying not to use a library, but I forgot that I could check them to see what they did. I appreciate it very much, I'll definitely be spending some time studying this one.

The USBdevice.attach is in the core, not a library.

I was talking about lowpower lol. And really? I did not realize that, I assumed it was part of lowpower.

I simply put that [ USBDevice.attach(); ]  into my original code in wakeUp ISR, USBCON = 0 in my sleep(), and it works perfectly!

I only used lowpower for the sleeping cus it was convenient.


text:
Can I read using an analog pin on an arduino Mega whether or not there is a high (5v) voltage on a wire from another board's digital pin?
I am making a peer-to-peer network of initiating devices and a common hub, which controls most of the hardware. It sends a number over Serial to Mega's Serial1 (Mega's Serial is used for communicating to the computer), but as a fallback it initiates a general alarm by sending a 5v signal (using digitalWrite(pin, HIGH)) to the main board. In order to complete the circuit and get the read, how would I do this?
Thanks!

what you ask is purpose of a digital pin. to read a state of a digital pin of some other device

5V is a value of voltage, not a value of current .... please edit the title of your post

Yes of course you can. Better to use digitalRead() than analogRead() however.
You just need to tie the grounds of the 2 Arduinos together, and set up the pin on the Arduino you want to sense the input as INPUT or INPUT_PULLUP. Then do a digitalRead on the pin. It will return LOW if the other Arduino is setting the pin LOW, and HIGH if the other Arduino is setting it HIGH.
And, as Juraj points out in their comment, CMOS devices like Arduinos respond to voltage, not current. Their inputs are capacitive. They react to a voltage potential, not current. (When you initially change a CMOS input from one state to another a small amount of current flows in to change the state of the capacitor and after that the only current that flows is a very tiny amount of leakage current through the capacitor on the input.)

Thanks a bunch, I would not have thought of this myself. I'd have gone to the ends of the Earth over-engineering some code to beam signals off the moon and back just to say "HEY" to the other board lmao.

@duncan-c, you should not suggest in an answer on Arduino SE that LOW is  false and HIGH is true.

@Juraj, why shouldn't you suggest this? In my experience, we use switches that are normally open when in normal state, so closing them and closing a HIGH voltage would signify the change.

@WinterfromSYGMAH  HIGH / true, and LOW / false are different constants, and should not be used interchangeably. Juarj is correct. I edited my post.

@DuncanC and Juraj, thank you for the clarification and the help

formally, you should always write digitalRead(pin) == LOW or digitalRead(pin) == HIGH to check the state. there is no warranty that the value of LOW is 0 on all Arduino architectures. there could be some strange MCU package somewhere :-)


text:
sensor for illegal parking detection
I want to create a system that will detect illegal parking. I will place the sensor s to specific locations and when a car parks there the system will send a message to local authorities. My question is if a PIR is the suitable sensor for this project.
thanks in advance.

probably not - because people walking would trigger it

i think that it is a suitable sensor ..... some testing would be required to make sure that it is actually suitable for the specific application .....a question remains whether the local authorities would act on the message received

really thank you for the quick response and help. Do you think that propably  ultrasonic sensor would be a better choice or a  Laser tripwire?..

I'm assuming it will be communicating wirelessly. YellowBrick used to have transmitters under the parking spot. They would send a signal (to a satellite) every minute. But when there was a car parked on top, the signal would be blocked by the car. So they would know there's a car based on the missing signal.

Another option would be machine vision: https://hackaday.com/2019/02/04/sudo-find-me-a-parking-space-machine-learning-ends-circling-the-block/

Don't get discouraged, there are many ways to do this, but I would rate a PIR as being one of the worst options because even a bird or a squirrel could set it off. Plus, once the car has stopped you can't detect it's presence anymore with a PIR sensor, it has to be moving. I would recommend either using something like a webcam and OpenCV for this or if you're set on using an Arduino and physical sensors, multiple laser or multiple ultrasonic sensors placed 5-10 feet apart so that they both have to trip at once for positive detection of a vehicle instead of something else. You're going to have to spend some time experimenting and tuning. If you want something very reliable and you own the place, you could always do what the public street works does and cut a loop into the pavement and install a large steel cable and use inductance, but that may be overkill. ;)
Some other ideas:

Paint a pattern on the ground using high contrast paint and detect
when the pattern is completely covered.  Maybe there is something you
can do with IR reflective paint and use a camera with no IR filter,
this way you could make a pattern invisible to the eyes.
A carbon monoxide detector - Detects dinosaur powered vehicles, but
is nice to the environmentally conscious.

About a decade ago now I created my own parking detection using a Raspberry Pi and a webcam and some Perl code I wrote (non-opencv). I basically just detected the shadow contrast under the car and it worked very well. Originally I tried detecting red colors in the tail lights, but this was more troublesome due to other lighting in the environment. Especially at night. In my case, I didn't have direct access to set up physical sensors and lasers would have been too intrusive, so visual analysis made sense.


text:
Motor driver not working properly in case we connect motor to it
We are making a Bluetooth controlled RC car. when we connect our motor (moderate power) to motor driver then  Bluetooth module is automatically disconnected after taking initial command from Arduino code ,and if we connect our led (low power) instead of Motors to motor driver then project is working fine. what could be the possible problem?

Tell us which motor it is and which battery you use. The motor might ask ten times more current than the battery can deliver.

I am using a 4volts rechargeable battery with a supply of 2Ampere hour.and motors are of moderate power and taking current of 7 amperes each when connected independently to battery.

And motor driver is L298n type.

Can you give the brand and type of the battery and the motor and a link to them? Please add the extra information to your question. The l298n can be used with a 12v battery and a small motor, but not with a 4v battery. Do you know the stall current of the motor?

Ok let me try a 12volts battery to my setup.

Are those 12v motors?

@Jot, that appears to be a secret .... lol

These motors can also be run by 4volts supply. As you suggested to give motor driver 12volts supply,it worked fine. And thanks for your precious suggestions.

@jot ,if you want to help me more ,please post a circuit diagram showing different connections to arduino uno,motor driver l298n, and hc05 bluetooth module to the motors. Thanks in advance.

I used an external battery to supply the motor, and a BJT as a switch to trigger it (Base connected to Arduino).


text:
Keep motor moving
I have a problem on how to keep my stepper motor moving when button is released. It should only stop moving if I press the button again.
For now, stepper motor  is only moving IF the button is constantly pressed.
//Constants won't change. They're used here to set pin numbers:
const int buttonPin = 4;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin
const int dirPin = 8;        // the number of the motor direction pin
const int stepPin = 9;         // the number of the motor step pin

//Variables will change:
boolean flag = true;
int buttonState = 0;         // variable for reading the pushbutton status
int distance = 0;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(dirPin, OUTPUT);  //YELLOW
  pinMode(stepPin, OUTPUT); //ORANGE

  digitalWrite(buttonPin, LOW);
  digitalWrite(dirPin, HIGH);
  digitalWrite(stepPin, HIGH);
}

void loop() {
  buttonState = digitalRead(buttonPin); // Read the state of the pushbutton

  if (digitalRead(buttonPin) == LOW) {  // If pushbutton is pressed, buttonState is HIGH:
    digitalWrite(ledPin, HIGH);
    digitalWrite(dirPin, LOW);          // LOW=FORWARD DIRECTION
    digitalWrite(stepPin, HIGH);        // stepPin = MOTOR ON/OFF
    delayMicroseconds(100);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(100);
    distance++;
    if(distance > 21000){
      distance = 0;
      delay (3000);
      reverse();
    }
  }

  if (digitalRead(buttonPin) == HIGH){ // turn LED off:
    digitalWrite(ledPin, LOW);
    digitalWrite(dirPin, LOW);  //LOW = FORWARD DIRECTION
    digitalWrite(stepPin, LOW); //stepPin = MOTOR ON/OFF
    delayMicroseconds(100);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(100);
  }
}

void reverse() {
  digitalWrite(dirPin,HIGH); //HIGH = REVERSE DIRECTION
  digitalWrite(stepPin,HIGH);
  delayMicroseconds(100);
  digitalWrite(stepPin,LOW);
  delayMicroseconds(100);
  distance++;
    if(distance > 21000){
      distance = 0;
      delay(3000);
      return;
    }
  reverse();
}

1.) Please format your code. Left-aligned code is hard to read. It should be indented properly. That will also make it easier for you to spot problems. 2.) Use variables in order to name pins, e.g. pin 8 and 9. You have already done so for pin 4 and 13. Why not for 8 and 9? With names, people don't have to remember what number has what purpose

3.) if you want two different actions when a button is pressed, then you need to keep records of the current state. So you will need a vaiable like bool isMoving=true and toggle that on each button press.

N.b. your code is unreadable, so I won't attempt to debug your program, but I will present some pseudo-code that could help.

It should only stop moving if I press the button again ... [as of] now, [the] stepper motor is only moving IF the button is constantly pressed.

So what you need to do is save the state of your Motor, (MOVING, STOPPED, etc.) and base your code on that state.
You will also need to de-bounce your switch.
Your loop will have to:

Read & de-bounce the switch
Update the state based on switch
Run the stepper based on state

pseudo-code:
// include libraries etc.
#include <Stepper.h>

// set up your buttons pins etc.
int button = <pin>;
Stepper = step(...); // pins etc.

void setup()
{
   // do setup stuff...
}

enum MOTORSTATES {
  STOPPED = 1,
  FORWARD = 2,
}

MOTORSTATES state = STOPPED;

// forward declare your functions
bool isPressedDebounce(int pin);
void doStep(Stepper&, MOTORSTATES);
MOTORSTATES changeState(MOTORSTATES);

// loop is now simple
void loop()
{
  if(isPressedDebounce(button))
    state = changeState(state);

  doStep(step, state);
}

// because we have broken our problem into pieces
bool isPressedDebounce(int pin)
{
  // proccess and de-bounce the switch
  // implementation left as exercise for reader
}

void doStep(Stepper& step, MOTORSTATES state)
{
  // based on the state move the stepper
  // implementation left as exercise for reader
  switch(state)
  {
    case STOPPED:
      // DO IT
      break;
    case FORWARD:
      // DO IT
      break;
  }
}

MOTORSTATES changeState(MOTORSTATES state)
{
  // n.b. I used this pattern because it is the beginning of a state machine!
  switch(state)
  {
    case STOPPED:
      return FORWARD;
      break;
    case FORWARD:
      return STOPPED;
      break;
  }
}

I structured the pseudo code such that it contains a simple state machine, and can be easily extended. State machine code is very useful for programming Arduinos!

There are two issues:

You SHOULD pull-up or pull-down the input pin when using pushbutton.
You should detect the "press" and "release" event.

Two above issues are mentioned in this tutorial


text:
Losing value of variable
I am making a project involving the AutoConnect, ArduinoJSOn and LedControl libraries to fetch some values from an endpoint.
Basically what I do is connect to the internet, fetch the values from a JSON file in a given URL, store the values in variables and display the corresponding numbers in a 7segment module (using a max 7219 module).
Everything seems to work perfectly in the first iterations of the loop program, but after some iterations switching the values from one value to another, it starts to act strangely, as the input values changed on runtime:
[AC] WiFi.config(IP=0.0.0.0, Gateway=0.0.0.0, Subnetmask=0.0.0.0,
DNS1=0.0.0.0, DNS2=0.0.0.0) [AC] DHCP client(STARTED)
[AC] WiFi.begin()
[AC] Connecting........[AC] established IP:192.168.1.139
[AC] http server started
Wifi connected: 192.168.1.139
Connected to endpoint
Daily:13.37
Monthly:1111
4
13.37
4
1111
4
13.37
4
1111
4
13.37
4
1111
4
13.37
4
1111
2
h
0

2
h
0

2
h

As you can see in the previous serial output, after the 8th iteration, everything starts malfunctioning.
The output correlates with the number of digits that will be used in the 7-segment led module ( 4 ) and the number to display ( 13.37 and 1111 ). Then it starts getting the wrong values forever.
For getting the values in the JSON I use the following code:
void fetchJSONandPutValues(){

     HTTPClient http;  //Object of class HTTPClient
     http.begin(projectURL);
     int httpCode = http.GET();
     //Check the returning code
     if (httpCode > 0) {
      //Parsing
      const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
      DynamicJsonBuffer jsonBuffer(bufferSize);
      JsonObject& root = jsonBuffer.parseObject(http.getString());
      // Parameters
      daily = root["daily"];
      monthly = root["monthly"];
      // Output to serial monitor
      Serial.print("Daily:");
      Serial.println(daily);
      Serial.print("Monthly:");
      Serial.println(monthly);

      finalDaily = (char *) daily;
      finalMonthly = (char *) monthly;
    }

    http.end();   //Close connection

   //setLCDValues(daily);
}

For displaying the numeric values in the 7-segment module I have made this function:
void setLCDValues(char * value){

  int charsInValue = strlen(value);
  boolean decimalPoint = false;
  int numLEDElements = charsInValue;
  char cleanedValue[8] ;

  //look for point position
  int positionPoint = 999;

  for (int i = 0; i < charsInValue; i++){
    if (value[i] == '.')
    {
      positionPoint = i;
      numLEDElements -= 1;
      break;
    }
  }

  int j = 0 ;
  for (int i = 0; i < charsInValue; i++){
    if (value[i] != '.')
    {
      cleanedValue[j] = value[i];
      j++;
    }
  }

  Serial.println(numLEDElements);

  for (int i = 0; i < numLEDElements; i++){

    if ( i == positionPoint -1 )
    {
      ledDisplay.setChar(0, numLEDElements -1 - i, cleanedValue[i], true);
    }
    else
    {
      ledDisplay.setChar(0, numLEDElements -1 - i, cleanedValue[i], false);
    }
  }
}

And in my loop() I have the calls to setLCDValues:
currentMillis = millis();

if (currentMillis - previousMillis >= interval){

      previousMillis = currentMillis;

      if (showDaily)
      {
        setLCDValues(finalDaily);
        showDaily = false;
        Serial.println(daily);
      }
      else
      {
        setLCDValues(finalMonthly);
        showDaily = true;
        Serial.println(monthly);
      }
}

I am guessing the problem I have here might be related to using pointers, although I haven't found yet the issue here. Could it be a problem with one of the libraries ? (ArduinoJSON?)

you fragment the memory heap with DynamicJsonBuffer and http.getString()

Thanks for pointing in the right direction, @Juraj - I will try to change the DynamicJsonBuffer to a StaticJsonBuffer (as stated in https://arduinojson.org/v5/doc/memory/ )  when I get back home.

@Juraj , you were totally right here, changing the DynamicJsonBuffer to a StaticJsonBuffer solved the memory leak. Although I don't understand the issue about using the http.getString(). How does this function fragments the memory and what would be a good alternative to it?


text:
Serial Port not recognized by Arduino IDE
I’m attempting to connect with a Adafruit Huzzah Feather ESP8266 board. I’m running a 2018 mbp with Mojave. I loaded the Silabs driver (CP210) to connect with the onboard UART on Huzzah board. I got the Arduino IDE 1.8.8 installed and loaded the 2.5.0 ESP8266 library (I also tried library 2.4.2).
The serial port appears  in the IDE (SLAB_USBtoUART). It also appears when I run the /dev/tty.* command and in About this Mac. From the IDE when I try to Get Board Info. Nothing. I get the message “Native serial port, can’t obtain info”. Everything seems good, except nothing from the IDE. I pulled up CoolTerm, set it the port and hit the reset on the Huzzah. I see data after hitting reset.
I run the Huzzah board from a powered USB hub through one of the USB-C ports. Tried different combinations, no luck.
I have a very old WIn7 machine, loaded everything like on my mbp, there I can get board info. I would run the IDE on it, except the machine is sooo slow. I would very much like to get it working on my mac. It seems so close, but no cigar.

did you try to upload to the board? the "Get Board Info" works only with some Arduinos

Yes, on the win7 machine I was able to upload to the board.

and on Mac? do you have same error message? turn on verbose mode in Preferences.

I solved the problem. Thanks to @Juraj for suggesting turning on verbose mode. Thanks. Not getting Board Info from the IDE, I figured the port wasn't working. Ignoring the Board Info problem, I went to compile and upload a simple program. Without verbose mode on, it looked like it wasn't connecting up. In reality it was a problem with the esp8266 libraries. After fixing that issue all is good.

Download usb port driver from the link below
http://www.wch-ic.com/downloads/CH341SER_EXE.html

Adafruit Huzzah Feather ESP826 has CP2104 as USB chip, not CH340


text:
EEPROM.read data not comparing with DHT11 sensor value - Arduino temp controller
I'm using a DHT11 to read temperature to control a relay that will control a fan. When 'A' is pressed it allows the user to update the temp value that the relay will go HIGH at. The value is being stored and read to and from the EEPROM but they are not being compared properly in the if statement. Please help!
#include <EEPROM.h>
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <dht11.h>
dht11 DHT;

char temperature[2];
char initial_temperature[2];
char new_temperature[2];
char key_pressed=0;

const int relay = 8;
const int dht11_data = 6;
int temp=0;
int relayState = LOW;
int i=0;
int j=0;
int init_pass = 0;

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {38, 40, 42, 44};
byte colPins[COLS] = {46, 48, 50, 52};

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

 //initialize an instance of class NewKeypad
 Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

 void setup() {
 Serial.begin(9600);
 pinMode(relay, OUTPUT);
 digitalWrite(relay, relayState);
 lcd.begin(16,2);
 lcd.print("  Welcome to ");
 lcd.setCursor(0,1);
 lcd.print("     Test 2");
 delay(2000);
 lcd.clear();

   }

void loop() {

DHT.read(dht11_data);
temp=DHT.temperature;

lcd.clear();
lcd.setCursor(5,0) ;
lcd.print("Temp");            //display"Temp="
lcd.setCursor(5,1);
lcd.print(temp);
lcd.write(0xDF);              //Display custom characters '°'
lcd.print("C");

delay(200);
initialtemperature();

       // here is the problem - comparing temp>=init_pass
 // 'temp' will not compare with value of 'init_pass'
 // like it does with a number value in it's place.

for(int j=0;j<2;j++){
init_pass = (initial_temperature[j] - '0');

if (temp >= (init_pass)){

 if(init_pass==2)
   relayState = HIGH;
   digitalWrite(relay,  relayState);

   Serial.print(init_pass);
  }
  }

 key_pressed = customKeypad.getKey();
 if(key_pressed=='A')
 change();
}

void change(){
  j=0;
int i=0;
Serial.begin(9600);
lcd.clear();
lcd.print("FanOn Temp=");
lcd.print(initial_temperature);
// Serial.print(initial_temperature);
lcd.write(0xDF);
lcd.write("C");
lcd.setCursor(0,1);
lcd.print("New Temp=");
delay(200);
while(i<2)

{

char pressed=customKeypad.getKey();
if(pressed){
  new_temperature[i++]=pressed;
  lcd.print(pressed);
  EEPROM.write(j,pressed);
  j++;
}

pressed=0;

}
if(i==2){
lcd.write(0xDF);
lcd.write("C");
delay(1000);
lcd.clear();
lcd.print("Saved");
delay(1000);
  }
  }

 void initialtemperature(){

for (int j = 0; j < 2; j++)
initial_temperature[j] = EEPROM.read(j);

}

temp is not comparing with init_pass ... if (temp >= (init_pass)){
if(init_pass==2)
relayState = HIGH;
digitalWrite(relay,  relayState);
Serial.print(init_pass);
}

btw it was formatted until I posted it... not sure what I did

print as in Serial.print? I was using that for testing. If you mean something else, can you provide an example?

Don't post >100 lines of code and say something vague like "... they are not being compared properly in the if statement." Delete code that isn't germane to your question, and point out the specific line that is giving you trouble (along with a description of any setup or context we need in order to understand the line in question.)

the problem starts at: if (temp >= (init_pass)){     comparing temp>=init_pass
'temp' will not compare with value of 'init_pass'  like it does with a number value in it's place.

Everything in this sketch works up to this point.

you are misunderstanding the problem ..... the if (temp >= (init_pass)){ also works correctly ..... it just does not give the results that you expect because the two values are not what you think they are     ........ as per my previous comment, what were the values of temp and init_pass and the length of temp and init_pass before the if statement?

So, to my understanding temp is a numeric or a integer value? and init_pass is converted to ASCII DEC value by using init_pass = (initial_temperature[j] - '0');? ...and the length off both is 2. it seems i either need to find a way to convert the 2 characters to one byte or write the value as one byte to begin with?


text:
Can I configure pairing for HC-05 and Arduino, and use the HC-05 without Arduino after?
I have a system that is outputting data via its serial, and I need to relay that data to my PC wireless-ly. If I were to setup an Arduino and HC-05 at the system's side to relay the data, that would mean I need to use two serial ports. I know this could be done with SoftwareSerial library. However, I would like to know if I could set up the pairing between master and slave with arduino, then unplug the HC-05 from the Arduino, and connect it directly to the system's serial output. Would this work?
Edit for clarification:

I do not want to use SoftwareSerial
I do not want to use an MCU during normal operations
I want the HC-05 to take in serial data from a system's serial, and transmit it via bluetooth to my PC
Only during pairing configuration, will I want use an MCU (Arduino) to set it up. I want to know if the comms will still work when I take out the Arduino and connect the system's serial data output to HC-05's Rx instead.

Is this possible?

configure the HC-05 and pair it, then power it down .... power up again and run a sketch like the one in this question and test connectivity with serial monitor .......  https://arduino.stackexchange.com/questions/61469/does-baud-rate-for-hc-05-bluetooth-module-need-to-match-the-serial-monitor/61510#61510

I haven't built anything yet, I am just going through design planning before building it. Preferrably, I do not want to use SoftwareSerial. My idea is to pair it up with Arduino, and get the HC-05 to trasmit whatever serial data that comes into its Rx from the system - without an Arduino in place.

i understand your requirements .... the comment describes a process for confirming that the HC-05 retains its settings when powered off

IIRC, you can pull up (or leave unconnected) the KEY pin of the HC-05. Then it will act as the transparent serial connection you want.


text:
Reading a monochromatic bitmap with Arduino for plotting
Complete newbie here.
I am following this thread:
How to read bitmap image on Arduino
Specifically the third reply from : frarugi87 in my attempt to plot a monochromatic bitmap image with a plotter device.
Basically: bitmap>SD card board>arduino uno> plotted image
I attempted to modify their code to work with monochromatic bitmaps and removed the print to file function:
    // MODIFIED CODE FROM BELOW CONTRIBUTOR

    // (c) Michael Schoeffler 2016, http://www.mschoeffler.de

    #include <SD.h> //Load SD library
    int chipSelect = 4; //chip select pin for the MicroSD Card Adapter
    File file; // file object that is used to read and write data

int32_t readNbytesInt(File *p_file, int position, byte nBytes)  // FUNCTION WHICH READS A DETERMINED AMMOUNT OF BYTES INTO A SINGLE VARIABLE
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result;
}

    void setup() {
      Serial.begin(9600); // start serial connection to print out debug messages and data

      pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode
      if (!SD.begin(chipSelect)) { // Initialize SD card
        Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
      }

      if (SD.exists("bitmap.bmp")) { // if "bitmap.bmp" exists, say so
        Serial.println("Found The Bitmap File.");

      }

      file = SD.open("bitmap.bmp", FILE_READ);   // open the file to an object for reading

      // DETERMINE HOW LARGE THE BITMAP FILE IS
      int howmany;
      howmany = file.available();
      Serial.println(howmany);    // print the how large the file is

      // DETERMINE STARTING IMAGE ARRAY LOCATION IN THE BITMAP FILE
      int32_t dataStartingOffset = readNbytesInt(&file, 0x0A, 4);
      Serial.println("The starting location in the fiile is...");
      Serial.println(dataStartingOffset);

      // DETERMINE THE IMAGE HEIGHT AND WIDTH
      int32_t imgwidth = readNbytesInt(&file, 0x12, 4);
      Serial.println("The image width is the following pixels:");
      Serial.println(imgwidth);
      int32_t imgheight = readNbytesInt(&file, 0x16, 4);
      Serial.println(imgheight);

      // MODIFIED CODE. DOES THE COLOR DEPTH LOCATION WORK IN THE BITMAP AND DOES IT GIVE CORRECT INFO ABOUT THE FILE?
      int16_t pixelsize = readNbytesInt(&file, 0X1C, 2);
      if (pixelsize != 24)
      {
        Serial.println("This image is most definitely not 24 bpp");
        Serial.println(" it is actually a depth of :");
        Serial.println(pixelsize);

      }

       file.seek(dataStartingOffset);   //skip bitmap header and go directly to the image data array.

     /*  for(int32_t i = 0; i < imgheight; i ++) {
        for (int32_t j = 0; j < imgwidth; j ++) {
            B = file.read();
            Serial.println("height and width location from bottom");
            Serial.println(i);
            Serial.println(j);
            Serial.println("B");
            Serial.println(B);
        }
        Serial.println("height advance");
    }

*/
      int B;

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

            B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

        B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

            B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

            B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

        B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

    file.close();

    Serial.println("done write");

    }

But when I read a 16x16 monochromatic bitmap: see below

At what I assume is the color table starting location (given by dataStartingOffset variable).
I get strings two bytes of correct color information, followed by two bytes of just...zeros.
Is this a bitmap formatting thing?
Serial output for 16x16 bitmap looks like this:(only up to 9 of the 16 lines starting from the bottom)

Found The Bitmap File. 126 The starting location in the file is... 62
  The image width is the following pixels: 16 16 This image is most
  definitely not 24 bpp  it is actually a depth of : 1 1111111 11111110
  0 0 11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0
  11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0
  11111111 11111111 0 0 1111111 11111110 0 0 done write

And when I try to read a bitmap that is around 200 x 200 pixels, I get very strange height and width numbers that are negative and my above code does not work at all!
Does a 16x16 bitmap have different byte structure formatting than a 200x200?
Any help is appreciated. Again, I am a complete newbie here. I am just trying to figure out how to read a bitmap.

did the code work before you started to modify it?

check  your bitmap  file format here .... https://hexed.it/

That I do not know. It does give me correct values for a 16x16 monochromatic bitmap image (well...including the unwanted zeros), and the code seems straightforward, but I never tested it with a COLOR bitmap. I assume the person tested their code before posting.

never assume anything, but the code in that answer is very nicely formatted, so i would tend to trust it also ....... like i implied in my first comment, run the code unmodified

BMP file format table ..... http://www.ue.eti.pg.gda.pl/fpgalab/zadania.spartan3/zad_vga_struktura_pliku_bmp_en.html

I do agree on that. Test to see if the code works first. I'll try it with a color bitmap tomorrow and see what turns up.

Bitmap files (.BMP) have to have a row size that is a multiple of 4 bytes. Any extra space in a row has to be padded with 0.
Since your rows are 16 pixels wide that equates to 2 bytes. That's not a multiple of 4, so it is padded with to bytes of 0 to make it a multiple of 4.
Your code needs to take that into account and know that if it hasn't read a multiple of 4 bytes then to read enough "dummy" bytes to get to the start of the next row.
Also, note that BMP files are the only files in the known universe where the image data is stored upside down (starting lower-left corner instead of upper-left corner).

ah. That makes sense. Thanks for clarification. Any idea why I would be having confusion with larger bitmaps , like 200x200? The color table "start position" ends up being a very large negative number using the code that I posted.

Bitmaps come in numerous different data formats. You should inspect the header to find out what type it is. Here is a library for my chipKIT DisplayCore system (doesn't work with Arduino, only chipKIT), but feel free to take what you like from it.

A side note, Postscript and PDF also has the (0,0) origin at the lower left corner of the defined page area. One could possibly argue they are not image formats, but they do describe "ink" on a "page"


text:
Bool function for color variables
I am new of using Arduino.
I have seen code for color variables that has uses bool function. Is there anyone who can say me how this function connect to the colors of RGB LED matrix? This code has written for Arduino Due and the RGB LED matrix is 32*32.
// Non-constant variables
// Color variables
bool R [32][32] = {1};
bool G [32][32] = {1};
bool B [32][32] = {1};

bool is a data type, not function. you have 3 two dimensionals arrays of booleans. boolean is a datatype for true/false but the size of bool is 8-bit

Without the rest of the code one can only guess why the original author did what they did.  But this appears on the surface as a terrible wast of data space.

// Non-constant variables  .... from this comment line you can tell that the author of the software may not have been thinking clearly


text:
Troubleshooting Program using sensors and actuators
I am doing a project on waste management. I have to separate waste majorly as metal, plastic and other materials. For that using Arduino Mega 2560. I have connected Inductive proximity sensor @ A0 (Anolog pin 1 of Arduino) & Capacitive proximity Sensor @ A1(analog pin 2 of Arduino). The two 5V DC motor which are to be used as actuators when the sensors sense the object.
I have given 12 V to the 2 sensors and I have directly connected the sensor's output pin with arduino.
If the Inductive sensor senses any metal object in the conveyor, the dc motor which is a actuator here has to rotate forward, wait sometime and to rotate reverse and stay until the next sense started.
The same for capacitive sensor.
But the problem was there is even though the sensor is not sensing the motor is running. The motor keeps on running forward, delayed and reverse. Please help me out for this, I don't know where I have done the mistake.
The program I have tried is here:
#define motorpin1 4 \\dc motor's pin 1
#define motorpin2 5 \\dc motor's pin 2
#define motorpin3 6 \\dc motor's pin 3
#define motorpin4 7 \\dc motor's pin 4

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(A0,INPUT);
  pinMode(A1,INPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
if((analogRead(A0)<400) && (analogRead(A0)>100)
{
  digitalWrite(motorpin1,HIGH);
  digitalWrite(motorpin2,LOW);
  delay(5000);
  digitalWrite(motorpin1,LOW);
  digitalWrite(motorpin2,HIGH);
  delay(5000);
  digitalWrite(motorpin1,LOW);
  digitalWrite(motorpin1,LOW);

}
if((analogRead(A1)<400) && (analogRead(A1)>100)
{
  digitalWrite(motorpin3,HIGH);
  digitalWrite(motorpin4,LOW);
  delay(5000);
  digitalWrite(motorpin3,LOW);
  digitalWrite(motorpin4,HIGH);
  delay(5000);
  digitalWrite(motorpin3,LOW);
  digitalWrite(motorpin4,LOW);

}

That sketch does not compile. We like to see the sketch that causes the problem that you describe. Can you tell more about the sensors? Can you tell us the brand, type, and a link to them please. What is connected to pin 8 and 9?

And what is the circuit like? I mean, how are the sensors and actuators connected?
Maybe you have an "open collector" sensor, and consequently need a pull-up/pull-down, maybe your sensor sends you a "reverse" voltage value.
For sure your code can be improved by removing all those delays and properly designing the phases, otherwise the board will become "blind" to the other sensor when moving one actuator

what are the outputs of the two sensors like? ..... forget about the motors for now ..... write a sketch that prints out the output values of the sensors and add the findings to your question


text:
Define preset colors using FastLed library
I'm using an addressable 150 led strip and an Arduino Nano to control it, using FastLed library.
I'm tring do create a function turn_on_leds, which gets 4 parameters:
1) delay time for lighting a led in the loop, 2) direction ( not relevant for now), 3) color index for colors array , 4) brightness percentage.
Problem #1: a color array is defined to select from a preset definitions of colors (Fastled reference, but when selecting col_indx =2, meaning colors[2], leds are not lit in Red as they should, AND when setting leds[i]=0xFF0000, the right result is set.
Problem #2: at loop there is a for intended for raise bightness from 0 to 100, BUT the results are 0 for first iteration and 9 for all others.
Appreciate any HELP!!
Guy
Code:
#include <FastLED.h>

#define NUM_LEDS 10
#define BRIGHTNESS  55
#define DATA_PIN 7

char *colors[] = {0x000000,0xFFFFFF,0xFF0000,0x008000,0x0000FF}; // black, white,r,g,b
CRGB leds[NUM_LEDS];
int t = 0;

void setup() {
  Serial.begin(9600);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  //  FastLED.setBrightness(BRIGHTNESS);
}

void turn_leds_on(int del_1, bool dir_1, int col_indx, int bright_1) {
  if (dir_1 == true ) { // start to end
    for (int i = 0; i <= NUM_LEDS; i++) {
      leds[i] = 0xFF0000;//colors[col_indx];
      FastLED.setBrightness(bright_1*255/100);
      FastLED.show();
      delay(del_1);
    }
  }
}

void loop() {
  Serial.println(t);
  turn_leds_on(50, true, 2, 100);
  delay(1000);
  //  turn_leds_on(50, true, 0, t);
  //  delay(1000);

  if (t < 100 ) {
    t += 10;
  }
  else {
    t = 0;
  }
}

Your colors array should be CRGB type, not char *.
CRGB colors[] = {0x000000,0xFFFFFF,0xFF0000,0x008000,0x0000FF}; // black, white,r,g,b

For your second problem - you are overflowing the bounds of your LEDs array:
for (int i = 0; i <= NUM_LEDS; i++) {
  leds[i] = 0xFF0000;//colors[col_indx];

You are going from 0 to 10 inclusive. That's 11 iterations. There is no such array slice as leds[10], so the value you write to it ends up overwriting the next two bytes in memory - and those happen to be occupied by the variable t.

thank you. that solved problem 1, what about 2 ?

@Guy.D You are overflowing the bounds of an array.

OMG , you are so RIGHT.  ThankYou!


text:
if/else on digitalRead not executing on 'else' portion
I am a beginner with C++ but used to be good with BASIC (2 decades ago lol). I'm building a peristaltic metered doser that allows you to input desired mL on a 4x4 keypad and then when 'fill' button is pressed it doses the desired mLs through the peristaltic.
I'm still drafting/printing the peristaltic housing and all of that but in the meantime I want to get as much of the coding done as possible. It's still incomplete, but one of the functions I want the doser to have is a 'PRIME/FLUSH' button.
Originally I wanted the button to run the pump as long as the button is held down to prime the tubing with solution or flush the tubing with DI water. But I haven't had luck figuring out how to use a 4x4 button in momentary switch mode.
A workaround I had was to have the button be an on/off button. So press it once, pump turns on, press it again, pump turns off. Since the pump isn't printed yet I've been using the onboard LED as a tester for the coding (hence the LED_BUILTIN).
The issue, from my research I figured what I would need was an if/else statement. When the button is pressed (in this case the 'a' button), it reads the LED_BUILTIN status and if its HIGH it turns it off and if its LOW it turns it on.
But the 'if' part is working, it turns it on, but the 'else' part is not. When the LED is already on and the 'a' button is pressed, it stays on and doesn't rewrite to LOW.
Code below, any advice?
#include <KeypadShield.h>

KeypadShield keypad;

#include <LiquidCrystal_I2C.h>
#include <Wire.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

char Data[15];
byte data_count = 0;

int x;

char customKey;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  keypad.begin();
  lcd.begin(20,4);
    lcd.setCursor(4,0);
    lcd.print("Let's Fill!");
    lcd.setCursor(4,1);
    lcd.print("Designed by");
    lcd.setCursor(4,2);
    lcd.print("JP");
    lcd.setCursor(5,3);
    lcd.print("2019 v1.0");

    delay (2000);

    lcd.clear();

    lcd.setCursor(1,0);
    lcd.print("Enter volume in mL");
    lcd.setCursor(3,1);
    lcd.print("on keypad then");
    lcd.setCursor(5,2);
    lcd.print("press DONE");
    lcd.setCursor(0,3);
    lcd.print("mL:");
}

void softReset()
{
asm volatile ("  jmp 0");
}

void loop()
{
    customKey = keypad.getNextKeypress();

    if (customKey)
    {
      if (customKey == 'a')
      {
        if (digitalRead(LED_BUILTIN == LOW))
        {
          digitalWrite(LED_BUILTIN, HIGH);
          lcd.clear();
          lcd.setCursor(5,1);
          lcd.print("FLUSHING");
        }
        else
        {
          digitalWrite(LED_BUILTIN, LOW);
          lcd.clear();
          lcd.setCursor(1,0);
          lcd.print("Enter volume in mL");
          lcd.setCursor(3,1);
          lcd.print("on keypad then");
          lcd.setCursor(5,2);
          lcd.print("press DONE");
          lcd.setCursor(0,3);
          lcd.print("mL:");
        }
      }

      if (customKey == 'd')
      {
       softReset();
      }

      if (customKey != 'p' && customKey != 'a' && customKey != 'b' && customKey != 'c' && customKey != 'd' && customKey != 's')
      {
        Data[data_count] = customKey; // store char into data array
        lcd.setCursor(data_count+3,4); // move cursor to show each new char
        lcd.print(Data[data_count]); // print char at said cursor
        data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
        x = atoi (Data); //convert string to integer 'x' for use in equations
      }

     if (customKey == 'p')
      {
       lcd.clear();
       lcd.setCursor(7,0);
        lcd.print(x);
        lcd.setCursor(Data[data_count]+13,0);
        lcd.print("mL");
        lcd.setCursor(0,1);
        lcd.print("FILL --> fill");
        lcd.setCursor(0,2);
        lcd.print("RESET --> change mL");
        lcd.setCursor(0,3);
        lcd.print("FLUSH --> finish");

      }
    }
};

digitalRead(LED_BUILTIN) == LOW move the ). (you read a LED?)

Holy crow... thanks Juraj. Brain fart right there... that fixed the issue! And yes, the LED right now is just a placeholder for my peristaltic pump (once I finish drafting and printing the housing). I'm just using it to make sure everything works. Thanks again!

the pump can be read?

@Juraj I was thinking I could read whether or not the pump was on or off, or some variation of the concept

by accident on Uno you will read the pin state last set, but better have a state variable

You may remove the ';' at the very end of the sketch. If you do not know all the consequences of a soft reset, then you should not use it. We don't use it, for a good reason. When the microcontroller of the arduino uno is powered on, everything is in a off-state. That means that no internal parts (timers, bus controllers, and so on) needs to be initialized. That's why it is so easy to use for small projects and for an arduino board. With a soft reset, you continue at the beginning of the code. If something was wrong and in a wrong state, then the soft reset might make it worse.

(Heh... before even seeing the code I guessed you'd done this...)
You are comparing a pin number, not the results of digitalRead(), and then passing the results of that comparison to digitalRead():
if (digitalRead(LED_BUILTIN == LOW))

It should read:
if (digitalRead(LED_BUILTIN) == LOW)

Note the order of the brackets:  LED_BUILTIN is passed to digitalRead(), and then the result of calling that function is compared to the value LOW.

Thanks Majenko! Major brain fart on my part... but that solved the issue. haha. Spend so much time looking for the big problems that the little ones just stay right under your nose...

@Jay Absolutely. It's called "Code Blindness".