text:
Error compiling code for Arduino/Genuino Uno

Arduino: 1.8.6 Hourly Build 2017/10/20 02:33 (Windows 10), Board:
  "Arduino/Genuino Uno"
c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe:
  unable to rename 'core\core.a'; reason: Permission denied
exit status 1 Error compiling for board Arduino/Genuino Uno.
This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

Please help me fix this problem. This is my code:
int redled = 6;
int yellowled = 9;
int greenled = 12;

void setup() {
  pinMode (6, OUTPUT);
  pinMode (9, OUTPUT);
  pinMode (12, OUTPUT);
}

void loop() {
  digitalWrite (redled, 1);
  delay(9000);
  digitalWrite (redled, 0); //stopped
  digitalWrite (yellowled, 1);
  delay (3000); // yellowled lights for 3 sec.
  digitalWrite (yellowled, 0);
  digitalWrite (greenled, 1);
  delay (9000);
  digitalWrite (greenled, 0);// greenled starts flashing
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
}

Why are you running an hourly build? What did you expect?

There are some reports of this error in the Arduino IDE issue tracker: https://github.com/arduino/Arduino/issues/5616 and https://github.com/arduino/Arduino/issues/4683 where it was found to be caused by antivirus software

Explanation is in your question : c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

please use digitalWrite (redled, 1); HIGH and LOW in digitalwrite instead of 1 and 0.

In what way does this answer the question?

The problem is just what the error message says it is.

c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

When you are compiling your code the compilation process is trying to rename a file called core.a (.a means a library). I'm guessing it is doing this because you have changed the board type and it needs to compile the library for that type of board.
You don't have permission to change this file. This could be because:

You don't have Windows security permission.
The file is in use already.
It's because you have installed it on your desktop.

The easiest to check is 2, reboot you machine and start only one instance of the IDE and try again. If it works, something (don't ask what) was accessing the file.
If it doesn't work you need to change the security permissions of the parent folder and all sub folders and files. You will need to Google how to do that, and you will need to search for core/core.a.


text:
Trouble in acquiring NEO6M GPS data through S-Function builder at Matlab simulink using Arduino libraries
I have connected a NEO6M GPS module to an Arduino Mega 2560 and programmed using TinyGPS++ library's "Device Example". I am getting proper data at serial port.

NEO6MGPS to ArduinoMega2560
Vcc           3.3volts
GND           GND
TX            Pin10
RX            Pin9

I have created S-function for NEO6M-GPS for ArduinoMega2560 at Matlab to output latitude longitude alone from TinyGPS++ "Device Example" code with following:
Initilization:
No of discrete states:1
Sample mode: Discrete
Sample time value: 0.1

Data Properties:
Two "Output ports" are defined latitude & longitude of data type int32

Libraries:
#ifndef MATLAB_MEX_FILE
#define ARDUINO 100
#include <Arduino.h>
#include "TinyGPS++.h"
#include "TinyGPS++.cpp"
#include "SoftwareSerial.h"
#include "SoftwareSerial.cpp"
TinyGPSPlus gps;
SoftwareSerial ss(10, 9);
#endif

Outputs:
    if(xD[0] == 1)
    {
      #ifndef MATLAB_MEX_FILE
      while (ss.available() > 0)
      gps.encode(ss.read());
      if (gps.location.isValid())
      {
        latitude[0]=gps.location.lat();
        longitude[1]=gps.location.lng();
      }
      else
      {
        Serial.print("0");
      }
      #endif
    }

Discrete Update:
    if(xD[0]!=1)
    {
      # ifndef MATLAB_MEX_FILE
      Serial.begin(115200);
      ss.begin(9600);
      # endif
      xD[0]=1;
    }

Note: I am successful in building the s function and changing the wrapper name to .cpp and editing with addition of extern "C" at appropriate lines. And able to deploy on target hardware.
"### Done invoking postbuild tool."  "### Successfully generated all
binary outputs." AVR Memory Usage
---------------- Device: atmega2560 Program:   11082 bytes (4.2% Full) (.text + .data + .bootloader) Data:       1066 bytes (13.0% Full)
(.data + .bss + .noinit)

During live simulation run I don't observe any output in the scope/display.
My question is do I have any logical errors in writing code at "output" part of s-function or misplacing the code at other fields of s-function ?
I am okay to change my library, all I need is latitude and longitude displayed at simulink. Please do suggest necessary changes to be made.

Can someone help on this issue ?

Did you manage to figure this out?

source: Stack Exchange

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

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

sort: votes


text:
What are the parameters of the browseUrl() callback in the Ethercard library?
I'm reading a code that uses Arduino as a webclient and when he tries to catch the info from the site, he uses a callback with the following parameters:
static void response_callback (byte status, word off, word len)

Can anyone explain me how does each one of this parameters work exactly?
PS.: The example I got it from:
#include <EtherCard.h>

#define HTTP_HEADER_OFFSET 0
static byte mymac[] = {0x12,0x34,0x56,0x78,0x90,0xAB};
char website[] PROGMEM = "www.yourwebsite.com";

byte Ethernet::buffer[700];
static uint32_t timer = 0;

static void response_callback (byte status, word off, word len) {
  Serial.print((const char*) Ethernet::buffer + off + HTTP_HEADER_OFFSET);
}

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

  if (!ether.begin(sizeof Ethernet::buffer, mymac, 10))
  {
    Serial.println("Failed to access Ethernet controller");
    while(1);
  }
  else
    Serial.println("Ethernet controller initialized");
  Serial.println();

  if (!ether.dhcpSetup())
  {
    Serial.println("Failed to get configuration from DHCP");
    while(1);
  }
  else
    Serial.println("DHCP configuration done");

  if (!ether.dnsLookup(website))
  {
    Serial.println("DNS failed");
    while(1);
  }
  else
    Serial.println("DNS resolution done");

  ether.printIp("SRV IP:\t", ether.hisip);
  Serial.println();
}

void loop() {
  ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 5000;
    ether.browseUrl("/", "yourpage.php", website, response_callback);
  }
}

Where do you get that callback signature?

Just added the example I got it from

The Arduino world indeed often lacks traditionally detailed API documentation.  One fallback is to do a full-text search (with a GUI tool or grep -R ) of the library folders and installation for the function name, and find its actually source code to study.

Apparently, the callback is executed on every packet which arrives by the browseUrl call.
"off" and "len" are pointers to the Ethernet buffer holding the data. "Off" are the initial value (offset) and "len" (length) is the amount of data received.
"byte status", I am not sure what it means, but it's very likely will be some kind of error code. It's not being used in any sample I am seeing, so I am really wondering what it means...
Check this link for a fully working sample
Callback here are called browseUrlCallback1 and browseUrlCallback2.
Can't figure out a link with the detailed documentation. If someone has it, please post it.

Could it be this product: http://jeelabs.org/pub/docs/ethercard/ ?

Yeah, but as all I have found, it lacks specific documentation about callback details. BrowseUrl is well documented as usual, but it just specifies how the callback method has to be defined, not what does each parameter mean.

Thats exactly my problem, I can't find its documentation anywhere!
Btw, thx for the response!

It's all in the source. In the file tcpip.cpp in the ethercard-master.zip you find the function static uint8_t www_client_internal_result_cb. There you see how status is derived from the HTTP status code, like uint8_t f = strncmp("200",(char *)&(gPB[datapos+9]),3) != 0;. Why waste any other space in a docfile nobody likes to write or even read?

They are not actually pointers.  "off" is presumably an offset index while "len" is a count or size.

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

authors: Дмитрий Семенов

authors: Наташа Люкшина


text:
Arduino Uno simple LED example with pointers
I am new to Arduino and I have recently started off by trying to turn on an LED connected to pin 13 on my Arduino Uno using pointers.
I opted to do this with pointers because this would give me a better understanding on what really goes behind when I use predefined Arduino functions.
My simple code looks like this,
uint8_t *data = (uint8_t *) 0x05; //PortB data register ptr (Since pin 13 is PB6)
uint8_t *dir = (uint8_t *) 0x04;  //PortB dir register ptr (Since pin 13 is PB6)

void setup() {
    *dir = 0x40;  //PB6 direction set to O/P
    *data = 0x40; //PB6 data set to 1 to turn on the LED
}

void loop() {
  *data = 0x40;
}

I tried the same program using   pinMode(13, OUTPUT) and digitalWrite(13, LOW) functions and it works fine. But I do not understand what could be wrong with my pointers. If you find anything wrong, kindly let me know.

"I opted to do this with pointers because this would give me a better understanding on what really goes behind when I use predefined Arduino functions." No it won't.

I would like to really access the registers on my own rather than through functions. I know it would be easier with functions but I want to do this to understand register access better. Moreover behind a function like pinMode, I do beleive that all it does is write a bit onto a register which I would like to do on my own for starters.

But using pointers won't help with that.

You made two small mistakes:

The addresses of the I/O registers are 0x24 for DDRB and 0x25
for PORTB. The numbers you used are I/O port numbers, but since
pointers are supposed to point to memory, you have to use the
memory-mapped addresses instead.
Pin 13 is PB5, not PB6.

With these two mistakes fixed, your code works as expected. There are
still two issues however:

Under some circumstances, the compiler can optimize away some writes
to these registers. You have to qualify the pointers as “pointer to
volatile data” in order to avoid this. Even if your simple example
does not show this problem, it is always safer to use the qualifier.
The compiler generates inefficient code. Not as inefficient as
digitalWrite(), but still... It knows how to optimize, but it is
prevented to do so by the fact that your pointers are modifiable. You
should qualify them as const if you want to benefit from compiler
optimizations.

With those fixes, your pointer definitions would look like:
volatile uint8_t * const data = (uint8_t *) 0x25;
volatile uint8_t * const dir  = (uint8_t *) 0x24;

and access to them gets compiled into efficient in ans out assembly
instructions.
That being said, if you want to do direct port access, I would recommend
doing it the avr-libc way:
void setup() {
    DDRB  = _BV(PB5);
    PORTB = _BV(PB5);
}

void loop() {
    PORTB = _BV(PB5);
}

The way the AVR-libc defines the I/O registers is roughly equivalent to
#define PORTB (* (volatile uint8_t *) 0x25)

Thank you so much ! I was a bit confused with the address of the register. But once I used a main function and the proper register address it all started working without library variables like PORTB ! :) And also thank you for the volatile and constant suggestions.

Port definitions in AVR-Libc are done via black magic. Don't attempt to replicate them as a beginner. That being said...
"How do I pass an IO port as a parameter to a function?"
volatile uint8_t *data = &PORTB;
volatile uint8_t *dir = &DDRB;

Thank you so much ! After I checked your 'black magic' link it was a bit clear. I implemented what you had suggested and used a main function. There on it worked fine.


text:
Onboard led HIGH and LOW seems reversed
On an ESP32 board I am trying this simple code to control the onboard led.
But if I set it to HIGH, led is OFF, if I set it to LOW, led is ON (fully bright).
What could cause this ?
The board has one red and one blue leds, the blue one is the one that can be controlled.
#define onboard_led 2

void setup() {
  pinMode(onboard_led, OUTPUT);
}

void loop() {
    digitalWrite(onboard_led, HIGH);
    // digitalWrite(onboard_led, LOW);
}

Edit: it was a board like this ("Geekcreit" I think):

To know for sure, you'd need to show the design of the board.  But it's not uncommon for leds to be arranged in circuit such that to turn them on you sink current through the chip.  As in, LED is wired something like  3.3V --- RESISTOR --- LED --- GPIO_PIN.  When GPIO goes LOW (toward ground), your current flows and the LED turns on.   It's also possible that the MCU's pin is connected to a transistor that inverts the logic in addition to offloading the current handling onto the transistor.

There’s nothing wrong with your board. Your confusion is caused by how the onboard LED is wired as explained by @timemage. Many ESP boards have this arrangement for the onboard LED and you might also find other (external) hardware that has active-low controls. If you measure the I/O pin that is connected to the internal LED you will see that when it’s “HIGH” it’s at 3.3V (or close to it) just like it’s supposed to be.

I know it sound weird as a beginner, but it's not that unusual. Certain chips are better at sinking current (connecting to ground), than sourcing current (connecting to Vcc). A similar inverted logic is often used with buttons, where the input pin has a pull-up resistor. Resulting in reading a LOW when the button is pressed, and HIGH when not pressed. If this messes with your head a bit you could invert the value in code, which might make it more intuitive to read. Like digitalWrite(onboard_led, !HIGH);, where the HIGH indicates you want it to turn on, and the ! inverts it automagically.

OK, so I understand this is common. I don't have detailed schematics of the board, but I added a photo and name of board.

@adrianTNT, unfortunately there are a lot of boards /like/ that.  To the extent that a picture would be helpful, it would need to be either a picture of your board or one that you are certain is identical.  Otherwise it's just another variable.

@timemage I found that it is not uncommon for leds to be lit both ways (HIGH/LOW) so that is good enough of an answer for me :)

As this image from Okdo Page on LED Driving shows, there are two ways to drive an LED from a GPIO output pin:

In the Active HIGH case, a HIGH output on the GPIO will turn the LED on since that will source current out of the pin and through the LED into ground.
In the Active LOW case, a LOW output on the GPIO will sink current from the +V supply into the pin.
In your case the LED is hooked up in the Active LOW configuration and so to turn it ON you must set the pin to LOW.
I'll add that these ESP32 boards are made by many different manufacturers and they are not all identical.

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


text:
Dimming this ~30V led with PWM, what do I need?
I have a street lamp with a led and simple driver in it, I don't know the exact led voltage but the driver (image attached) says 27-36V DC output, MODEL: 50W.
Is there a part I could place between this driver and the led, so I can control dimming by Arduino via PWM ?
The led driver specs (large image below) says: INPUT; AC 85-285V and OUTPUT: DC 27-36V 1500mA, MODEL: 50W
I thought it would work to put this "PWM power module" between the driver output and the led, but (I tested months ago) I remember it started to blink, I think only when decreasing power but not on full power (controlled by PWM with arduino).

Should it work with this module or I am trying something very wrong ?
Are there any other parts that should work for sure in this situation ?

The specs on the PWM module are these:
Voltage: 5 V - 36 V DC;
Power: 400 W;
Current: 30 A;
PWM Voltage: 3.3-20V;
PWM frequency: 0-20kHz ;

your question is unrelated to the arduino ... why are you asking here?

because I need it to work with Arduino, otherwise I can find parts that control dimming with a rotating knob, but this is an Arduino project.

your question is about the LED power supply, not anything that controls it ...  you would have the same question if you used a 555 timer for dimming ... technically, you are actually asking if you can use a rotating knob to dim the LEDs ... and it has been answered that no, you cannot

No, that is not what I asked, it is an Arduino project, I used arduino board, software and modules to connect to this driver. I needed to know where the problem is.

it makes no difference how you generate a PWM control signal, software or hardware, the result is the same ... that makes arduino irrelevant to the question ... if you cannot control the power supply with a 555 timer, then you cannot control it with an arduino either

It will not be possible for you to PWM dim your LED with that LED driver (power supply).
That is a constant current driver with under/over-voltage protection. It delivers a specific amount of current (1.5A) and varies the voltage to allow that to happen.
If the voltage rises too high or falls too low then there must be a fault, so it shuts the power off. This is usually because there is either a short (LEDs tend to "fail short") or an open circuit. The former causes the voltage to drop too low and the latter for it to be too high.
When you insert PWM control you alternate between driving the LEDs and an open circuit. If that open circuit persists too long (low duty cycles) the driver will shut off.
You will need to replace the LED driver (the power supply) with one which includes PWM control internally to it.

Can you give me more info on what kind of power supply I should look for ? I tried looking for pwm led driver 220v module but closest I could find was controllers with knob for PWM control.

No, I can't. I don't know what is available. All I know is that you can't PWM the output of that power supply and you need to find one that you can.

If you buy a 30V current-limiting power supply set to limit the current to 1.5A, you should be able to use it to power your LED light through a high power logic level MOSFET. You could control the MOSFET with a PWM signal from an Arduino and use that to vary the brightness of your light. With a little googling I found an adjustable power supply with an output ranging from 0-30V and a power rating of 0 - 1.5A https://www.canakit.com/r182-0-30v-0-1.5a-adjustable-regulated-power-supply.html
It does not look to be weather-proofed like the one you show however, and you'd need to make sure the heat-sink was able to dump enough heat to prevent it from overheating.


text:
TCP client readStringUntil only when data exists
I have the attached script that reads data from a socket server (it is PHP at the server end).
My problem (I think) is that the readStringUntil() needs a test above it, so that it "reads up to \r" only if there is any data being received, otherwise it seems to keep trying to read forever, because when I DO send data, it is received with 1-2 seconds delay.
If I constantly send (properly \r delimited) data without any pause, then it seems to be received instantly (10-20ms or so).
I tried: if (client.available()) { String received_message = client.readStringUntil('\r'); } but it doesn't seem to be the right function, doesn't do anything.
This is ESP32 board, compiler mentioned it found two wifi libraries, one in arduino folder and one in ESP32, it used the second one. This might be relevant to what functions are available.
#include <WiFi.h>

const char* ssid = "MyWiFi";
const char* password =  "1234";

const uint16_t port = 8080;
const char * host = "myserver.example.com";

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

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("...");
  }

  Serial.print("wifi connected with IP: ");
  Serial.println(WiFi.localIP());
}

void loop() {

  WiFiClient client;

  if (!client.connect(host, port)) {
    Serial.println("connection to host failed");
    delay(500);
    return;
  }

  Serial.println("connected to server");

  // I assume this is where I need a test like "if any received data exists" >>>

  String received_message = client.readStringUntil('\r');
  Serial.println(received_message);

  // intentional delay doesn't seem to do much
  // when it constantly tries to read for data that is not always there
  delay(100);

  // do I need to disconnect here ?!
  // client.stop();
}

EDIT: my PHP loop looks like this:
do{
    $accept = socket_accept($socket) or die("Could not accept incomming connection");

    // $message_to_send = 'hi there '.microtime(true)."\r";
    // OR
    // get message from memcached variables

    if($message_to_send!=''){

        echo "\nsending: ".$message_to_send;

        socket_send($accept, $message_to_send, strlen($message_to_send), MSG_OOB);
    }

} while (true);

esp WiFi libraries close the connection when the last WiFiClient object which referenced it is destroyed. so here at the end of the loop().

does the server send data immediately after you connect to it? you send no request

You mean that is when it closes it automatically or when I need to call the close ? Thanks.

Server sends data immediately if I tell it to, it is inside an infinite loop where I make it check for new data and send it if found. The delay appears when it looped with no data to send and then it started sending something.

If the loop constantly sends properly delimited data on each cycle (e.g 'hi there '.microtime(true)."\r"), then there is no delay.

your client connects and disconnects in every loop(). make WiFiClient global, connect it back only when it disconnects. and then will if (client.available()) work

You mean the client.connect in top of the loop causes the delay ? I don't think is that because if I comment-out the client.readStringUntil() then it loops much faster.

Do I move WiFiClient right above the loop(){} to make it global ? And I don't know how to connect it back when it disconnects :/

client.readStringUntil() waits a second for the data. if the server sends the data immediately after the connection from client is established, then the  readStringUntil would catch it. if it sends the data later, the connection is already closed. if (!connected) connect

I don't know how to use the connected code you mentioned.

then you need project guidance and not an answer on a Q&A site. https://forum.arduino.cc/

I posted a topic exactly there under project guidance yesterday, nobody replied :/

I don't see it there.


text:
Arduino PRO Mini - The pads [was "jumpers"] on the back and Low Power Consumption
I've noticed that on the back of an Arduino PRO mini are two Jumpers next to the A4 and A5 pins, marked with red in the following :

Looking at the leads one seems to be a bypass for the POWER Led and the other a bypass for the regulator, but not sure.
Further, the schematic reveals just one Jumper SJ1 :

https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf
So, my questions are :

Why are there two physical Jumpers on the board ?
Are these two jumpers actually just one : SJ1 ?
And if so how to connect them in order to enable Power isolation ?

Both responses are correct but be mindful that this is a SparkFun feature.  An Arduino Pro Mini from China won't necessarily have the SJ1 pad.
1) Like Gerben said, the pads on the underside of the board are for I2C pull-up resistors.
2) Like David said, SJ1 is on the top of the board next to the GND and RST pins.  (It looks like a small solder blob.)
3) To isolate the regulator from VCC, remove the solder blob on the top of the board with a sucker or solder wick.
The Sparkfun schematic shows all of these elements:
https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf

You can look up the location of SJ1 in the Eagle project files that are provided by Sparkfun). For example, you can import them into KiCad (Free and Open Source), which opens a PCB and a Schematic editor.
To locate SJ1 you can simply click on it in the Schematic editor such that it's highlighted in the PBC editor, as well. For better overview, you may want to hide all the layers besides the foreground one (e.g. 'F.Cu') and click View/Zoom-to-Fit:

-> That means SJ1 is located on the front of the board, right of pin 9 (ground), i.e. it's highlighted in a lighter red. For comparison, I included an image (Sparkfun, CC BY 2.0) of the front, where you can see that SJ1 is marked by a white rectangle (painted on the board) and that it's closed, by default by a solder blob, which can be de-soldered (e.g. using solder wick and a bit of flux).

NB: To enable power isolation (i.e. such that the MCU can be directly powered without also powering the power-on LED and one side of the on-board LDO, e.g. in order to save power), you have to open SJ1.

Thus, the pads on the back of the board, you marked in an image you included in the question, are something different. In KiCad you can look them up as well: that means switch to the back layer (e.g. 'B.Cu') and click on the pads such that the related parts are highlighted in the schematic editor:

These pads are not jumper SJ1. On the front of the board just beneath the GND pad there is a blob of solder. This is SJ1 (I believe - I am writing from memory, I do not have a Pro Mini sitting on my desk at the minute) and removing the solder blob will disconnect the LED and output of the regulator from Vcc.

I think those aren't jumpers, but pads to place two pull-up resistors for I2C.
It seems the eagle files Sparkfun shares aren't the same as the board in the picture.
But you don't need to worry about this. If the RAW pin is not connected the MIC5205 regulator uses only 0.01μA according to the datasheet.

I would add that original post is not necessarily about Arduino from China, but old model
https://www.sparkfun.com/products/retired/11112 which I have since 2016.
It does not have this jumper and according to eagle file opened in KiCad, sadly the only way to disconnect the regulator is to desolder it. VCC trace goes directly under the VCC pin. On my copy (which might be a clone), the power regulator has the label the S20G or S2OG and an unidentified logo resembling a wave (EDIT: identified as MicrOne ME6211 made in China)
Power consumption with all pins output/low, ADC disabled and BOD disabled is roughly 80uA. Culprit might be either fake ATmega chip or voltage regulator.


text:
Multi-threaded Robot
I am working on a small robot project, the code which i made for this has a sequential execution in a single thread. There are a lot of Delay() function needed. Due to which the accuracy is extremely bad.
i want to to implement the movements in one thread and the sensor detection in another thread.
#define M1 3
#define M2 5
#define M3 6
#define M4 9
#define L_trig 2
#define L_echo 4
#define R_trig 7
#define R_echo 8
#define servo 10
#define solenoid_pin 11
#define LDR_pin1 12
#define LDR_pin2 13
void setup()
{
// Motors Initilization
pinMode(M1,OUTPUT);
pinMode(M2,OUTPUT);
pinMode(M3,OUTPUT);
pinMode(M4,OUTPUT);
// Ultrasonic  Initilization
pinMode(L_trig, OUTPUT);
pinMode(L_echo, INPUT);
pinMode(R_trig, OUTPUT);
pinMode(R_echo, INPUT);
S.attach(servo);
}

void loop()
{

 Runmotor(M1);
 Runmotor(M2);
 Runmotor(M3);
 Runmotor(M4);
 servo_rotation();
 Ultrasonic_value(L_trig,L_echo);
 Ultrasonic_value(R_trig,R_echo);

 if(Ultrasonic_value(L_trig,L_echo)<5 || Ultrasonic_value(R_trig,R_echo)<5)

   {
     turnLeft();
     //Serial.println("Working");
   }

}

// Run Motor
void Runmotor(int which)
{
  for(int i=0;i<1023;i++)
  {
 analogWrite(which, i);
  }
}
// Stop Motor
void stopmotor(int which)
{
  digitalWrite(which,LOW);
}
// To turn the robot left side
void turnLeft()
{
  stopmotor(M2);
  stopmotor(M3);
  delay(5000);
  Runmotor(M2);
  Runmotor(M3);
}
// To turn the robot Rightside
void turnRight()
{
  stopmotor(M1);
  stopmotor(M4);
  delay(5000);
  Runmotor(M1);
  Runmotor(M4);
}
// Servo Rotation
void servo_rotation()
{
 for(angle=0;angle<=180;angle++)
{
 S.write(angle);
 if(angle==90)
 {
   delay(2000);
 }
}
delay(2000);
for(angle=180;angle>=0;angle--)
{
  S.write(angle);
  Serial.println(angle);
  if(angle==90)
 {
   delay(2000);
 }
}
 delay(2000);
}

// Calculation of distance
long Ultrasonic_value(int which_trig,int which_echo)
{
  long duration, distance;
  digitalWrite(which_trig, LOW);
  delayMicroseconds(2);
  digitalWrite(which_trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(which_trig, LOW);
  duration = pulseIn(which_echo, HIGH);
  // distance = duration*343*100/2;
  distance = (duration/2) / 29.1;
  delay(100);
  return distance;
}

void Solenoid_Fire()
{
  digitalWrite(solenoid_pin,LOW);
}

void Solenoid_Reload()
{
  digitalWrite(solenoid_pin,HIGH);
}
/*
bool LDR_reading(int LDR_pin1 , int LDR_pin2)
{

}
*/

Please help me. I want to implement this code in a Multi-thread fashion. Thanks in Advance

I don't think threads are going to help. That's like driving a car by having one person look out the window and another person operating the steering wheel, accelerator and brakes. You have to coordinate your inputs with your outputs. Hiving off the two things (observing and doing) into different threads is just going to create other problems.

Like many things in life, it's also a matter of personal preference. However threads have the advantage of showing clearly what will preempt what. And they avoid busylooping. Of course there is a price to pay, namely reduced ease of debug and risk of deadlocks. Any choice is good, as long as it is informed.

Make a function startTurning and stopTurning, rather than blocking your complete execution with a delay.
You might than use a hardware timer (or software timer) to call these functions, so that in the meantime you can perform other calculations/logic/code/interaction.

You could also give my ThreadHandler library a try
https://bitbucket.org/adamb3_14/threadhandler/src/master/
It uses an interrupting scheduler to allow context switching without relaying on yield() or delay().
I created the library because I needed three threads and I needed two of them to run at a precise time no matter what the others were doing. The first thread handled serial communication. The second was running a Kalman filter using float matrix multiplication with the Eigen library. And the third was a fast current control loop thread which had to be able to interrupt the matrix calculations.
How it works
Each cyclic thread has a priority and a period. If a thread, with higher priority than the current executing thread, reaches its next execution time the scheduler will pause the current thread and switch to the higher priority one. Once the high priority thread completes its execution the scheduler switches back to the previous thread.
Scheduling rules
The scheduling scheme of the ThreadHandler library is as follows:

Highest priority first.
If the priority is the same then the thread with the earliest deadline is executed first.
If two threads have the same deadline then the first created thread will execute first.
A thread can only be interrupted by threads with higher priority.
Once a thread is executing it will block execution for all threads with lower priority until the run function returns.
The loop function has priority -128 compared to ThreadHandler threads.

How to use
Threads can be created via c++ inheritance
class MyThread : public Thread
{
public:
    MyThread() : Thread(priority, period, offset){}

    virtual ~MyThread(){}

    virtual void run()
    {
        //code to run
    }
};

MyThread* threadObj = new MyThread();

Or via createThread and a lambda function
Thread* myThread = createThread(priority, period, offset,
    []()
    {
        //code to run
    });

Thread objects automatically connect to the ThreadHandler when they are created.
To start execution of created thread objects call:
ThreadHandler::getInstance()->enableThreadExecution();

You could use a scheduler and simply start tasks with:
#include <Scheduler.h>
...
void setup()
{
  ...
  Scheduler.start(servoSetup, servoLoop);
  Scheduler.start(sensorSetup, sensorLoop);
  ...
}

void servoSetup()
{
  S.attach(servo);
}

void servoLoop()
{
  int angle;
  for(angle = 0;angle <= 180; angle++) {
    S.write(angle);
    if (angle == 90) {
      delay(2000);
    }
  }
  delay(2000);
  ...
}
...

The tasks must call yield() or delay() to context switch. The taskSetup function is called first and once by the task. The taskLoop function is repeatedly called by the task. This can be viewed as running an additional sketch.
For more details see the example sketches.

I think this needs a major rework. First here:
  for(int i=0;i<1023;i++)
  {
  analogWrite(which, i);
  }

The maximum you can analogWrite is 255, so change 1023 to 255.
Next, get rid of the delay() calls.

Let's look at turnLeft :
// To turn the robot left side
void turnLeft()
{
  stopmotor(M2);
  stopmotor(M3);
  delay(5000);
  Runmotor(M2);
  Runmotor(M3);
}

Why stop the motor and then start it again? Do you mean:
// To turn the robot left side
void turnLeft()
{
  stopmotor(M1);
  stopmotor(M4);
  delay(5000);
  Runmotor(M2);
  Runmotor(M3);
}

I don't see what the delay achieves anyway. Get rid of it:
// To turn the robot left side
void turnLeft()
{
  stopmotor(M1);
  stopmotor(M4);
  Runmotor(M2);
  Runmotor(M3);
}

In fact, I don't see what any of the delay() calls achieve. Try removing them.

See my post How to do multiple things at once ... like cook bacon and eggs for tips on doing multiple things without using delay().

Also consider using arrays. Instead of M1, M2, M3, M4, make an array:
const int NUMBER_OF_MOTORS = 4;
const int motorPins [NUMBER_OF_MOTORS] = { 3, 4, 6, 9 };

Now it is easier to set them all to output:
// Motors Initilization

for (int i = 0; i < NUMBER_OF_MOTORS; i++)
  pinMode (motorPins [i], OUTPUT);

It is also easier to start or stop all of them:
for (int i = 0; i < NUMBER_OF_MOTORS; i++)
  stopmotor (i);

Where stopmotor is now:
// Stop Motor
void stopmotor(int which)
{
  digitalWrite(motorPins [which],LOW);
}

(Edited to add)
I also don't see what this achieves:
void Runmotor(int which)
{
  for(int i=0;i<1023;i++)
  {
 analogWrite(which, i);
  }
}

Apart from the fact that you can't go up to 1023, if you stop at 255, the time taken to do all those analogWrite is just over 2 ms. Why bother? Why not just do this:
void Runmotor(int which)
{
  digitalWrite (which, HIGH);
}

M1   M2                                                                                M3   M4                                                                                When i want to turn left i should Stop the motors lies on 2nd diagional, For turn Right in vice versa

Which motor is which? Are M1 and M2 on the left, and M3 and M4 on the right? Better names would make this obvious, like frontLeftMotor, and frontRightMotor, etc.

You may want to take a look at LMX by David Anderson A Light-Weight Multi-Tasking Executive.
He has a very good set of videos on the code that he did for Dallas Personal Robotics Group (DPRG).
The specific videos for LMX are:

David Anderson on Robotics Software - part 1
David Anderson on Robotics Software - part 2

I am looking at this, for a similar project.
It seems light and simple enough that you could have a quick trial.
Converting those functions to threads shouldn't be too time consuming.
Once every activity is implemented as thread, you could use semaphores to hold them blocked and then create a state machine which controls them through the semaphores.


text:
Arduino capacitive touch sensor help
So I have been messing around with the Arduino Capsense library with the immensely helpful guide; http://www.instructables.com/id/How-To-Use-Touch-Sensors-With-Arduino/  (many thanks to DangerousTim!)   using the code provided, i managed to get a relay to operate with a sensor.  It worked great and I was able to adjust the distance and sensitivity.  But when i tried adding another sensor and relay, it stopped working.  I've been trying to isolate the problem for a while now and have gotten nowhere.  I'm hoping someone can help me, here's the original code for the single sensor and relay;
#include <CapacitiveSensor.h>
#include <CapacitiveSensor.h> //change '42' to any desired pin...

long time = 0;
int state = HIGH;
boolean yes;
boolean previous = false;
int debounce = 200;
CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
// To add more sensors...
//CapacitiveSensor   cs_4_6 = CapacitiveSensor(4,6);        // 10M resistor       between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
//CapacitiveSensor   cs_4_8 = CapacitiveSensor(4,8);        // 10M resistor  between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil

void setup()
{
    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
    pinMode(13, OUTPUT);
}

void loop()
{
    long total1 =  cs_4_2.capacitiveSensor(30);

    if (total1 > 60){yes = true;}
    else {yes = false;}

    // to toggle the state of state
    if(yes == true && previous  == false && millis() - time>debounce){
        if(state == LOW){
            state = HIGH; }
        else state = LOW;
        time = millis();
    }

    digitalWrite(13, state);
    previous = yes;
    delay(10);
}

and here's the code for the two sensors and relays
#include <CapacitiveSensor.h>

int led = 13;
int led2 = 12;
long time = 0;
int state = HIGH;
long time2 = 0;
int state2 = HIGH;
boolean yes;
boolean previous = false;
boolean yes2;
boolean previous2 = false;
int debounce = 200;

CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10M resistor  between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

void setup()
{
    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
    cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...
    pinMode(led, OUTPUT);
    pinMode(led2, OUTPUT);
}

void loop()
{
    int total1 =  cs_4_2.capacitiveSensor(30);
    Serial.println(total1);
    int total2 =  cs_5_7.capacitiveSensor(30);

    if (total1 > 60){yes = true;}
    else {yes = false;}
    if (total2 > 60){yes2 = true;}
    else {yes2 = false;}

    // to toggle the state of state
    if(yes == true && previous  == false && millis() - time>debounce){
        if(state == LOW){
            state = HIGH;
        }
        else
            state = LOW;
        time = millis();
    }

    if(yes2 == true && previous2  == false && millis() - time2>debounce){
        if(state2 == LOW){
            state2 = HIGH;
        }
        else
            state2 = LOW;
        time2 = millis();
    }

    digitalWrite(led, state);
    previous = yes;
    digitalWrite(led2, state2);
    previous2 = yes2;
    delay(10);
}

Maybe you wired sensor cs_5_7 to pins 5 and 7, as it's name misleadingly suggests...

I think you are making a mistake initializing cs_5_7.
CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

You are using same pin 4 for both Capacitive sensors. Try using different pins. I am quite sure that, this would help.

The library documentation says it's OK to share the send pin among several sensors.


text:
reading data from server arduino and gsm900a
I am facing a problem in reading data from thingspeak server
after each AT command, I get the right response from the gsm
However, after
AT+HTTPPARA = "URL","thingspeak.com/channels/channelNumber/fields/1/last.txt"
AT+HTTPACTION=0
AT+HTTPREAD

I always get the response as HTML code so not as content
I really need your help and will appreciate any suggestions.
Thanks in advance.


text:
How do I create a code that lets me use an array of 10 thermistors on one arduino?
I am new to programming and am trying to create an array of 10 thermistors on one arduino. So far I have found a code for Temperature Sensor Using NTC Thermistor that is only for one thermistor. How do I fix this code for 10 thermistors?
Here is the link where I found the code.
https://thecustomizewindows.com/2020/10/temperature-sensor-using-ntc-thermistor-arduino-ntc/
The code below has been changed a little for the thermistor I am using.
Thank you.
#define RT0 10000   // Ω
#define B 3470      // K
#define VCC 5       //Supply voltage
#define R 10000     // R=10kΩ

float RT, VR, ln, TX, T0, VRT;

void setup() {
  Serial.begin(9600);
  T0 = 25 + 273.15;                 //Temperature, Celsius to Kelvin
}

void loop() {
  VRT = analogRead(A0);              //Acquisition analog value of VRT
  VRT = (5.00 / 1023.00) * VRT;      //Conversion to voltage
  VR = VCC - VRT;
  RT = VRT / (VR / R);               //Resistance of RT

  ln = log(RT / RT0);
  TX = (1 / ((ln / B) + (1 / T0))); //Temperature from NTC thermistor

  TX = TX - 273.15;                 //Conversion to Celsius

  Serial.print("Temperature:");
  Serial.print("\t");
  Serial.print(TX);
  Serial.print("C\t\t");
  Serial.print((TX * 1.8) + 32);    //Conversion to Fahrenheit
  Serial.println("F");
  delay(500);
}

the answer depends on how you intend to connect 10 thermistors to an arduino

You haven't said which (of the many kinds) of "Arduino" you plan to use, but Uno being the most common, I'll assume that. You also haven't said why/whether you must use a particular temperature sensor, but if you can be flexible about that, there will more choices of solution.
First, thermistors: You read a thermistors with an an A/D converter. Uno has an A/D converter but it has only 6 channels available - not enough for your spec of 10 sensors.

You could add an external A/D multiplexer with 5 channels fed into one of your on-board channels plus the remaining 5 on-board channels.
Or add a 10-channel multiplexer for all 10 sensors and feed it to one of the on-board A/D channels. This is better because it's simpler - all of the sensor signals will be processed identically, and all accessed the same way in the code.
Add an external 10-channel A/D. It will cost a little more but will be even easier to work with.

If you don't require thermistors, I'd suggest the Dallas/Maxim DS18b20 "1-wire" sensors. The "1-Wire" bus is a proprietary protocol developed by Dallas Semiconductor on which these sensors depend. You use one, simple, twisted-pair bus to access all of them, needing only 1 Arduino pin (and ground) to provide both power and communication to/from the sensors. Libraries are available to manage the bus and the communication. The 1-wire bus can be in a linear or a branched configuration, to suit your installation. You can use 2 wires (ground and power+data) or 3 wires (ground, power, data). Here's a link to the DS18b20 data sheet for the details.
Update:
I didn't really answer your question about coding for 10 thermistors (since you can't directly connect 10 thermistors to an Uno), I'll try to address that now without getting into any more detail about what kind of sensors you use or how you connect them.
You'll need to read 10 sensors, compute the sensor data to temperature and store it, and do whatever you plan to do with the temperature value. Your present code prints it (as both degC and degF, but let's just describe that part as printing the value).
You'll need a for( ) loop that executes 10 times, once for each sensor, where the loop index tells which sensor (0-9) you'll be processing. In time the loop executes, read a sensor, compute the temperature from what the sensor gives you, if it isn't already in the units you need, and print the value. So structuring that as if it were code (but I won't be writing it out in full C++) it would look like:
tell all 10 sensors to take a measurement; // if necessary
for( i = 0; i < 10; ++i ){
   read data from sensor[i];
   convert it to temperature;      // depends on the sensor
   print the temperature value;
}

If that is all you want to do, code this loop in your setup() function. Each time you reset the Arduino, it will measure and print all 10 temperatures and stop (actually, loop forever, doing nothing, until you power it down). If you want it to do this periodically, code this loop in your loop() function, with a delay(5000); statement after it. Now it will print the 10 temperatures every 5 seconds. You can change the 5000 (it's in milliseconds) to whatever period you want.
But it's the details that get you. You've got code to read and convert thermistors but your Arduino can't directly connect to 10 thermistors. If you use an external multiplexer, then you'll have to include code for that. If you use DS18b20 1-Wire sensors, you'll need to download and use the code library for those, as well as converting their 1/16-degC units to the units of your choice.
I'd recommend you start with 2 or 3 thermistors since you have the code for them, and write the loop for those. Once that's working, you'll have the answer to your title question. Then you'll have to decide how to connect 10 sensors of some kind, as I wrote about earlier. That will involve some additional coding, for an analog multiplexer, or for 1-Wire sensors, or whatever solution you choose. Just expand your experiment by small steps at a time and get each step working before you move on.

https://arduino.stackexchange.com/questions/14702/issue-with-cd74hc4067-mux-on-high-values has code for a 16-channel multiplexer attached to A0


text:
Problem with IR remote and Pushbutton for digispark
As digispark is more compact and suitable for my electrical application. Following the same procedure in brtiberio answer. I tried to convert the script from Arduino UNO to digispark, but not succeed
#define irPin 2
const int buttonPin1 = 0;
const int buttonPin2 = 4;
const int relay1 = 1;
const int relay2 = 3;
int Relay1State = 0;
int Relay2State = 0;
int master1State = 0;
int master2State = 0;
int button1State;
int button2State;
int lastButton1State;
long lastDebounceTime1 = 0;
int lastButton2State;
long lastDebounceTime2 = 0;
long debounceDelay = 50;
void setup() {
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  digitalWrite(relay1, Relay1State);
  digitalWrite(relay2, Relay2State);
}

void loop() {

  int key = getIrKey();

  if(key == 7388){
    Relay1State = !Relay1State;
    if(Relay1State == true)
      digitalWrite(relay1, HIGH);
    else
      digitalWrite(relay1, LOW);
  }

  if(key == 1778){
    Relay2State = !Relay2State;
    if(Relay2State == true)
     digitalWrite(relay2, HIGH);
   else
     digitalWrite(relay2, LOW);
  }
}

int getIrKey(){
  int len = pulseIn(irPin,LOW);
  int key, temp;
  key = 0;
  //Serial.print("len=");
  //Serial.println(len);
  if(len > 6000) {
    for(int i=1;i<=32;i++){
      temp = pulseIn(irPin,HIGH);
      if(temp > 1000)
        key = key + (1<<(i-17));
    }
  }
  if(key < 0 )
    key = -key;

  //if(key)
    //Serial.println(key);

    delay(250);
  return key;
  //**********************//
  int reading = digitalRead(buttonPin1);
  if (reading != lastButton1State) {
    lastDebounceTime1 = millis();
  }
  if ((millis() - lastDebounceTime1) > debounceDelay) {

    if (reading != button1State) {
      button1State = reading;

      if (button1State == HIGH) {
        master1State = !master1State;
        Relay1State = master1State;
      }
    }
  }

  digitalWrite(relay1, Relay1State);
  lastButton1State = reading;

  //*******************************//
  int reading2 = digitalRead(buttonPin2);
  if (reading2 != lastButton2State) {
    lastDebounceTime2 = millis();
  }
  if ((millis() - lastDebounceTime2) > debounceDelay) {

    if (reading2 != button2State) {
      button2State = reading2;

      if (button2State == HIGH) {
        master2State = !master2State;
        Relay2State = master2State;
      }
    }
  }

  digitalWrite(relay2, Relay2State);
  lastButton2State = reading2;
}

Any advise, please?

not succeed is not a description of a problem

Not sure why you means of "to convert the script from Arduino UNO to digispark"? IRremote library does support DigiSpark (and ATtiny85) without the need of any conversion.

Which Arduino Core are you using? If you are running ATTinyCore, you can use the IRremote library without any problem.

The remote part is working well. the problem is with the push button function only. it dosen't works.

@Mah would you please share your final codes? I am in badly need of that

Your button code is in the function int getIrKey(). But it never gets executed, because before it you execute return key;. With that you leave the function and returning the value of key. Everthing that comes after the return statement will not be executed.
Putting the button code in that function doesn't make sense in the first place (since the buttons are not used to "get the pressed IR key"). Instead try to put it in the loop() function, after the other relay code.

Thanks to chrisl. It is working fine now.

If you think my answer was correct, you can mark it as correct, so that others can see and learn from that.

Sorry, I forget that.


text:
Arduino classes, can't get property value
I have tried hard to make a stepper motor work with a class, but I can't get a property returning its value in a method. I get 0 (zero) instead of 26 (expected) from _stepPin.
I have tried this->_stepPin with no success.
Here is the code. See the comments inside.

 class MKSStepperMotors {

   public:
    int _dirPin;
    int _stepPin;
    int _enablePin;

    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;

      //Habilitamos el motor
      pinMode(_enablePin, OUTPUT);
      digitalWrite(_enablePin, LOW);

      //Cambiamos la direccion y aumentamos la velocidad
      pinMode(_dirPin, OUTPUT);
      digitalWrite(_dirPin, LOW);

      // Le indicamos el pin de señal
      pinMode(_stepPin, OUTPUT);

    }

    void move(int steps, int stepDelay)
    {

      for (int x = 0; x < steps; x++) {
        Serial.println(_stepPin); //  <-- _stepPin is zero and not 26 as it should
        digitalWrite(_stepPin, HIGH); <-- _stepPin is zero and not 26 as it should
        delayMicroseconds(stepDelay);
        digitalWrite(_stepPin, LOW);  <-- _stepPin is zero and not 26 as it should
        delayMicroseconds(stepDelay);
      }
    }
};

 MKSStepperMotors pedo(28, 26, 24);

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

 void loop() {

      pedo.move(3200,100);

}

When you put the type there, you are creating new variables.  SO in your constructor:
 MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;

You start by creating three new variables with the same names as the member variables defined in the class.  Throughout the rest of the constructor those get used instead of the ones that are member variables.
You gotta lose the "int" there.
You also have another bug in there.  The constructor may run before the init function if one of these objects gets declared at global scope.  Things like digitalWite and pinMode aren't going to work yet in that case.  A constructor should just have code to initialize variables, it should never touch hardware.  The stuff that uses hardware should be in another member function (usually called begin or init) that you can call from setup.

Did Work !!!!! And I accepted the "init' method suggestion. THANKS

You have redeclared the class member fields in your constructor:
class MKSStepperMotors {

   public:
    int _dirPin;
    int _stepPin;
    int _enablePin;

    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;
      ...
    }

The int _dirPin = dirPin; declares a local variable with the same name as your class member _dirPin and shadows it, hence your 3 class members never get initialized!
You should change your constructor as follows:
    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      _dirPin = dirPin;
      _stepPin = stepPin;
      _enablePin = enablePin;
      ...
    }

Or better, use standard C++ constructor initialization:
    MKSStepperMotors(int dirPin, int stepPin, int enablePin)
    :_dirPin(dirPin),_stepPin(stepPin),_enablePin(enablePin) {
      ...
    }

In this latter example, you don't need to initialize your class members in the constructor body as they are already initialized before the body gets executed (this is idiomatic C++ usage).


text:
Series of µsec pulse generation using Arduino Due
I'm working on a project in which I need a series of very accurate pulses containing 2 shots in every pulse. The pulse should have 100µsec on time followed by 300ms off time. But when I'm programming the Arduino Due I'm getting random pulses of non-uniform width. But when I'm trying the same code in microsecond range I'm getting perfect wave.
Here is the code that I'm using

#define LED 8 // Pin designated to give out the pulse
int cycles = 2;  // No. of times you want it to give pulse
int high = 100; // High time in microseconds
int low = 300;  // Low time in milliseconds
int i = 0;
int univ_cycle = 10;

void setup() {
  // put your setup code here, to run once:
 pinMode(LED, OUTPUT);
 Serial.begin(9600);

}
void loop(){
  for (i ; i < univ_cycle; i ++){
  pulse();
  delay(100);
  }
}
void pulse() {

  // put your main code here, to run repeatedly:
  for(int counter = 0;counter < cycles;counter++){
  digitalWrite(LED, HIGH);
  delayMicroseconds(high);
  Serial.println("ontime");
  digitalWrite(13, LOW);
  Serial.println("offtime");
  delay(low);
  Serial.println(counter);
  }

}

Here is the image of the waveform in microsecond setting

Here is the wavefrom that we got in millisecond setting

I would like to know how can I get the similar wave in microsecond also.

I would suggest as a start removing those Serial.println calls. They will make complete nonsense of any timing you attempt to do.

Look into using one of the 16bit timers. What do you mean with “two shots in every pulse”?

@Gerben I assume he means ___-__-______-__-______-__-_____

@Majenko silly me. I should have looked at the scope output.

@Gerben Can you please suggest me how to use 16-bit register?

Setup the timer to call an interrupt service routine every 100us. In this routine increment a counter. Set the output high when the counter is 0, and low otherwise. Reset the counter when you reach 3000 (i.e. 300ms). This is for a single pulse. For the double pulse you’d have to add some extra code. I’d suggest checking the timer1  library for setting up the timer interrupt.


text:
arduino suddenly shows “avrdude: ser_open(): can't open device ”\\.\COM3" after last upload
I am using arduino uno to make a sound detector. I uploaded a program, found error in the code that it returns unintended numbers unreasonably big. I also think I used wrong code for the module, but it was connected in the way that can work properly with the proper code.
The code I uploaded was:
const int ledPin =13;
const int middleValue = 512;
const int numberOfSamples =128;

int sample;
long signal;
long averageReading;

long runningAverage = 0;
const int averagedOver = 16;

const int threshold=400;

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

void loop(){
    long sumOfSquares = 0;
    for (int i=0; i<numberOfSamples; i++){
        sample = analogRead(0);
        signal = (sample - middleValue);
        signal *= signal;
        sumOfSquares += signal;
    }
    averageReading = sumOfSquares/numberOfSamples;
    runningAverage=(((averagedOver -1 )*runningAverage)+averageReading)/averagedOver;

    if(runningAverage>threshold){
        digitalWrite(ledPin, HIGH);
    }else{
        digitalWrite(ledPin, LOW);
    }
    Serial.println(runningAverage);
}

When the arduino suddenly stopped sending serial numbers, I pressed reset button and uploaded the default code:
void setup() {
}

void loop() {
}

but now it shows that it cannot connect to COM3 (arduino) and cant find the device, When I can see arduino uno successfully connected to PC using device manager (windows 8.1). The led light of arduino also turns on when I connect it to power source or usb.
it shows "port not found" when I click to see the serial output
Did I just fry Arduino? How should I fix this?
Also, i checked the led pin 13 blinking three times when i plug in the usb. I just cant upload anything

I ran into such a problem when I was accessing my Arduino board from two different windows applications like Arduino IDE and eclipse. or Eclipse and some serial monitor windows application. Make sure you close any application that programs or communicates with the Arduino board, and make sure you configure the COM you are using in Arduino IDE and try again.
Also try disconnecting any wire that is connected to RX and TX pins when you are programming the Arduino.

You might have your serial monitor open at COM3 somewhere which is why AVRdude is failing to open the port again. Make sure the serial monitor is closed.
if you are opening serial ports on Python or your own developed applications, you have to explicitly close the port on exiting the program, otherwise, the port remains open and you come across such errors.

my arduino revived the next day.... don't know why but it works!


text:
How do I connect multiple pinhole cameras and take photos and video at the press of a button?
I am trying to set up a 4 cameras which can take videos/photos at the press of a button.
Things which I will need:

4 micro cameras(the ones which are very small in size) with good
shutter speed and sensor. The cameras will often travel at 20 to
30mph. So I guess good shutter speed is needed.
2 Push buttons. One will start and stop taking pictures really fast, and the other will do the same for video
Battery which can last atleast taking 5 images/1 min of video recording.
4 Microsd cards and the connectors. Is there anyway I would be able to set up a common adapter to all these cards, so when connected to a computer it will show up as 4 different drives?

So I think I can make the set up using this: http://www.arducam.com/
But can it take images really fast. I couldn't see any information regarding this. It should be able to take like 4 images per second. Also it would be awesome if this set up can somehow support taking videos.
Now another thing I need is a push button which will start taking the photos and stop taking it.
This whole thing should operate from a battery.
Mostly I want to know is the list of products which will work or the specs to look for when choosing the products. Also I would like to know if this is the best way to go for  a project like this. This thing will be more like a toy, so I don't want to use really expensive parts for this. Also I don't want a gopro. I want to make this whole set up myself.
Let me know if you need to know more details about this.

Arduino's are way underpowered for these kinds of applications. Might I suggest something like a Raspberry Pi with Multi Camera Adapter

As it stands, I think this question is too broad to get good answers. At the very least you need to be clear about whether you are planning to use the Arduino as a controller for the cameras or if you're hoping to do the image processing yourself.

I want to connect 4 cameras and control it by using a single button to start and stop image capturing. It needs to take like 4 images per second. I want the arduino board because I would like to enable WiFi functionality and small webserver to access the images. What cameras I should use to capture the images as Arduino board can't process the images. Do you have any suggestions? @Gerben

That will never work on a single arduino uno. Webserver, WiFi, images capture, image storage. Why do you insist on using an arduino?

Now that I think about it, I think I will use Pi instead of arduino. The thing is Pi is bigger and it will need a bigger power source. I thought of using arduino because of these reasons.

Arduinos and Cameras do not mix well at all.  It's all down to the sheer quantity of data involved in pictures.
Take for instance a typical VGA image - 640x480 pixels at 24-bit (3 byte) colour depth.  One single picture requires 640x480x3 = 921600 bytes just to store it.
Add to that the fact that most small cameras include hardware JPEG compression which the Arduino really has no hope of being able to handle, and you just can't do anything with it.
Most camera modules use a system called CSI-3 (Camera Serial Interface version 3) for streaming the raw data from the CCD elements into the target.  That allows for high speed data transfer of the whole frame at a speed that is able to support video.  If you think about video as 25 frames per second, and raw data, that means that the data is being transferred from the CCD elements in total at arouns 22 MiB/s - there is absolutely no way that an Arduino can deal with that kind of data.  So cameras that attach to an Arduino have their own controller chip that compresses the image to JPEG and streams it out through a much slower interface - typically RS232.  All the Arduino can then do is tell the camera "Take a picture for me" at which point an image is captured and compressed, and then the Arduino receives the JPEG data through serial (slowly) and stores it on an SD card (also slowly). It can't do anything else with it.
To crunch those numbers - assume that the compressed VGA image from the camera's processor chip is 100,000 bytes (I took a typical photo, scaled it to 640x480 and saved it with 90% JPEG compression and it was roughly that size).  At 9600 baud you get 960 bytes per second. 100,000 / 960 = 104 seconds.
That is how long it would take to transfer one single image through the Arduino.
If the camera has a higher speed UART, say 115200 baud (11520 Bps), that would then give you 100,000/11,520 = 8.7 seconds.
So no, using an Arduino to control cameras in that way just isn't possible.
Instead you need a system that can talk CSI-3 directly - something with a direct camera connection, such as the Raspberry Pi.  Another alternative is any embedded computer with enough processing power and USB ports to connect cheap USB webcams to.  Again the Raspberry Pi would do - especially the newer version 2 with the quad core processor.

I really thought of doing this with raspebrry pi, but the thing is I need it to run with batteries and the whole set up should be portable. So if we add Raspberry pi it would need heavy(300gms atleast) batteries right? Is there anyway of doing this without using heavy batteries? I don't care if I use raspebrry pi or arduino to be frank!

If you want to work with video you need a higher powered system. If you work with a higher powered system you require more current. If you require more current you need bigger batteries. It's a fact of life. Using the right batteries is important of course - Li-Poly gives better power density (smaller/lighter batteries with higher power) than alkaline, for instance.

So what if I don't want the video. I would need like 4 images captured per second. Can that be done without a system like raspberry pi or arduino?

It sounds to me like you want to get a bunch of cheap digital cameras and interface the trigger buttons to the Arduino so the Arduino just tells them to take photos. The cameras themselves then do all the work.

If that can be done, yes. I wanted arduino board because then I can access these photos via WiFi or can connect a single cable to access the pictures from all the 4 cameras. So is it doable?

With Arduino you can only control, you cannot get at the data. For that you will need a Pi or something else that can directly interface with the camera or its USB interface. There's no getting away from it, you can't do what you want on an Arduino! At the moment you're trying to use a trowel to do open cast mining. It just won't work.

Yeah, I think its better to use Pi. I can't find any other way of doing it!


text:
Why is 1020 steps used for crossfading colors on an RGB LED?
I'm looking into how to smoothly crossfade between colors on an RGB LED with the Arduino and I've found this piece of code for doing it:
https://www.arduino.cc/en/Tutorial/ColorCrossfader
I understand all parts of the code except for one thing.
The values for red, green and blue are changed incrementally through 1020 steps, because 255*4 = 1020.
But WHY 4? There are 3 colors, and 255 * 3 = 765. So why not 765 steps?

@Brian, that would be the number of steps to go through every possible colour combination. That wasn't the program intent. (Paraphrasing:) You define a series of RGB colours - #CC0000, #30DD00, etc. - and get the system to smoothly transition between them. The 1020 steps is intended to give quarter bit resolution on the step interval. Details in my answer.

I'm looking a non=blocking cross fader because while it is cycling through the colours slowly the processor is still able to receive serial communications.
So far the non-blocking ones are not smooth enough.

Extract from code:
int wait = 10;      // 10ms internal crossFade delay; increase for slower fades

for (int i = 0; i <= 1020; i++) {
  redVal = calculateVal(stepR, redVal, i);
  grnVal = calculateVal(stepG, grnVal, i);
  bluVal = calculateVal(stepB, bluVal, i);

  analogWrite(redPin, redVal);   // Write current values to LED pins
  analogWrite(grnPin, grnVal);
  analogWrite(bluPin, bluVal);

  delay(wait); // Pause for 'wait' milliseconds before resuming the loop

  if (DEBUG) { // If we want serial output, print it at the
    if (i == 0 or i % loopCount == 0) { // beginning, and every loopCount times
    }
    DEBUG += 1;
  }
}

The 1020 in the loop determines the time taken to make the crossfade from the current colour to the next - not the total cycle as you seem to think. In the main loop we have
crossFade(red);
crossFade(green);
crossFade(blue);
crossFade(yellow);

And each of these crossfades will take 1024 * wait ms to complete. 'wait' is set to 10 ms so I would expect it to take 10.24 s to complete a fade from one colour to the next.
[Edit]
I think the large number (1020) is just to give a fine resolution in the steps calculation which is all done with integers. (What struck me as odd is that it doesn't use 256 * 4 = 1024.) The larger we make this number the finer the step resolution becomes. With coarse steps the ramp will complete too early.
Let's say we had 255 steps and we wish to go from 134 to 0.
step = 255 / (endValue - prevValue)
step = 255 / (134 - 0 ) = 1.9 which will be rounded down to 1.

This means that the crossfade will be complete in 134 steps instead of 255. i.e., it will finish 47% early.
If we use 1020 steps and we wish to go from 134 to 0.
step = 1020 / (endValue - prevValue)
step = 1020 / (134 - 0 ) = 7.6 which will be rounded down to 7.

This means that the crossfade will be complete in 938 steps instead of 1020. i.e., it will finish 8% early.

See the update.

The 1020 is indeed a granularity mistake. First he/she/they/them/it/x say(s) 0 to 255, to then conclude that's 255 levels. Undermines my trust in the efficiency of the remaining maths to be honest, as the total average effective fade error will be lower with the correct 1024 steps for quarter-bit granularity in integer maths. Though the better way is fixed point or integer-remainder maths of course, but "them" often finds that scary?

I'd say it's fine for the application. I don't know that we'd notice the steps given that they're 1/255 of the full brightness. The Arduino code is intended for a learning audience and in this instance I think simplicity and readability wins over accuracy.

"What struck me as odd is that it doesn't use 256 * 4 = 1024" Hee hee. This is classically known as a fence-post error. When you start at (let's say) a value of 00, it only takes 255 steps to get to the maximum value of 256.

@Asmyldof - It's entirely possible that 0 is not considered a level - it is just "off". Not the clearest of thinking, if so, but not all that unusual.

@WhatRoughBeast For steps, yes 255 to go from 0 to maximum, but if you use oversampling ( *4 ) as an argument for the loop, you're increasing granularity. Making a 64/255th bit granularity in the maths in stead of 1/4th bit increases the statistical chance for glitch errors, as bitlevels don't coincide with round maths more than 4 times per 255 steps. Whether you consider 0, 55, 255, or everything below 128 as off.

For my transition between colors I used arrays during the setup to collect the main transitions (bigger jumps between RGB values) then during the loop I used a series of analogWrite() commands essentially splitting the jumps by a 16th, for example starting at 255, 0, 0 the next array value was 223, 0, 0 in the loop it went from 255, 0, 0 to 253, 0, 0 to 251, 0, 0 finally landing the last loop value of 225, 0, 0 before starting the loop over at the next array value of 223, 0, 0. It's important to realize what colors transition into others and what the corresponding RGB values are of that transition.
Tomorrow I'll post my code, it's a bit messy as it was more proof of concept that starting with a distinct plan.


text:
NodeMCU (ESP8266) Defining static IP, stops Firebase processing
Hello i am new to NodeMCU (ESP8266) i am building a small program to connect with WIFI (with internet) and if internet is not available i want to process request over IP address.
I am using firebase as a database / server to fetch the status. And process command through a URL like http://192.168.1.223/on?pin=04 if internet is connected then no problem i can update firebase entry, but with same network (LAN) connection over wifi i want to process i need to have static IP. But the concern is i am not able to make this IP address static, and if i make it static then my NodeMCU is not able to connect with firebase.
Here is how my code looks like:
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <ESP8266WebServer.h>

#define FIREBASE_HOST "pushst-56f2c.firebaseio.com"
#define FIREBASE_AUTH "mhBpzrNyhhwEGwmFxkVFTIEylwrXMw0gm"
#define PATH "/clients/devicename/watermotor"

IPAddress ip(192, 168, 1, 223);  //Node static IP
IPAddress dns(192, 168, 1, 223);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);

char ssid[] = "MyNetwork";
char password[] = "Qwert98!!";

int wifiStatus = WL_IDLE_STATUS;

ESP8266WebServer server(80);

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

      delay(100);
      Serial.println();
      Serial.println();
      Serial.print("Your are connecting to;");
      Serial.println(ssid);

      WiFi.begin(ssid, password);
      WiFi.config(ip, dns, gateway, subnet);

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

      wifiStatus = WiFi.status();

      if(wifiStatus == WL_CONNECTED){
          digitalWrite(WIFI_CONNECT_LED, LOW);

         Serial.println("Your IP address is: ");
         Serial.println(WiFi.localIP());

         Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
         Firebase.set("/clients/devicename/watermotor/name", "Motor");
         Firebase.set("/clients/devicename/watermotor/relay_status", "off");
         Firebase.set("/clients/devicename/watermotor/device_status", "online");
         Firebase.stream(PATH);

         server.on("/on", handleOnRequest); //Associate the handler function
         server.on("/off", handleOffRequest); //Associate the handler function

         server.begin(); //Start the server
      }
      else{
        Serial.println("");
        Serial.println("WiFi not connected");
      }

}

void loop() {
    server.handleClient();
    if (Firebase.failed()) {
      Serial.println("streaming error");
      Serial.println(Firebase.error());
      delay(1000);
      return;
    }

    if (Firebase.available()) {
        Serial.println();
        Serial.print("Firebase available");
        Serial.println();
        FirebaseObject event = Firebase.readEvent();
    }
}

I am not sure if its there is some problem with FirebaseLibrary or its just the ESP8266!
Any suggestions will be helpful, thanks in advance! :)

why same IP for esp8266 and DNS?

Its just for reference, i can keep any @Juraj

it should be the address of the DNS server which can resolve the name of the firebase host

Not getting you @Juraj any example?

example? just fill in the IP address of the DNS server which is usually the address of the router/gateway IPAddress dns(192,168,1,1); (if this is right)

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

Ok i am trying it @Juraj

Hey buddy its done! It helped! @Juraj

They suggestion you gave has make it work! :) Thank you so much. I think you should post it as an answer. I will be happy to upvote it.

You have wrong DNS server IP address. In your sketch it is the same as the static IP address you assign to esp. Then the name of the firebase host can't be resolved by DNS.
The DNS server is usually the router/gateway.
IPAddress dns(192,168,1,1)

I also placed the same problem(If I set the static IP means it's not getting internet)But Then I added the DNS "IPAddress dns(192,168,1,1)" for that also it didn't connect to the Internet. But I connected to the Internet after adding the "IPAddress dns(8,8,8,8)".
This is my Code
#include <ESP8266WiFi.h>
const char* ssid = "Varaprasad";
const char* password = "varara";
int red = D6; int green = D7; int blue = D8;
const char* host = "18.221.215.201";
IPAddress staticIP(192,168,1,78);
IPAddress gateway(192,168,1,254);
IPAddress dns(8, 8, 8, 8);
IPAddress subnet(255,255,255,0);
void setup()

{
 pinMode(red,OUTPUT); pinMode(green,OUTPUT); pinMode(blue,OUTPUT);
Serial.begin(9600);
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
WiFi.config(staticIP,dns, gateway, subnet);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
  if(WiFi.status() == WL_CONNECTED){
  WiFiClient client1;
    if (client1.connect(host,80))
      {
         client1.stop();
      analogWrite(red,0); analogWrite(green,1023); analogWrite(blue,0);
      }
      else{
      analogWrite(red,1023); analogWrite(green,0); analogWrite(blue,0);
      client1.stop();
      }
    }
  }


text:
Compile Error Getting when i try to read firebase data using esp32 in Arduino IDE
I am trying to read the firebase data using esp32, when i try to read firebase data statically(string literal) no error is coming.
String board=Firebase.getString(fbdo, F("Device/board")) ? String(fbdo.to()).c_str() : fbdo.errorReason().c_str(); //getting data successfully

But when i try to read data dynamically using String object, i am getting compile error for given code
String string2 = "Device/board";
String board1=Firebase.get(fbdo, F(string2)) ? String(fbdo.to()).c_str() :
    fbdo.errorReason().c_str();

ERROR : #define F(string_literal) (FPSTR(PSTR(string_literal)))

How to solve this problem?

add to the question the exact error message you get

don't use the F macro on esp32

The macro F() can only be used with string literals, not with variables.
A simple solution should be (I cannot test) to provide string2 directly. (I hope that Firebase.get() is overloaded.) Try this:
String board1 = Firebase.get(fbdo, string2) ? String(fbdo.to()).c_str() : fbdo.errorReason().c_str();

To save precious RAM, you might consider to use another data type for string2. To get a similar result, you could try:
const __FlashStringHelper *string2 = F("Device/board");
String board1 = Firebase.get(fbdo, string2) ? String(fbdo.to()).c_str() : fbdo.errorReason().c_str();

To gain some more insight, you might like to read this guide on PROGMEM.

Thank you bro, i will test it and let you know the result


text:
Troubleshooting UART communication between nano 33 ble sense r2 and Adafruit Feather 32u4 with LoRa Radio Module
I've tried connecting the gnd's for both the boards and have connected rx to tx and vice versa in both the boards. I've powered both by batteries, and I'm trying to get sensor data from the nano, and trying to send it to the feather via UART, and long distance away using the Lora capabilities of the Feather.
I've loaded this program in the nano:
/*
Including libraries
*/
//Accelerometer{
#include "Arduino_BMI270_BMM150.h"
//Accelerometer}
//Temperature and humidity{
#include <Arduino_HS300x.h>
//Temperature and humidity}
//Pressure{
  #include <Arduino_LPS22HB.h>
//Pressure}

/*
Creating variables for sensors
*/
//Acceleration variables{
float x, y, z;
//Acceleration variables}
//Temperature and humidity variables{
float temperature;
float humidity;
//Temperature and humidity variables}
//Pressure variables{
float pressure;
//Pressure variables}

void setup() {

/*
Setting up sensors
*/
Serial1.begin(9600);
//Accelerometer{
  if (!IMU.begin()) {
    Serial1.println("Failed to initialize IMU!");
    int i = 0;
    Serial1.println("Trying again\n");
    while (!IMU.begin()){
      if(i>0){
        Serial1.print(" Failed\n");
      }
      Serial1.print("Try number ");
      Serial1.print(i);
      i++;
      delay(1000);
    }
    Serial1.print("Passed\nOn attempt number ");
    Serial1.print(i);
    Serial1.print("\n");
  }
//Accelerometer}
//Temperature and humidity{
if (!HS300x.begin()) {
  Serial1.println("Failed to initialize humidity temperature sensor!");
  int i = 0;
    Serial1.println("Trying again\n");
    while (!HS300x.begin()){
      if(i>0){
        Serial1.print(" Failed\n");
      }
      Serial1.print("Try number ");
      Serial1.print(i);
      i++;
      delay(1000);
    }
    Serial1.print("Passed\nOn attempt number ");
    Serial1.print(i);
    Serial1.print("\n");
}
//Temperature and humidity}
//Pressure{
if (!BARO.begin()) {
  Serial1.println("Failed to initialize pressure sensor!");
    int i = 0;
    Serial1.println("Trying again\n");
    while (!BARO.begin()){
      if(i>0){
        Serial1.print(" Failed\n");
      }
      Serial1.print("Try number ");
      Serial1.print(i);
      i++;
      delay(1000);
    }
    Serial1.print("Passed\nOn attempt number ");
    Serial1.print(i);
    Serial1.print("\n");
}
//Pressure}
}

void loop() {
  /*
  Read sensor data into the variables
  */
  //Read acceleration{
  if (IMU.accelerationAvailable()) {
    IMU.readAcceleration(x, y, z);
  }
  //Read acceleration}
  //Read temperature and humidity{
  temperature = HS300x.readTemperature();
  humidity = HS300x.readHumidity();
  //Read temperature and humidity}
  //Read pressure{
  pressure = BARO.readPressure();
  //Read pressure}

  /*
  Print the sensor data to Serial1 (hopefully implement sending this data to the lora feather, which will radio it to a distant arduino)
  */
  Serial1.print("\nAcceleration (x, y, z): ");
  Serial1.print(x);
  Serial1.print(", ");
  Serial1.print(y);
  Serial1.print(", ");
  Serial1.print(z);
  Serial1.print("\nTemperature: ");
  Serial1.print(humidity);
  Serial1.print("\nHumidity: ");
  Serial1.print(humidity);
  Serial1.print("\nPressure: ");
  Serial1.print(pressure);
  delay(1000);

}

I've loaded this program in the transmitting feather:
/* The program for the feather1 to take information from nano 33 ble sense rev2 and radio it to  where the feather2
** will communicate to the ground station's program todisplay the data in a user friendly manner, and will display results
*/
#include <RH_RF95.h>

// LoRa settings
#define RFM95_CS 8
#define RFM95_RST 4
#define RFM95_INT 7
#define RFM95_FREQ 915.0

RH_RF95 rf95(RFM95_CS, RFM95_INT);

void setup() {
  Serial.begin(9600);
  pinMode(RFM95_RST, OUTPUT);
  digitalWrite(RFM95_RST, HIGH);
  delay(100);
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);
  if (!rf95.init()) {
    Serial.println("LoRa init failed. Check your connections.");
    while (1) ;
  }
  rf95.setFrequency(RFM95_FREQ);
  rf95.setTxPower(23, false);
  Serial.println("LoRa Transmitter Ready!");
}

void loop() {
  static uint16_t messageCount = 0;
  String input;
  while (Serial.available() > 0) {
    char c = Serial.read();
    input += c;
  }
  if (input.length() > 0) {
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    input.getBytes(buf, input.length() + 1);
    rf95.send(buf, input.length() + 1);
    rf95.waitPacketSent();
    Serial.println("Sent message #" + String(messageCount) + ": " + input);
    messageCount++;
  }
  delay(1000);
}

I've got this program in the receiving feather:
/* The program for the feather2 to recieve information from feather1 ** and will communicate to the ground station's program todisplay the data in a user friendly manner, and will display results
*/

#include <RH_RF95.h>

// LoRa settings
#define RFM95_CS 8
#define RFM95_RST 4
#define RFM95_INT 7
#define RFM95_FREQ 915.0

RH_RF95 rf95(RFM95_CS, RFM95_INT);

void setup() {
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  /* The infinite while loop above not needed if you're not using rx/tx for sending
  ** the recieved radio data to your program or are using some other method to
  */
  pinMode(RFM95_RST, OUTPUT);
  digitalWrite(RFM95_RST, HIGH);
  delay(100);
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);
  if (!rf95.init()) {
    Serial.println("LoRa init failed. Check your connections.");
    while (1) ;
  }
  rf95.setFrequency(RFM95_FREQ);
  rf95.setTxPower(23, false);
  Serial.println("LoRa Receiver Ready!");
}

void loop() {
  if (rf95.available()) {
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);
    if (rf95.recv(buf, &len)) {
      Serial.print("Received: ");
      Serial.println((char*)buf);
    } else {
      Serial.println("LoRa receive failed");
    }
  }
}

I have been able to establish UART communication between two Unos before, but I'm unable to find out why it isn't working in this case. I can confirm it isn't working because the Serial monitor for the recieving feather (feather2) only shows this:
17:52:39.840 -> LoRa Receiver Ready!

Why this is happening, and any potential fixes for this?

As I see 32U4 I'd expect the Serial is used for native USB serial (CDC). If you want to use usart on pins 0 and 1, you'd have to use Serial1 instead.
Nano 33 BLE is the same, it has native USB and you are correctly using Serial1 for accessing serial pins 0 and 1 (however nRF52840 can use any pins).


text:
Wake esp8266 from deep sleep with PIR but disable while running code
I am using an ESP8266 to control a ring of neopixels. I want to use a PIR to trigger a brief light show. I'm using batteries and need them to last as long as possible.
I have it working by checking the PIR for motion.  If there is motion I run the light show. If no motion I put the ESP8266 into deep sleep for 15 seconds. When I wake I try again.
I would prefer to use the PIR to reset the ESP, and I did get it to do that but the problem was that further movement would reset again and start the light show from the beginning. I would like to be able to disable reset while I'm running code.
I did some research and found this:
PIR motion wake ESP8266 from deepsleep
It's pretty much what I need.
Is there a final circuit diagram or a similar solution?
Thanks.

Hi I have being using the circuit below now for a few weeks and all seems to work.
When I wake from deep sleep I set the Latch pin to 0 to prevent any more resets. I do the work, I check if there is still motion by reading PIR out, if no movement I set the Latch pin to 1 and go into deep sleep.

Have you measured the current consumption when the PIR is not detecting anything ? To me it looks like 2.5mA if R3 is only 1k.

Updated R3 to 47K and works fine for the last few days. Thanks.


text:
Using a leds driver ic with arduino
I have an ic (CT1642 1442) it's a led driver 8 bit, i want to use it with my arduino nano and i don't have any idea how to use it.
If someone can help me ill be thankfull.

https://github.com/arkroan/CT1642, https://forum.allaboutcircuits.com/threads/how-to-use-an-ct1642-or-sm1642-led-driver-with-key-scan-arduino-project.116955/, https://arduino-projects-free.blogspot.com/2020/07/fd1642-ct1642-sm1642-et6227.html, etc. You'll likely need to be a bit more specific with what exactly you're working with (bare chip? Board with that chip?) and what you want to do with it.

Start by getting the datasheet for the ic and read through it.

@lurker No, start by learning to read Chinese - then get the datasheet and read it...


text:
Atmega2560 PWM on PH4
I am trying to convert the following code to output to pin 7 (PH4, OC4B) on an Arduino Mega. The code outputs to pin 6. This code is from a GitHub for the GRBL on the Mega "https://github.com/fra589/grbl-Mega-5X" out of the cpu_map.h It is clear that PH6 and PH7 are on the same PORTH but I just do not know what bits need changing to get GRBL to output on pin 7.Any help would be welcome.
#elif defined (SPINDLE_PWM_ON_D6)

    // Set Timer up to use TIMER4C which is attached to Digital Pin 6 - Ramps Servo 2
    #define SPINDLE_PWM_MAX_VALUE     255.0 // Translates to about 1.9 kHz PWM frequency at 1/8 prescaler
    #ifndef SPINDLE_PWM_MIN_VALUE
      #define SPINDLE_PWM_MIN_VALUE   1   // Must be greater than zero.
    #endif
    #define SPINDLE_PWM_OFF_VALUE     0
    #define SPINDLE_PWM_RANGE         (SPINDLE_PWM_MAX_VALUE-SPINDLE_PWM_MIN_VALUE)

    //Control Digital Pin 6 which is Servo 2 signal pin on Ramps 1.4 board
    #define SPINDLE_TCCRA_REGISTER    TCCR4A
    #define SPINDLE_TCCRB_REGISTER    TCCR4B
    #define SPINDLE_OCR_REGISTER      OCR4A
    #define SPINDLE_COMB_BIT          COM4A1

    // 1/8 Prescaler, 16-bit Fast PWM mode
    #define SPINDLE_TCCRA_INIT_MASK (1<<WGM41)
    #define SPINDLE_TCCRB_INIT_MASK ((1<<WGM42) | (1<<WGM43) | (1<<CS41))
    #define SPINDLE_OCRA_REGISTER   ICR4 // 8-bit Fast PWM mode requires top reset value stored here.
    #define SPINDLE_OCRA_TOP_VALUE  0xFF // PWM counter reset value. Should be the same as PWM_MAX_VALUE in hex.

    // Define spindle output pins.
    #define SPINDLE_PWM_DDR   DDRH
    #define SPINDLE_PWM_PORT  PORTH
    #define SPINDLE_PWM_BIT   3 // MEGA2560 Digital Pin 6

You want to replace pin 6 (PH3, OC4A) with pin 7 (PH4, OC4B). There are
three things you have to change. First, the output compare register,
which is OCR4A for pin OC4A and OCR4B for pin OC4B. Thus:
-#define SPINDLE_OCR_REGISTER      OCR4A
+#define SPINDLE_OCR_REGISTER      OCR4B

Then, the configuration bit that enables the output:
-#define SPINDLE_COMB_BIT          COM4A1
+#define SPINDLE_COMB_BIT          COM4B1

Last, the bit to set in the data direction register, which is 3 for PH3
and 4 for PH4:
-#define SPINDLE_PWM_BIT   3 // MEGA2560 Digital Pin 6
+#define SPINDLE_PWM_BIT   4 // MEGA2560 Digital Pin 7

Note: as in diff -u format, the prefix - means “remove this”, the
prefix + means “add this”.

Thanks for the help. I spent hours trying to figure out the datasheet.


text:
Help with LCD's menu and seeing values continuously
I want to see the voltage data using void volt();, when I go to the "Item2SubItem3" within void menuChanged. Now I can only see the data at that time: how can I refresh the value every second?
void setup()
{
    // setup()...
}

void loop()
{
    //loop()...
}

// DC Voltometer
float vPow = 4.7;
float r1 = 100000;
float r2 = 10000;

void volt()
{
    lcd.clear();
    float v = (analogRead(0) * vPow) / 1024.0;
    float v2 = v / (r2 / (r1 + r2));
    lcd.setCursor(0, 0);
    lcd.print("DC VOLTOMETER");
    lcd.setCursor(0, 1);
    lcd.print(v2);
    delay(1000);
}

void menuChanged(MenuChangeEvent changed)
{
    MenuItem newMenuItem = changed.to; // get the destination menu
    lcd.setCursor(0, 1);            // set start position for lcd
                                 // printing to the second row

    if (newMenuItem.getName() == menu.getRoot())
    {
        lcd.print("Main Menu       ");
    }
    else if (newMenuItem.getName() == "Item1")
    {
        lcd.print("Item1           ");
    }
    else if (newMenuItem.getName() == "Item1SubItem1")
    {
        lcd.print("Item1SubItem1");
    }
    else if (newMenuItem.getName() == "Item1SubItem2")
    {
        lcd.print("Item1SubItem2   ");
    }
    else if (newMenuItem.getName() == "Item2")
    {
        lcd.print("Item2           ");
    }
    else if (newMenuItem.getName() == "Item2SubItem1")
    {
        lcd.print("Item2SubItem1   ");
    }
    else if (newMenuItem.getName() == "Item2SubItem2")
    {
        lcd.print("Item2SubItem2   ");
    }
    else if (newMenuItem.getName() == "Item2SubItem3")
    {
        lcd.print("Item2SubItem3   ");
        delay(2000);
        volt();
    }
    else if (newMenuItem.getName() == "Item3")
    {
        lcd.print("Item3           ");
    }
    else if (newMenuItem.getName() == "Item4")
    {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Item4           ");
    }
}

I think it would be easier to answer your question if you try to break down your problem to a smaller piece of code.

menuChangeEvent is only called if the menu is changed. I.e. you moved inside the menu. I don't this the MenuBackend framework supports what you want it to do.

how can i use a menu in order to monitoring sensors?

As Gerben implied in a comment, menuChangeEvent is called only when the menu selection changes.  Thus, your voltmeter readout will print only whenever you change the menu selection to Item2SubItem3.  The code shown below illustrates how to modify your loop() so that it checks the menu selection once per second.  Each second the main loop will do whatever function is currently selected, such as displaying a current voltmeter reading.  Note, you can make the menu decoding shorter and less tedious as shown in the answer, and can put variable declarations near where they are used instead of in random places.
void setup() {
}  // setup()...

// DC voltmeter reading
void volt () {
  const float vPow = 4.7, r1 = 100000, r2 = 10000;
  lcd.clear();
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = v / (r2 / (r1 + r2));
  lcd.setCursor (0,0);
  lcd.print("DC Voltmeter");
  lcd.setCursor (0,1);
  lcd.print (v2);
  // Don't delay(1000) since loop() takes care of delay.
}

long int second = 0;
uint8_t itemcode = 0; // Will be number nm for Item n, Subitem m
int passnumber = 0;
void menuChanged(MenuChangeEvent changed) {
  MenuItem menuitem = changed.to; //get the destination menu
  String itemname = menuitem.getName();
  lcd.clear();        // Make printing spaces at line ends unnecessary
  lcd.setCursor(0,1);         //set lcd printing position = second row
  if(newMenuItem.getName() == menu.getRoot()){
    lcd.print("Main Menu");
    itemcode = 0;
  } else {
    lcd.print(itemname);
    itemcode = 10*(itemname[4] & 7);
    if (itemname.length() > 5)
      itemcode += itemname[itemname.length()-1] & 7;
  }
  passnumber = 0; // Actions can test passnumber if they like
  second = 0; // Cause actions to take place now
}

void loop() {
  long int now = millis()/1000; // Get elapsed-seconds
  if (now == second) return;    // Only do stuff once per second
  // Update to current second and do chosen menu item
  second = now;
  switch (itemcode) {
  case  0: break;
  case 10: break;
  case 11: break; // Fill in with code for different cases
  case 12: break;
  case 20: break;
  case 21: break;
  case 22: break;
  case 23:    // Item 2, subitem 3, read voltmeter
    volt();
    break;
  case 30: break;
  case 40: break;
  }
  // You can test passnumber to control for cases that only go once
  ++passnumber;
} // end of loop()

Edit: I moved the declaration of second and added second = 0 within menuChanged() to decrease latency between a menu item being selected and its action taking place.  Without second being zeroed in menuChanged(), up to a second could pass between an item's selection and its action; latency would average 0.5 seconds, which is undesirable in a user interface.


text:
I want to modify setup, to also keep the serial USB port opens so I can send strings via a Raspberry Pi
I am trying to modify the original code from these guys GRA & AFCH, who have made an Arduino Sketch Program that runs a Arduino powered Nixie Clock.
Here is the link to their Firmware file:NixieClockShieldNCS314.ino
Here is the specific part I want to modify.

void setup()
{
  digitalWrite(DHVpin, LOW);    // off MAX1771 Driver  Hight Voltage(DHV) 110-220V

  Wire.begin();
  //setRTCDateTime(23,40,00,25,7,15,1);

  Serial.begin(115200);

    if (EEPROM.read(HourFormatEEPROMAddress)!=12) value[hModeValueIndex]=24; else value[hModeValueIndex]=12;
    if (EEPROM.read(RGBLEDsEEPROMAddress)!=0) RGBLedsOn=true; else RGBLedsOn=false;
    if (EEPROM.read(AlarmTimeEEPROMAddress)==255) value[AlarmHourIndex]=0; else value[AlarmHourIndex]=EEPROM.read(AlarmTimeEEPROMAddress);
    if (EEPROM.read(AlarmTimeEEPROMAddress+1)==255) value[AlarmMinuteIndex]=0; else value[AlarmMinuteIndex]=EEPROM.read(AlarmTimeEEPROMAddress+1);
    if (EEPROM.read(AlarmTimeEEPROMAddress+2)==255) value[AlarmSecondIndex]=0; else value[AlarmSecondIndex]=EEPROM.read(AlarmTimeEEPROMAddress+2);
    if (EEPROM.read(AlarmArmedEEPROMAddress)==255) value[Alarm01]=0; else value[Alarm01]=EEPROM.read(AlarmArmedEEPROMAddress);
    if (EEPROM.read(LEDsLockEEPROMAddress)==255) LEDsLock=false; else LEDsLock=EEPROM.read(LEDsLockEEPROMAddress);
    Serial.print("led lock=");
    Serial.println(LEDsLock);

  pinMode(RedLedPin, OUTPUT);
  pinMode(GreenLedPin, OUTPUT);
  pinMode(BlueLedPin, OUTPUT);

  tone1.begin(pinBuzzer);
  song=parseSong(song);

  pinMode(LEpin, OUTPUT);
  pinMode(DHVpin, OUTPUT);

 // SPI setup

  SPI.begin(); //
  SPI.setDataMode (SPI_MODE3); // Mode 3 SPI
  SPI.setClockDivider(SPI_CLOCK_DIV128); // SCK = 16MHz/128= 125kHz

  //buttons pins inits
  pinMode(pinSet,  INPUT_PULLUP);
  pinMode(pinUp,  INPUT_PULLUP);
  pinMode(pinDown,  INPUT_PULLUP);
  ////////////////////////////
  pinMode(pinBuzzer, OUTPUT);

  //buttons objects inits
  setButton.debounceTime   = 20;   // Debounce timer in ms
  setButton.multiclickTime = 30;  // Time limit for multi clicks
  setButton.longClickTime  = 2000; // time until "held-down clicks" register

  upButton.debounceTime   = 20;   // Debounce timer in ms
  upButton.multiclickTime = 30;  // Time limit for multi clicks
  upButton.longClickTime  = 2000; // time until "held-down clicks" register

  downButton.debounceTime   = 20;   // Debounce timer in ms
  downButton.multiclickTime = 30;  // Time limit for multi clicks
  downButton.longClickTime  = 2000; // time until "held-down clicks" register

  //
  //digitalWrite(DHVpin, HIGH); // on MAX1771 Driver  Hight Voltage(DHV) 110-220V
  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  doTest();
  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  if (LEDsLock==1)
    {
      setLEDsFromEEPROM();
    }
  getRTCTime();
  setTime(RTC_hours, RTC_minutes, RTC_seconds, RTC_day, RTC_month, RTC_year);
  digitalWrite(DHVpin, LOW); // off MAX1771 Driver  Hight Voltage(DHV) 110-220V
  setRTCDateTime(RTC_hours,RTC_minutes,RTC_seconds,RTC_day,RTC_month,RTC_year,1); //записываем только что считанное время в RTC чтобы запустить новую микросхему
  digitalWrite(DHVpin, HIGH); // on MAX1771 Driver  Hight Voltage(DHV) 110-220V
  //p=song;
}

Now, I need to be able to constantly access the standard Serial USB to be able to receive a string from my Raspbery Pi. I was thinking of adding the following after their code in void setup()
Serial.begin(9600);

Now I doubt this alone could let me constantly listen to input from Serial USB. But how can I make the code not conflict with the EEPROM.read() commands (I believe this takes in the value from an RTC module attached to the kit)
Thus, a simple loop like the following might not work:
void loop(){
if (Serial.available()) {
    light(Serial.read() – ‘0’);
}
delay(500);
}

So my question is how can I add functionality such that the Arduino is constantly listening to the Serial port for instructions?
If you are interested in the potential things I want to be able to do with this functionality, please refer to this code: Potentiall Additions
Thank you

(1) You already have serial initialization (Serial.begin(115200)) at your code. (2) "Now i doubt this alone.... ", "... simple loop like this might not work", why not try it first, and tell the error instead of using imagination