text:
How do I resolve error message "assignment of function 'void digitalWrite (uint8_t, uint_8)"?
I am a beginner in using Arduino and programming in c/c++. I am trying to connect a 10-segment LED and a moisture sensor to my Arduino Uno, and when the moisture level is very low, the first 2 red LEDs will be turned on, when it is slightly higher, the next three orange LEDs will be turned on, when it is slightly higher the next three green LEDs will be turned on, and finally when the moisture level is above the threshold for the green LEDs, the final blue LED segment will turn on.   I have written a program that works, and I have tested both the moisture sensor and the 10 segment LED separately to ensure they are working. Although the program works how I intend it, about 30-40% of the time I am unable to run the program due to an error message in the process of uploading. To be clear, I do not change the code at all from the working state of the code to the error message appearing. I wanted to know why this message appears, and how to avoid/resolve this issue.   I have included my code below:
/*
   Arduino LED Bar Graph with Moisture Sensor
   Started June 25, 2020

   edited 6/28
    (added blue LED)
*/

int redLED = 13;
int yellowLED = 12;
int greenLED = 11;
int blueLED = 10;

#define SensorPin A0
float sensorValue = 0;
float moistureLevel = 0;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(redLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED, OUTPUT);
}

void loop()
{
  if  (Serial.available() > 900)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (redLED, HIGH);
    digitalWrite = (yellowLED, LOW);
    digitalWrite = (greenLED, LOW);
    digitalWrite = (blueLED, LOW)
  }
  else if (Serial.available() > 750)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (yellowLED, HIGH);
    digitalWrite = (redLED, LOW);
    digitalWrite = (greenLED, LOW);

  }
  else(Serial.available() > 550)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (greenLED, HIGH);
    digitalWrite = (redLED, LOW);
    digitalWrite = (yellowLED, LOW);
    digitalWrite = (blueLED, LOW);
  }
  else(Serial.available() < 549)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (greenLED, HIGH);
    digitalWrite = (redLED, LOW);
    digitalWrite = (yellowLED, LOW);
    digitalWrite = (blueLED, HIGH);
  }
  for (int i = 0; i <= 100; i++)
  {
    sensorValue = sensorValue + analogRead(SensorPin);
    delay(1);
  }
  sensorValue = sensorValue / 100.0;
  Serial.println(sensorValue);
  delay(100);
}

And here is a copy of the exact error message:
/tmp/777165248/sketch_jun25a/sketch_jun25a.ino: In function 'void loop()':

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:33:33: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = {redLED, HIGH};

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:33:33: error: cannot convert '<brace-enclosed initializer list>' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:34:35: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (yellowLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:34:35: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:35:34: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (greenLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:35:34: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:36:33: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (blueLED, LOW)

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:36:33: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:41:36: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (yellowLED, HIGH);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:41:36: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:42:32: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (redLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:42:32: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:43:34: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (greenLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:43:34: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:47:3: error: expected ';' before '{' token

{

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:54:3: error: 'else' without a previous 'if'

else(Serial.available() < 549)

^~~~

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:55:3: error: expected ';' before '{' token

{

^

exit status 1

the error message occurs during code compilation, not during upload ... you always get that error, not only sometimes .... the obvious thing to do, is to review the digitalWrite command, to see if you made a mistake ... please do that

You have:
digitalWrite = (redLED, HIGH);

This is incorrect since digitalWrite is a function not a variable.  Instead you likely want:
digitalWrite(redLED, HIGH);

This calls the digitalWrite function with the two arguments.

please don't write Answer to syntax error questions. they are off-topic

@Juraj I'm having trouble finding where the site policy prohibits such questions or answers.  Please post a reference to it.  Thanks.

https://arduino.stackexchange.com/help/on-topic "Off topic:  General Coding: "

@Juraj. The coding question is very much Arduino related.  I think you're reading way more into the guideline than is there.

https://arduino.meta.stackexchange.com/questions/2667/trivial-questions-must-be-off-topic

Trivial for you is not trivial for a beginner.

lack of research is a closing reason too. basic examples show how to use digitalWrite.


text:
IRremote sending only works once with Arduino Nano
I am trying to control a receiver, wich is not working. I believe i have to send the code at least three times... but after the first time the IR Led stays off. I am using the Arduino Nano with the LED connected to pin 13. The "Send" message keep printing.

I am using this lib: https://github.com/Arduino-IRremote/Arduino-IRremote
I tried multiple versions of the lib

My code:
#include <IRremote.h>

IRsend irsend;

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

const static unsigned int raw[68] = {8950,4450,550,550,600,550,600,500,600,550,550,550,600,500,600,550,600,500,600,1600,600,1600,600,1650,550,1650,550,550,600,1600,600,1600,600,1650,550,550,600,1600,600,1600,600,550,550,550,600,500,600,550,550,550,600,1600,600,550,550,550,600,1600,600,1600,600,1600,600,1600,600,1650,550};

void loop() {
  Serial.println("Send");
  for (int i=0; i<3; i++) {
    irsend.sendRaw(raw,68,38);
    delay(40);
  }
  delay(5000);
}

Works only again once when resetting the Arduino

In all the examples found in the project's github files the delay between transmissions is over an order of magnitude longer than 40ms. Maybe that would help.

I believe i have to send the code at least three times  ... then what is preventing you from repeating irsend.sendRaw(raw,68,38) two more times?

@st2000 40ms is about right for the NEC protocol. The RAW code looks a lot like NEC.

Are you saying you can't see the IR led light up three times in a row, or that it isn't repeating after the 5 second delay? The former is pretty unlikely for you to notice, as the led being off for 40ms is hard to notice for us humans.

Got it to work... Code is fine. Pin 13 was the problem, because for the Nano it actually is Pin 3.  I actually tested it earlier with another LED but my other one was for some reason really dark, so i  just missed it.

source: Stack Exchange

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

sort: votes


text:
Valid options for output port on Mega 2560
I would like to adopt this library on an Arduino Mega2560:
https://github.com/gueei/DShot-Arduino
However, the macro DSHOT_PORT needs defined for the Mega2560 here:
https://github.com/gueei/DShot-Arduino/blob/master/src/DShot.h
So I need to add a #if defined(__AVR_ATmega2560__) macro to that DShot.h header, however, it is not clear to me where to lookup the port mapping on a 2560 mega.  I'm looking directly at the schematic itself here:
https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf
And understand that the 'ports' are groupings of IO where the pins are described as P?#, ? being the port letter and # being 0-7.
So what are my valid options?  It appears that some ports (A,C,L) aren't pinned at all, some (D,J) only a few pins, and just about none of them (except K/F) have all port pins utilized.  Also, I can see most of these pins are reserved for some type of functionality (analog, SPI, etc).  I'm assuming I'm looking for a port with available pins reserved for PWM, such as Port B (pins 10-13 are PWM).  Would this be correct?

According to the PDF you link to, port A is mapped to digital pins 22-29 on the board, port C to 30-37, port C to 42-49.

You don't care about extra functionality of the pin unless you do need that extra functionality. Why would you want PWM?

Thanks for clarification, I did read the drawing right.  I assumed the lines that stopped early where not completed on the drawing (PDF search function failed me).
Also, w/ respect to the additional functionality, I assumed PWM because DShot is often a replacement for PWM (as far ESC's).  Does other functionality prevent me from using the pin (ex - pin 22 is PB3 'MOSI' SPI signal)?

It would seem this library needs a single pin to communicate. So it
doesn't really matter whether the port you choose has only a few pins
available. Also, you do not care that some pins can have extra
functionality, like SPI, I2C, etc, unless you do plan to use that
functionality.
There is one think you should be aware of: the library uses the in and
out assembly instructions to access the port. These instructions can
only access the ports that are mapped in the regular I/O space of the
microcontroller, not those that are in the “extended I/O” space. In the
case of the ATmega2560, this means you can use any of the ports A
through G, but you cannot use H, J, K nor L.

Thank you for feedback!  Sounds like I can likely use most any pin on the board.

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


text:
Using an Arduino as an input device
I had an idea to create a control panel using an arduino and some buttons. How would I go about making the arduino emulate an input device so that when I press a button connected to the arduino, it would cause the same effect as when a keyboard key was pressed? (I'm using arduino UNO, if it helps.)
Thanks in advance.

Welcome to Arduino SE! This post was closed as a duplicate of this question: http://arduino.stackexchange.com/questions/991/can-the-2nd-mcu-on-the-uno-r3-be-used-for-keyboard-emulation. If you feel that this question is different, please feel free to edit your question. Thanks!

I don't agree that this is a duplicate. That question asks whether or not it can be done in a specific way, whereas this question asks in general, only mentions the Uno in passing (and not even the R3 specifically), and doesn't bring up the '16U2 at all.

The easy answer is to use a Leonardo, Micro, or Due instead. They already support USB HID functionality via Mouse and Keyboard.
If you insist on using an Uno R3 then you will need to reprogram the on-board ATmega16U2 to accept serial commands from the ATmega328P and generate the appropriate USB HID events.
If you're using an Uno or clone that doesn't have an ATmega16U2 as well then you're SOL and will have to write a program that runs on the computer that receives the commands via serial and translates them into HID events.

I have successfully reprogrammed the UNO's R3 8U2 to support keyboard emulation, as to just this. Making dedicated user inputs for kiosks to Computers. I recommend NicoHood's GitHub as it allows simultaneous Arduino Bootloader and Keyboard functionality, making it easy to reprogram the Arduino.
This along with using Capacitive Touch Sensor connected to Copper tap under clear acrylic protecting printed graphics of buttons is very quick and easy to make. Very little machining.
Example of such code is found at artemis-firmwares it was initially created with a different 8U2 method. Where next time we will use NicoHood's.
Note the stock keyboard send key command for the Arduino is limited. Where the above methods allows the code to send complete virtual keys supporting full emulation.

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


text:
Which arduino should I start on to learn about it?
I'm pretty interested in arduino and the things I can learn from it. Being that I'm new into this I wanted to know which model I should get that would be easiest to learn on and why. What does this model come with, how much, and reputable place where one can purchase this.

How new are you? Do you know EE? C++?

Welcome to Arduino SE! This question is really broad since we don't know anything about your abilities and skills. For now, I've closed the question. You can edit your question to add more information (i.e. programming skill, needs/wants, budget, potential projects, etc.). Thanks!

I would simply say: buy a startkit like this one.At the end it is not important which Arduino board you'll start. They are (almost) the same*. At the very beginning you can start with Uno or Nano and even Leonardo could be very good. Those boards are very similar and you can program them in the same. Even the pins location and designation is not really different.
The most important thing about Arduino is to understand how to work and program and interface such a board with the sensors. In this sense I would choose a Uno board (or even 2009) which is less expensive and very easy to find overall. I don't really know how much experience you have, but it is likely, at the beginning, that you invert polarities of batteries, you drain too much power, or you invert some pins and damage the microcontroller. In that case doesn't make sense to buy the last powerful mega expensive board on the mark. If you get a Uno you can do almost everything and have for the next month a lot to learn.
To change from Uno or Nano to the other board it is not very difficult. Once you understand the basis you can switch to every board you want. If you need more power and memory you can buy a Mega. If you need much more power you can buy a Due/Tre/etc...you need just an upgrade not everything from scratch to learn.
If you are really new to Arduino the best way is to buy such a learn package as I showed you above. That have everything you need to understand basic of programming till to RC-Servo movement and motor drivers.
Happy new year.
*: stay away for the moment from the Arduino Due/Tre/Zero/Yuan/.. series. they are too expansive and require a lot of attention (3.3V, max drain current from the pins, pull up, pull down...etc..). Here is the risk to get your board damaged within few time very high. And you'll spend a lot of time thinking that the board has some problems.

Not to mention that most of those are ARM-based and so will require relearning the in-depth stuff if you go there.

Agree on the starter kit. Another option if you don't know much/any programming or electronics is start with a makeymakey board.  The main thing is to learn basic electronics and interfacing and to get comfortable breaking down things into small basic steps that are easy to program.

@IgnacioVazquez-Abrams you are right but seen from the side of the program doesn't too much from Due und Uno. There are new functions, of course, but the IDE and all the library stuff is the same. But in EE you are right, it needs a lot more caution and deep understanding how microcontroller works

It's best to buy an official starter kit: you support the community and you receive support if something doesn't work as expected http://store.arduino.cc/product/K000007

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


text:
Can't store temperature in variable ( for further processing)
I am trying to store temperature data in a variable, so that I can use it for making a JSON object, but the problem is, that when I try to store the temperature in a variable, it prints out the wrong value. I'm using a DHT11 temperature/humidity sensor and a library for calculating the temperature.
Serial.print("Temperature (°C): ");
Serial.println((float)DHT11.temperature, DEC);
int temp1 = ((float)DHT11.temperature, DEC);
Serial.println(temp1);

These 4 lines is printing out this:
Temperature (Â°C): 23.0000000000
10

The first one is correct, but the second line should also be saying "23".
I have tried only loading the data in once with the library, as in outcommenting one line, but that does not work.
It's like I have some syntax wrong, but I can't figure out what.

This line:

int temp1 = ((float)DHT11.temperature, DEC);

casts DHT11.temperature to an float, throws away the value, then assigns DEC to temp1. That is not what you want.

int temp1 = DHT11.temperature;

Thank you so much. This fixed it straight away. I knew it was just some stupid syntax that I was doing wrong, but I just couldn't figure out what. Thnx.

For extra reading: http://en.wikipedia.org/wiki/Comma_operator


text:
Problem with declaring 2D vector in Arduino
I have included the STL library in Arduino and i can run a program with 1D vector.
But i am getting error while declaring a 2D vector.
#include <StandardCplusplus.h>
#include <serstream>
#include<vector>
#include<iterator>

using namespace std;

vector <vector<int> > grid;
vector<int> col(5,3);
grid.push_back(col);

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

void loop()
{
  for(int i = 0; i < 5; i++)
  {
    Serial.println(grid[[0][i]);
  }
}

And the error is
'grid' does not name a type.

Do i need to add another header file?

The error is coming from
 grid.push_back(col);

You cannot have this line at the top-most level outside a function / main. Move it inside setup or loop.


text:
Interfacing SD card with arduino without shield
I am trying to connect SD card with arduino without using a shield. To convert to 3.3v, I have used voltage divider circuit as described in these two sites:
http://garagelab.com/profiles/blogs/tutorial-how-to-use-sd-card-with-arduino
http://www.martin-gardner.co.uk/how-to-connect-your-old-sd-card-to-an-arduino/
When I uploaded the code i got the following error on serial monitor:
Initializing SD card...initialization done.
error opening test.txt
error opening test.txt

Can you show us your code and circuit diagram?

The code is exactly of Examples/SD/ReadWrite

Is the SD card properly formatted. FAT or FAT32?

Yes, it has been formatted to FAT32.

Does your code use CS pin 10 as shown in your wiring diagram, or use CS pin 4 as shown in the martin-gardner.co.uk site code? It's related to the initialization code if (!SD.begin(4)) {.

@MarkU We have changed the code 'if(!SD.begin(4))'  to   '(!SD.begin(10))'

I can't understand what exactly happened, but i first uploaded CardInfo file from Examples > SD > CardInfo and after that i uploaded ReadWrite and i got the correct output.


text:
Can anyone suggest me a software timer library that does not use polling but timer ISR instead?
There are many software timer libraries available in Arduino.
A library called SimpleTimer http://playground.arduino.cc/Code/SimpleTimer is really good with many functions, but it uses polling.
If anyone is familiar with a really good library that uses Timer ISR of Atmega instead of polling, please suggest me as i am using ultrasonic sensors and i can't afford polling.

If it used the hardware timer then it wouldn't be a software timer library.

ultrasonic sensor is using the pulseIn() function. But i need software timer for another purpose.

Yeah, I have the same problem.
The only solution I found is to rewrite  a lot of the code. Still ongoing, though.
For you, Timer1 is probably the best candidate, unless you have already some use for it, like in my case.
A quick hack is to free Timer0: it is currently (ab)used by the wire library, which provides the typical arduino timing.
But you can remove/rename the file wiring.cpp to something that will not be identified as source (ex: wiring._cpp) and comment out the init() function call from the main() function in the main.c file.
Normal Arduino stile time functions will not work, of course.
Unfortunatelly Arduino SW really lacks the structured design that would allow it to be useful in more complex cases and most of the libraries make exclusive use of resources that could be shared, timer being the most prominent example.
Port ISRs is another.
Btw, if you happen to use a SW serial library, it's already game over, as it busy loops inbetween bits, in interrupt context (!), rather than using a timer.

Correct me if i am wrong: the first line of timer1 library page says : "This library is a collection of routines for configuring the 16 bit hardware timer called Timer1"  Can it be used to generate software interrupts?

I decided to ignore the library and write my own, as I didn't like the style used by the library.
Here's my (GPLv2) work:
https://github.com/igor-stoppa/pem
Check
https://github.com/igor-stoppa/pem/tree/master/src/pem_Arduino
you can look at hw-adaptation-uno.cpp for a very simple exampel of how to use the timer.

Thanks! I don't intent to use your entire work, but it will surely help me write my own code. thanks.

Yes, I wasn't proposing that :-)
But it shows in few lines how to use directly the timer interrupt. For more details, you can refer to the fine manual, but it shouldn't be necessary.
The slightly trickier part is to calculate the value to use.

What you do, is:
check your main clock (20/16/8MHz), choose a divider for the prescaler, then calculate the scaled clock (main/prescaler) and multiply it by the period you want to use. The result must be subtracted from the max value that the timer register can assume (256 for 8bit, 65536 for 16bit register).
This will cause the Overflow interrupt to trigger once  the max value is reached.
Then you can rearm or not, depending if it's periodic.
Remember to rearm as first thing, so that the period is stable, regardless of what else you do in the isr.

Can you help me with this? http://arduino.stackexchange.com/questions/6860/error-function-not-declared-in-the-scope

done, please remember to upvote my answers if they are useful ;-)


text:
How to get the name of connected device over BLE?
I am implementing a BLE peripheral in my firmware with Arduino ESP32.
When the central gets connected to it, I'd like to log the name of the central & its address.
How can I do that?
#include <BLEServer.h>

class ServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
        ble.log("ServerCallbacks: Connected");

// ==> how can I add the connected device ID or name in the log?

        ble.deviceConnected = true;

        #if SUPPORT_LEDS_INDICATOR

        // === Show France flag colors
        // RGBW = 1,2,3, 4
        // CODE : BBWRR
        // CODE = 33411
        const String code = "BBWRR";
        ledIndicator.showAccessCode(code);
        #endif

        #if SUPPORT_BUZZER
        /// BLE connection jingle
        buzzer.playBleConnectedMelody();
        #endif
    };

    void onDisconnect(BLEServer* pServer) {
        ble.deviceConnected = false;
        ble.log("ServerCallbacks: Disconnected");

        #if SUPPORT_BUZZER
        /// BLE connection jingle
        buzzer.playBleDisconnectedMelody();
        #endif
    }
};

/// Somewhere in the setup:
server = BLEDevice::createServer();

// == Set up our calbacks
server->setCallbacks(new ServerCallbacks());

(Note: this is all just from reading the library source code, nothing has been tested).
You can't get the details of the just-connected-client. However you can get a list of the currently connected clients.
There is a function in the BLEServer class:
std::map<uint16_t, conn_status_t> getPeerDevices(bool client);

You can use that to get the list of connected clients. The "key" of the map is the connection id, and the "value" of the map is the "conn_status_t" struct, which includes a pointer to the peer device structure:
typedef struct {
    void *peer_device;
    bool connected;
    uint16_t mtu;
} conn_status_t;

You can keep your own list of "current" connection IDs and compare that to the "live" list when a new connection is made to find which is the new connection.
So you can take that peer_device pointer, cast it to a BLEClient pointer, then you call any of the normal BLEClient functions on that, including toString() which will return a string representation of the client.
That of course isn't the "name" of the client. I am not sure (not being an expert on BLE) how you get the name, but I think you may have to actively query it from the client, which should be perfectly possible now you have the BLEClient object pointer.


text:
In CLion, how can I set up multiple cpp files for arduino
I'm using the Arduino plugin in CLion. I can't seem to figure out how to have multiple cpp files for my classes. I have been putting the code in my .h up until now, but that's going to bite me soon.


text:
Mega2560 programming megacore avrdude: Device signature = 0x000000
I have two sunfounder mega2560s. I am using one as an ISP programmer and the other is my target. The programmer has the original bootloader on it. I have placed the ArduinoISP sketch on my programmer and connected LEDs and stuff as here: https://www.arduino.cc/en/pmwiki.php?n=Tutorial/ArduinoISP
I have connected all six pins on my programmer to all six pins on the target. I'm using the ICSP towards the middle of the board on both boards as opposed to the one near the USB cable.
I am trying to place megacore on the target. I have followed the directions here: https://github.com/MCUdude/MegaCore#how-to-install.
I am running Arduino IDE on Windows 10. I am selecting Tools->Board->megacore->Mega2560 and then Tools->Programmer->Arduino as ISP.
I believe all of this setup is correct, so I Click Burn Bootloader. I get the following results:
Arduino: 1.8.15 (Windows Store 1.8.49.0) (Windows 10), Board: "ATmega2560, Yes (UART0), EEPROM retained, Arduino MEGA pinout, BOD 2.7V, LTO disabled, External 16 MHz"

avrdude: Version 6.3-20201216

         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\ThomH\Documents\ArduinoData\packages\MegaCore\hardware\avr\2.1.3/avrdude.conf"

         Using Port                    : COM19

         Using Programmer              : stk500v1

         Overriding Baud Rate          : 19200

         AVR Part                      : ATmega2560

         Chip Erase delay              : 9000 us

         PAGEL                         : PD7

         BS2                           : PA0

         RESET disposition             : dedicated

         RETRY pulse                   : SCK

         serial program mode           : yes

         parallel program mode         : yes

         Timeout                       : 200

         StabDelay                     : 100

         CmdexeDelay                   : 25

         SyncLoops                     : 32

         ByteDelay                     : 0

         PollIndex                     : 3

         PollValue                     : 0x53

         Memory Detail                 :

                                  Block Poll               Page                       Polled

           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00

           flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00

           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500

         Description     : Atmel STK500 Version 1.x firmware

         Hardware Version: 2

         Firmware Version: 1.18

         Topcard         : Unknown

         Vtarget         : 0.0 V

         Varef           : 0.0 V

         Oscillator      : Off

         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000

avrdude: Yikes!  Invalid device signature.

         Double check connections and try again, or use -F to override

         this check.

avrdude done.  Thank you.

I have double checked all of my connections and am powering the target 2560 from a power block on a USB cable.
All research on the web turned up only issues with connections or separate power. Also, I don't know how to use the avrdude from the command prompt to add the -F as suggested.
Having tried everything, I'm looking for help here. Thanks.

How did you connect the Mega2560 to the Mega2560 (as the link you provided does not show that)? The Mega2560 uses different pins (50, 51 and 52) for programming the bootloader than the Uno. Have you mounted a 10µF capacitor between the Reset and GND line of the "programmer" Mega2560?

I have connected all six pins on my programmer to all six pins on the target. I'm using the ICSP towards the middle of the board on both boards as opposed to the one near the USB cable. -- That sounds very wrong. I suggest finding a reliable tutorial to follow.

The answer was that you must connect the reset pin of the target ICSP to pin 10 of the programmer Mega 2560. This was not very clear in the tutorial here: https://www.arduino.cc/en/pmwiki.php?n=Tutorial/ArduinoISP.
This fixed the problem for me, so it was a connection issue.


text:
Loading code to a mega 2560
As part of my application, I need to be able to update the code on my mega 2560 in the field with a download from the internet.
I have found this code in the AT Mega 2560 data sheet
 ;-the routine writes one page of data from RAM to Flash
 ; the first data location in RAM is pointed to by the Y pointer
 ; the first data location in Flash is pointed to by the Z-pointer
 ;-error handling is not included
 ;-the routine must be placed inside the Boot space
 ; (at least the Do_spm sub routine). Only code inside NRWW section can
 ; be read during Self-Programming (Page Erase and Page Write).
 ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24),
 ; loophi (r25), spmcrval (r20)
 ; storing and restoring of registers is not included in the routine
 ; register usage can be optimized at the expense of code size
 ;-It is assumed that either the interrupt table is moved to the Boot
 ; loader section or that the interrupts are disabled
..equ PAGESIZEB = PAGESIZE*2 ;PAGESIZEB is page size in BYTES, not words
.org SMALLBOOTSTART
Write_page:
    ; Page Erase
    ldi  spmcrval, (1<<PGERS) | (1<<SPMEN)
    call Do_spm

    ; re-enable the RWW section
    ldi  spmcrval, (1<<RWWSRE) | (1<<SPMEN)
    call Do_spm

    ; transfer data from RAM to Flash page buffer
    ldi  looplo, low(PAGESIZEB) ;init loop variable
    ldi  loophi, high(PAGESIZEB) ;not required for PAGESIZEB<=256

Wrloop:
    ld   r0, Y+
    ld   r1, Y+
    ldi  spmcrval, (1<<SPMEN)
    call Do_spm
    adiw ZH:ZL, 2
    sbiw loophi:looplo, 2 ;use subi for PAGESIZEB<=256
    brne Wrloop

    ; execute Page Write
    subi ZL, low(PAGESIZEB)       ;restore pointer
    sbci ZH, high(PAGESIZEB)      ;not required for PAGESIZEB<=256
    ldi  spmcrval, (1<<PGWRT) | (1<<SPMEN)
    call Do_spm

    ; re-enable the RWW section
    ldi  spmcrval, (1<<RWWSRE) | (1<<SPMEN)
    call Do_spm

    ; read back and check, optional
    ldi  looplo, low(PAGESIZEB)   ;init loop variable
    ldi  loophi, high(PAGESIZEB)  ;not required for PAGESIZEB<=256
    subi YL, low(PAGESIZEB)       ;restore pointer
    sbci YH, high(PAGESIZEB)
Rdloop:
    elpm r0, Z+
    ld   r1, Y+
    cpse r0, r1
    jmp  Error
    sbiw loophi:looplo, 1         ;use subi for PAGESIZEB<=256
    brne Rdloop

    ; return to RWW section
    ; verify that RWW section is safe to read
Return:
    in   temp1, SPMCSR
    sbrs temp1, RWWSB     ; If RWWSB is set, the RWW section is not ready yet
    ret
    ; re-enable the RWW section
    ldi  spmcrval, (1<<RWWSRE) | (1<<SPMEN)
    call Do_spmr
    jmp Return

Do_spm:
    ; check for previous SPM complete
Wait_spm:
    in   temp1, SPMCSR
    sbrc temp1, SPMEN
    rjmp Wait_spm
    ; input: spmcrval determines SPM action
    ; disable interrupts if enabled, store status
    in   temp2, SREG
    cli
    ; check that no EEPROM write access is present
Wait_ee:
    sbic EECR, EEPE
    rjmp Wait_ee
    ; SPM timed sequence
    out  SPMCSR, spmcrval
    spm
    ; restore SREG (to enable interrupts if originally enabled)
    out  SREG, temp2
    ret

I am trying to convert this to code I can use in my arduino project under wiring. My first question is the register. It looks like spmcrval is register 20, but how can I access that register from within my arduino project?
I have found constants like SPMEN in the arduino header, but not these register names.
Also, feel free, if you wish, to avoid the drama and say, "Here's the C source code," which will be worth a certain amount of hero worship.
Everything appears to use avrdude and so I'm trying to parse that as well.

https://github.com/jandrassy/ArduinoOTA/blob/master/examples/Advanced/OTASketchDownload/OTASketchDownload.ino

Only from bootloader section is it possible to write to flash on ATmega2560. Optiboot 8 has a do_spm function to write to flash. It is accesible over a header file available in examples in the Optiboot GithHub repository.
After the updated application binary is written to free part of the flash by the running application it is necessary to copy the updated application to run location from address 0. This must be done again by the bootloader.
Optiboot builds in MCUdude Mega Core and Mighty Core have Optiboot enhanced with my copy_flash_pages function which copies the pages and then resets the MCU.
My ArduinoOTA library uses do_spm and copy_flash_pages function to store and apply uploaded sketch binary. The InternalStorage object can be used to apply a downloaded binary too.

What I'm seeing handles the downloads. Is there something here that installs those downloads into the Mega 2560? I am pushing from a tablet.

it is a self update. calling InternalStorage.apply replaces the sketch with the downloaded binary

posted another question here: https://arduino.stackexchange.com/questions/85142/program-a-mega2560-from-a-different-serial-port about how to change a serial port to the one used by HC-05. can't find an example, but it seems basic.


text:
Using prototype PCBs as Arduino shield
Is is possible to use prototype PCBs (PCB with grid of unconnected holes with copper around them, usually with pitch 2.54 mm) as Arduino shield, when they are fitted with appropriate pin headers?
I am asking this question because I am not sure whether the Arduino UNO pin headers (which are split) will fit to the headers on the prototype PCB where I will “leave out” one pin on the header.
(Yes, I ho not have a Arduino board to try it out now.)

For the UNO style boards, no it's not possible. The digital headers have a 0.16 inch gap between them which offsets one set of headers 0.06" from the holes in the shield.
For this reason you can buy specific Arduino prototyping shields that have the headers in the right locations.

are you saying that the header pins are 0.16 inch apart?

@jsotola the entire header for pins 0-7 is not on the same 0.1 inch grid that the other three female headers collectively share together. Really, it's the distance between the center of digital pin 7 and center digital pin 8 being referred to. So without splitting hairs on about the distances between plastic housings and nearest distances and all that, it's the distance (by some definition) between two entire headers. That is, it's not referring to header's pin "pitch".

Yep, I thought that. Thank you.


text:
How to control 1 servo with 2 potentiometer?
I have been building a RC plane completely from scratch using an arduino but I am fairly new to this.
Essentially I have been able to make my two arduinos communicate with each other so that when one joystick is moved, the brushless motor is activated, and when the other joystick is moved up or down, 2 servos are activated to push my plane flaps up or down.
The problem I am running into is I am not sure how to control the same servo motors when I move the joystick left and right. Ideally when moved left, one servo would push a flap up and the other down, and vice versa.
The closest thing I have come across on the internet is using a push button to switch between the two control methods but I would ideally like everything to work more smoothly together w/o the push button if that makes sense.
If anyone has any ideas what to write in my code please let me know or if I need to clarify anything else.
Thank you so much for the help in advance.

joystick up-down and joystick left-right are two separate, independent controls

try reading on the finite state mashine. In simple programs like this it would help yyou manage different states.
https://create.arduino.cc/projecthub/tolentinocotesta/let-s-learn-how-to-use-finite-state-machine-with-arduino-c524ac?ref=part&ref_id=8233&offset=13

you are probably trying to do read joystick1, move servo1 ... read joystick2, move servo1 somehow ..... instead use variables ...  read joystick1, set variable value ... read joystick2, adjust variable value ... use final variable value to move servo1

Flaps or Ailerons? https://www.youtube.com/watch?v=XxrdhJanotw

First you should make sure that your inputs and outputs are separated in code. This means that the inputs (like the joystick potis) only change variables in your code. Then below the input code block you output these variables to the servos and motors. This makes the code in your situation easier, since the inputs don't trigger actions, but only set the variables for the actions, which then get executed by another code block.
Your up-down joystick sets the position for the flaps (as you have already coded). The left-right joystick then only creates a deflection from that position. You can code this like the following (in pseudo code):
Read up-down joystick
Map value from analog value to range 0 to 180 and save in variable "flap_pos"
Read left-right joystick
Map value from analog value to range -90 to 90 and save in variable "flap_deflection"
Write servo1 value as "flap_pos+deflection"
Write servo2 value as `flap_pos-flap_deflection"

Note that flap_deflection can be negative or positive (depending on joystick direction) and can thus deflect in both directions. And the different signs in the servo commands make sure that the deflection will behave inverted between the servos (one side moving down when the other is moving up). You will need to adjust the value mapping depending on your flap hardware. And you might want to restrain the values to a specific range (also depending on your hardware).
As you can see there is no if statement or similar in the pseudo code above. All the magic is in the mapping of the read analog values and the addition and subtraction.

Like the idea of pseudo code. The only reason why I am not marking up is becuase the question does not contain enough question to have a correct answer

There is no real magic, it is just simple math. :-D In "the good ol' days" analog mixers did what you describe digitally. Anyway, good answer, even if it reveals that (young) developers lost a lot of knowledge today.


text:
Deserialization error arduino uno and nodemcu esp8266 to Thingspeak
I am currently sending temperature and humidity readings to a Thingspeak channel via a nodemcu esp8266 wifi module using serial communication between the arduino and esp. I have set the time between sending data to Thingspeak to 30s, however the time stamps I receive on my Thingspeak channel are very inconsistent even though the data has been supposedly sent (ranging from 3 minutes to 15 minutes). I suspect this could be due to some timing error as I receive many deserialization errors when I convert the Json string (deserialize it on the NodeMCU side). Any help would be appreciated! Note, this is only a part of the project, there are multiple relays added, thus using the nodemcu on its own would be insufficient. I have also added some images, which shows the outputs.
Arduino Uno code:
//Arduino side code
#include <DHT.h>

#include <avr/wdt.h>                //Watchdog Timer

#include <SoftwareSerial.h>         //Arduino to NodeMCU Lib
#include <ArduinoJson.h>

SoftwareSerial nodemcu(5, 6);       //Initialise Arduino to NodeMCU (5=Rx & 6=Tx)

//Initialisation of DHT22 Sensor
#define DHTPIN 4
DHT dht(DHTPIN, DHT22);
float tempC;
float humidity;
float VPD;

void setup() {
  Serial.begin(9600);
  dht.begin();
  nodemcu.begin(9600);
  delay(2000);

  wdt_enable(WDTO_4S);              //Enable Watchdog timer

  Serial.println("Program started");
}

void loop() {
  StaticJsonDocument<1000> doc;

  dht22_func();                          //Obtain Temp and Hum data

  doc["humidity"] = humidity;            //Assign collected data to JSON Object
  doc["temperature"] = tempC;
  doc["VPD"] = VPD;

  serializeJson(doc, nodemcu);           //Send data to NodeMCU

  wdt_reset();                           //Reset for WDT
}

void dht22_func() {

  humidity = dht.readHumidity();
  tempC = dht.readTemperature();
  Serial.print("Humidity: ");
  Serial.println(humidity);
  Serial.print("Temperature: ");
  Serial.println(tempC);

  if (isnan(humidity) || isnan(tempC) || humidity == 0.0 || tempC == 0.0) {
    while (1) {}
  }
}

NodeMCU code:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>

#include <ESP8266WiFi.h>
#include <ThingSpeak.h>

SoftwareSerial nodemcu(D6, D5);                 //D6 = Rx & D5 = Tx

unsigned long previousMillis = 0;
unsigned long currentMillis;
const unsigned long period = 10000;             //Upload interval in ms

float tempC;
float humidity;
float VPD;

String apiKey = "";             //Write API key

unsigned long channelID = ;              //Thingspeak channel ID
const char *ssid =  "";             //Local network ssid
const char *pass =  "";                 //Local network password
const char* server = "api.thingspeak.com";      //Thingspeak server

boolean state1 = false;                         //Boolean variables
boolean state2 = false;

WiFiClient client;

void setup() {
  Serial.begin(9600);
  nodemcu.begin(9600);
  ThingSpeak.begin(client);
  while (!Serial) continue;
  delay(2000);

  Serial.println("Program Started");

  wifi_connect();                                      //Establish wifi connection
}

void loop() {
  currentMillis = millis();                                  //Get current time

  if ((currentMillis - previousMillis >= period)) {

    if (WiFi.status() != WL_CONNECTED) {                    //Check if connected to wifi, else
connect
      wifi_connect();
}
else {
  Serial.println("Currently Connected to WiFi");
}

while (state1 == false) {                                //Connect to Thingspeak and push data

  while (state2 == false) {
    parseJsonObject();
  }

  cloud_connect();
}

state1 = false;
state2 = false;
Serial.println("Cloud Connect Succesful");
Serial.println("-----------------------------------------");
previousMillis = previousMillis + period;                     //Update counter
  }
}

void wifi_connect() {
  Serial.println("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);

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

void cloud_connect() {
  if (client.connect(server, 80)) {           //80 is the standard port number used for web access
    String postStr = apiKey;
    postStr += "&field1=";
    postStr += String(tempC);
    postStr += "&field2=";
    postStr += String(humidity);
    postStr += "\r\n\r\n";

    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(postStr.length());
    client.print("\n\n");
    client.print(postStr);

    Serial.print("Temperature: ");
    Serial.print(tempC);
    Serial.print(" || Humidity: ");
    Serial.println(humidiy);
    Serial.println("Sent to Thingspeak");

    //Change state to true to break while loop
  state1 = true;
  }
  client.stop();
}

void parseJsonObject() {
  //Parse JSON object from serial port
  StaticJsonDocument<1000> doc;
  DeserializationError error = deserializeJson(doc, nodemcu);

  // Test if parsing succeeds
  if (error) {
    Serial.println("deserializeJson error");
    return;
  }

  //Parse Json values and store in variable
  humidity = doc["humidity"];
  tempC = doc["temperature"];

  if (isnan(humidity) || isnan(tempC) || humidity == 0.0 || tempC == 0.0) {
    Serial.println("Invalid Sensor Readings");
    return;
  }

  state2 = true;
  Serial.println("JSON Object Recieved");
}

try much less than 1000 bytes for StaticJsonDocument

How would this help? I'm quite a newbee to the javascript file format.

Uno has only 2000 bytes of SRAM

How much would be required for this application? Thank you for the response

I guess 200 should be enough. https://arduinojson.org/v6/assistant/

Thank you. This has shortened the intervals between uploads to Thingspeak, however the main problem of the deserilization of the json file is still evident (inconsistent intervals) . Any possible suggestions on this? I think most of the strings the nodemcu sends to the cloud might be "broken" - not the correct format, probably due to some timing error.

so a simplest patch would be to add at the beginning of parseJsonObject line while (nodemcu.peek() != '{') nodemcu.read(); to 'sync' the input to the beginning of the simple json you send from Uno so the deserializeJson doesn't start in the middle of the json (the Uno sends them without a pause)

Thingspeak supports multiple fields in one transaction so it may not be necessary to pack the data into a json string if you are sending only temperature and humidity value every 30 seconds or so.

@6v6gt json is send between uno and esp8266

thank you @juraj , I will try that now and let you know!

@juraj thank you so much. Massively improved the intervals and consistency between uploads. Regards!


text:
The code of ISR executes twice
i am using Arduino Mega.. ANd this is the code:
void bump(void);

void setup()
{
    pinMode(19,INPUT);
    attachInterrupt(4,bump,HIGH);
    pinMode(13,OUTPUT);
}

void loop()
{

}

void bump()
{
   for(float i = 0; i < 90000; i++){
   digitalWrite(13,HIGH);
   }
   for(float i = 0; i < 10000; i++){
   digitalWrite(13,LOW);
   }

}

Although i give +5 V to it once, the LED will blink twice...!
What is the solution?

Why have you chosen float as the data type of your counter, 'i'? At least, is 'float' used elsewhere in your program? If not, this use drags in a lot of code, just for counting. And why are you re-writing your port i/o on each count? Wouldn't: digitalWrite(13,HIGH); delay(ONTIME); digitalWrite(13,LOW); delay(OFF_TIME); do what you intend?

@JRobert: I wanted a huge value for i so i chose float.. Mayb long would have been better.. And we can't use delay inside ISR..

ISRs should never do more then needed. You can block other functions of the Arduino. Very seldom do I do anything more then set or clear a flag. In some variations of the Arduino family long times will cause it to crash.

After wondering over it for quite a long time, I finally came to the conclusion, that the interrupt should be made to trigger at RISING edge, if I want it to go into ISR the moment it gets HIGH.
Hence the setup line was change to
attachInterrupt(4,bump,RISING);

And the cod e works well.
I suppose that is because, when it receives a HIGH signal, than the period for which it receives HIGH is a bit long, during which it adds another interrupt into the queue, and so the ISR is executed once again.

Remember to mark your answer as solution in three days ;)

Oh yes, thanks a lot.. I didn't knew that :)


text:
PC8563 Arduino interface
i am trying to interface pc8563 with arduino uno . I have small doubt related to RTC slave address reading
RTC datasheet says page no 14
where device slave address is A2 for write and Read A3
i would like to know how A2 /A3
Example code from website device id mentioned as 0X51
My question how to config exact slave address ??
#include "Wire.h"
#define PCF8563address 0x51

byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

byte bcdToDec(byte value)
{
  return ((value / 16) * 10 + value % 16);
}

byte decToBcd(byte value){
  return (value / 10 * 16 + value % 10);
}

void setPCF8563()
// this sets the time and date to the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.write(decToBcd(second));
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));
  Wire.write(decToBcd(dayOfMonth));
  Wire.write(decToBcd(dayOfWeek));
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.endTransmission();
}

void readPCF8563()
// this gets the time and date from the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.endTransmission();
  Wire.requestFrom(PCF8563address, 7);
  second     = bcdToDec(Wire.read() & B01111111); // remove VL error bit
  minute     = bcdToDec(Wire.read() & B01111111); // remove unwanted bits from MSB
  hour       = bcdToDec(Wire.read() & B00111111);
  dayOfMonth = bcdToDec(Wire.read() & B00111111);
  dayOfWeek  = bcdToDec(Wire.read() & B00000111);
  month      = bcdToDec(Wire.read() & B00011111);  // remove century bit, 1999 is over
  year       = bcdToDec(Wire.read());
}

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  // change the following to set your initial time
  second = 0;
  minute = 28;
  hour = 9;
  dayOfWeek = 2;
  dayOfMonth = 13;
  month = 8;
  year = 13;
  // comment out the next line and upload again to set and keep the time from resetting every reset
  setPCF8563();
}

void loop()
{
  readPCF8563();
  Serial.print(days[dayOfWeek]);
  Serial.print(" ");
  Serial.print(dayOfMonth, DEC);
  Serial.print("/");
  Serial.print(month, DEC);
  Serial.print("/20");
  Serial.print(year, DEC);
  Serial.print(" - ");
  Serial.print(hour, DEC);
  Serial.print(":");
  if (minute < 10)
  {
    Serial.print("0");
  }
  Serial.print(minute, DEC);
  Serial.print(":");
  if (second < 10)
  {
    Serial.print("0");
  }
  Serial.println(second, DEC);
  delay(1000);
}

RTC datasheet

so, which one works? A2 or 51?

the two are actually the same address .... A2 is an 8 bit number .... 51 is a 7 bit number ... bit 0 is used to specify read or write .... write down A2 as a binary number ... you'll see that 51 is the top 7 bits

Normal I2C addresses are 7-bit long. On the first frame of an I2C
transaction, the master sends an 8-bit byte containing the address of
the slave followed by a bit specifying whether this is a read or a write
operation. Some people tend to call “address” the whole 8-bit frame,
which causes confusion. Because of this, we end up having three flavors
of I2C addresses:

the 7-bit address, which is the real device address
the 8-bit “write address”, which is the address followed by a 0
meaning “write operation”
the 8-bit “read address”, which is the address followed by a 1
meaning “read operation”

For your RTC, the 3 addresses are the following, in hex and binary:
7-bit = 0x51 = 0b1010001
write = 0xA2 = 0b10100010
read  = 0xA3 = 0b10100011

The Arduino Wire library expects the 7-bit address.


text:
Adding L293D motor shield to Breadboard
Anyone knows how to attach the l293D motor driver shield on a breadboard?
I need to put the shield on top of a breadboard and then use an Atmega328P as the main way of controlling it.
Than you :)

If the shield doesn't fit on the breadboard you need to use female to male jumper cables to connect it.

why do you want to do this? ... plug the shield onto the arduino instead

you can't put uno shield on breadboard

Acknowledging that it is not exactly the answer to your question, the folks at Adafruit have written an excellent tutorial on breadboarding the raw L293D chip. Which may be a more compact option for you?
Your question asks how to attach an L293D shield to a breadboard, and as @Juraj said in the comments, you can't do this easily directly. As @Jsotola mentioned, a UNO format shield is designed to connect directly to a uno, not to breadboard.
On a UNO format shield the pin alignment on the 18 pin (10+8) header sider of the shield (the digital pins) is not a comfortable fit into breadboard hole spacing (the shorter 14 pin side does align OK with breadboard). To make matters worse a UNO shield is wider than the available rows on a single standard breadboard. However, if you're willing to use more force and bend a few pins on the shield (not recommended) you can make this work using two breadboards side by side. The photo shows one possibility.

A better solution as mentioned by @ChrisL in the comments might be to use dupont connectors to connect the shield pins as needed (e.g. to a non-UNO format arduino).

There are different versions and clones of the L293D shield in circulation. I think most of these are based on the (now obsolete) Adafruit open source version 1. In any case you'll need to refer to the datasheet for the version you're using and be sure to connect every pin required from the shield to the arduino using the dupont connectors.
There are plenty of tutorials available regarding using the L293D shield, one example is at Last Minute Engineers


text:
Store files in AT45DB161D SPI chip to use them from arduino
I am new to this concept but I am wondering if it is possible to store some files on the AT45DB161D dataflash chip. these files must be read by Arduino. I know that I should use a file system and I saw the FatFs library but I don't have any idea how to do that with my Arduino nano.
is it possible to format the chip with Arduino and store files on it?
thank you in advance for your help and sorry about the obvious mistakes.

It's just a flash chip. Sure, you could run some form of filesystem on it, but that's rarely done in a small MCU environment. Just treat it like a block of memory (EEPROM) and store things at specific addresses. What kind of data do you want to store, anyway?

.text , .css , .html files
like the SPIFFS on esp32
how can I store these types of files at specific addresses?
can you explain a bit more.

There's many ways you could do it. For that sort of data a filesystem would be a simpler interface, sure. I assume you're wanting to run a web server on the Nano?

I am gonna do it on mega. but currently, I don't have access to one.
sorry, but can you provide me with some examples or documentations to implement the file system format?

You would probably take the FatFS library and write a "driver" for your flash chip. The FatFS system is modular and allows you to add drivers for new devices reasonably simply (well, simply for an experienced embedded programmer).


text:
In which package file is a default programmer selected?
After a clean IDE install, the programmer submenu already has a default option selected as shown below:

I am working on creating a core package and would like a default programmer to be selected after choosing a board, though I'm not sure which file sets the default. For example, here is a different 3rd party package that does not select a default programmer when a board is chosen.

The default preferences.txt file in IDE installation has this setting. It is not read from the boards package configuration files.
The programmer key in preferences.txt contains the last selected programmer. The default preferences.txt in lib folder in IDE installation  has programmer = arduino:avrispmkii. It is used if preferences.txt in Arduino15 folder doesn't exist or doesn't have the specific key.
With the recent change in Arduino IDE only programmers from boards package of the selected board are displayed, so it happens that no programmer is selected.


text:
Analog UV sensor displaying incorrect values in serial monitor (GUVA-S12SD)
Using Arduino Uno and a GUVA-S12SD sensor (https://www.adafruit.com/product/1918).
Here's my circuit. 5V into sensor+, GND into sensor-, A0 to sensor out.

Here's my code:
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  float sensorVoltage;
  float sensorValue;
  float uvIndex;

  sensorValue = analogRead(A0);
  Serial.print("Analog out: ");
  Serial.println(sensorValue);

  // 5 because 5V
  sensorVoltage = sensorValue * (5.0 / 1023.0);
  Serial.print("Output voltage: ");
  Serial.println(sensorVoltage);

  uvIndex = sensorVoltage / 0.1;
  Serial.print("UV Index: ");
  Serial.println(uvIndex);

  Serial.println();

  delay(1000);
}

Here's a sample from the serial monitor. The values stay about the same regardless of where I am in my house (in a sunny room, in the dark bathroom, etc.).
Analog out: 853.00
Output voltage: 4.17
UV Index: 41.69

Analog out: 853.00
Output voltage: 4.17
UV Index: 41.69

Analog out: 853.00
Output voltage: 4.17
UV Index: 41.69

Analog out: 853.00
Output voltage: 4.17
UV Index: 41.69

Output voltage is supposed to be very low. The UV index maxes out at around 11 - so 41 is too high. I checked what it is in my city right now, and it's 3. So this is super wrong. I don't have a multimeter to test with right now.
Any ideas about what could be going on? Did I order a bad sensor?

"regardless of where I am in my house" -  window glass blocks UV radiation almost completely (just FYI), so don't expect to get a reading inside ifyour house.

looks like the sensor module pins are not soldered

@SimSon I just tested outside and am getting the same readings

@jsotola Do they need to be soldered? I was hoping to be pretty modular with this experiment

@Dan the pins should be soldered to the module ... i am talking about the three pins visible in the three gold rings next to - Out +

@jsotola Ah I don't have any soldering equipment. I might be able to get some soon though. Is there any way to test this in the meantime or is soldering sort of the first step?

take the red jumper and insert it from the back of the board through the + hole ... insert the other two jumpers into the other two holes ... tie the three jumpers to the back of the board using the mounting hole next to the adafruit logo ... use a cable tie, or twist tie, or string, or rubber band ... pull on the jumper wire so that the ends are at an angle in the holes and are pressed tight against the side og the holes .... hopefuly that will work

@jsotola I managed to get the thing soldered but I'm getting the same high readings. Safe to say that the sensor is bad I guess?

analogRead returns an integer ... try defining sensorValue as integer


text:
ESP8266 ESP-12E: SD2 (GPIO 9) causing reboot when pulled low
I'm working on a project with reed switches, which are connected between a GPIO pin (in pullup mode) and ground. With some of my NodeMCU ESP-12E boards (HiLetGo brand) that I ordered, whenever the reed switch on GPIO9/SD2 is closed, the board is rebooting. However, some of these same boards do not exhibit this same behavior - the reed switch on this pin works correctly.
The reset reason is Fatal exception:4 flag:1 (WDT)
Is there any reason that some boards would work while others don't? Is this pin generally safe to use as an IO pin? I need at least 8 GPIO pins to work per board, and I'm having a hard time finding enough of them.
Here's my code, for reference
int REED_PIN = 9;
void setup() {
  Serial.begin(9600);
  Serial.println("Setup");

  pinMode(REED_PIN, INPUT_PULLUP);
  Serial.println(ESP.getResetInfo());
}

// the loop function runs over and over again forever
void loop() {
  int proximity = digitalRead(REED_PIN);
  if (proximity == LOW) {
    Serial.println("Magnet detected");
  }
}

GPIO9 is connected to the flash memory chip on the NodeMCU. It should not be used as a general I/O. You can find out more about what NodeMCU pins you can use and for what purposes, on this page

use pin 10 instead and set the flash to DIO to free it up.


text:
Not able to build program with arduino program under clion
I'm pretty new to arduino and I just downloaded clion and installed the arduino plugin so I have an IDE that I'm used to. Here is my code:
#include <Arduino.h>

// Time between a switch indicating not full and the time a valve is opened
#define SWITCH_DELAY 5000

#define PIN_SWITCH 2
#define PIN_GREEN 3
#define PIN_YELLOW 4

#define INT16 int
#define UINT16 unsigned int
#define UINT32 unsigned long

DelayChecker    degassingChecker(PIN_SWITCH, PIN_GREEN);

void setup() {
    pinMode(PIN_SWITCH, INPUT);
    pinMode(PIN_GREEN, OUTPUT);
    pinMode(PIN_YELLOW, OUTPUT);

    Serial.begin(9600);
    Serial.print("UINT16: " + sizeof(UINT16));
    Serial.print("UINT32: " + sizeof(UINT32));
}

void loop() {
    UINT32 now = millis();

    degassingChecker.check(now);
}

public class DelayChecker {
    private:
        UINT32 delayExpires = 0;
        UINT16 switchId = 0;
        UINT16 solenoidId = 0;
        bool solenoidOn = false;

    public:
        DelayChecker(const unsigned int sw, const unsigned int sol) {
            switchId = sw;
            solenoidId = sol;
        }

        void check(const UINT32 now) {
            if (delayExpires == 0) {
                INT16 switchState = digitalRead(switchId);
                if (switchState == LOW) {
                    delayExpires = millis() + SWITCH_DELAY;
                    digitalWrite(PIN_YELLOW, HIGH);
                }
            }
            else {
                if (now >= delayExpires) {
                    INT16 switchState = digitalRead(switchId);
                    if (switchState == LOW) {
                        if (!solenoidOn) {
                            digitalWrite(solenoidId, HIGH);
                            solenoidOn = true;
                        }
                    }
                    else {
                        if (solenoidOn) {
                            digitalWrite(solenoidId, LOW);
                            solenoidOn = false;
                        }
                    }
                }
            }
        }
};

I hit the run button and get the following.
====================[ Build | untitled1 | Debug ]===============================
/opt/clion/bin/cmake/linux/bin/cmake --build /home/thomas/CLionProjects/untitled1/cmake-build-debug --target untitled1 -- -j 12
[  7%] Building C object CMakeFiles/uno_CORE.dir/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/wiring_pulse.c.obj
[  7%] Building CXX object CMakeFiles/uno_CORE.dir/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/new.cpp.obj
[ 10%] Building C object CMakeFiles/uno_CORE.dir/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/wiring_shift.c.obj
/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/new.cpp:29:46: error: expected initializer before 'noexcept'
 void * operator new(size_t size, void * ptr) noexcept {
                                              ^~~~~~~~
gmake[3]: *** [CMakeFiles/uno_CORE.dir/build.make:317: CMakeFiles/uno_CORE.dir/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/new.cpp.obj] Error 1
gmake[3]: *** Waiting for unfinished jobs....
gmake[2]: *** [CMakeFiles/Makefile2:99: CMakeFiles/uno_CORE.dir/all] Error 2
gmake[1]: *** [CMakeFiles/Makefile2:133: CMakeFiles/untitled1.dir/rule] Error 2
gmake: *** [Makefile:151: untitled1] Error 2

It looks like an error in the libraries. Has anyone seen anything like this?

Could be some incorrect build settings by that plugin.

I found a github issue fixing this error : https://github.com/vsch/CLionArduinoPlugin/issues/36
It worked for me

You're referring to setting the Clion project settings to use language standard to c++17?

Yeah I'm sorry... First time for me ^^ thanks for explaining to me


text:
Arduino IDE not seeing Arduino library
Working on my first real Arduino project.
I opened my code in the Arduino IDE and hit build and I get errors "not declared in the scope" on every single call to the Arduino library. For instance, digitalWrite, digitalRead, INPUT, OUTPUT, etc.
I open other projects with my Arduino IDE and they build fine, so it's clearly the code in this project. I've restarted. No change.
Ideas?

If it's "clearly" the code in the project them maybe it would be a good idea to show us that code?

Still not sure what the problem was, but I included Arduino.h and everything worked. This is a hack, but an effective one. If someone else knows what I did wrong, let me know.

It would have been better to develop the question into something where the answer followed from it.  Given your answer, it seems likely that you were not using an .ino (or .pde) extension.  Something that would have revealed itself if you'd put verbose output from the compilation stage.  You should do that in future questions, along with the code, etc.

No, was using an ino. The only posting of code would have been my entire project, which is not small. Since the code belongs to my client, I have concerns about doing that. I would love help, but the price is a bit high in this case and I'll have to settle for a hack workaround.

I'm not going to down-vote this, but for me, what you're describing as an answer would have to be demonstrated to be believed.  If you have an .ino file but the code you're actually talking about is in a non-.ino file, e.g. header, then the answer makes sense, but this fact should be mentioned somewhere.  The Arduino build process does add this #include to your .ino files, originally called WProgram.h since Wiring, before "Arduino" even existed.


text:
Why does "Get Board Info" not work, but I can still program my Arduino Nano?
Dear Stack Exchangers,
I have been working with Arduinos for probably 10 years, and as a habit the first thing I do when I connect a device to the USB port is run the "Tools > Get Board Info" in the Arduino IDE just to make sure I've got the correct port selected, USB cable is good, etc.
Well tonight when I connected a Nano, the "Get Board Info" didn't work at all. So after spending hours rebooting, trying different cables, etc. I eventually just tried uploading a sketch, and that worked fine! But the "Get Board Info" still does not work.
Anybody have any ideas what is going on? Thanks!
Sincerely,
Ramblin' Wreck

By "Nano" you're referring to the ATMega328P based original Nano? Or one of a pile of other board's with that in the name? When it "doesn't work" what does it do instead? Which IDE version?

It has "NANO" printed on the board. Today though, the "Get Board Info" command works fine and I receive the following message:
BN: Unknown board
VID: 1A86
PID: 7523
SN: Upload any sketch to obtain it

I am using Arduino 1.8.13 on a Dell laptop with Windows 10.

To be clear, you were not getting that message before? If so, what were you getting? The content of the message in you are currently getting is in line with Juraj's answer.

Timemage, correct, I was NOT getting that message before. No message window popped up at all. I notice that today the Nano is on COM7 (used Device Manager to determine this), and last night it was on COM5. So perhaps that has something to do with it.

Odd. You should have received one of these messages instead of nothing at all.

The classic Arduino Nano uses an FTDI chip as USB to TTL Serial adapter. Many Nano (and Uno and Mega) clones use the CH340 as USB adapter. These USB chips present themselves with id set by the USB chip manufacturer. This doesn't provide a way to identify the specific board.
Original Uno and Mega Rev 3 and some clones use ATmega16u2 as USB adapter with a firmware by Arduino. Arduino sets the USB id in the firmware so it can identify as specific board type. (People reported Mega clones which presented itself as Uno).
The boards with MCU with native USB like Leonardo, Micro and ARM boards (Zero, MKR, Nano IoT, Nano BLE) provide the USB id set in boards.txt so they can be identified too.


text:
Can i use SCL, SDA pin for I2C
I read this article. In the article, it uses A4 and A5 for I2C. But can I just use SCL and SDA pin directly in the Arduino UNO R3? And do I need a put-up resistor for SCL and SDA pin?

Pins A4/A5 and the SCL/SDA pins are the exact same pins on the Arduino UNO R3. Not just "they perform the same function", but they are physically the same pins. It is one solid piece of metal from one pin to the other.
You don't need pullup resistors on the I2C pins because the Wire library turns on the internal pullups by default. However those internal pullups are about a tenth of the strength that I2C pullups should be, so I would recommend that you do add pullups, certainly for anything more than a couple of inches of wire.


text:
I2C HMC5983 communication issue
I have a really weird problem, when I run the exmple wire (I2C) scanner from Arduino, I get:
I2C Scanner
Scanning...
I2C device found at address 0x1E  !
done
However when I try directly to the 0x1E I get the following error code 2:
received NACK on transmit of address.
Below is my code that i did only modify the example code:
#include <Wire.h>

void setup() {
  Wire.begin();

  Serial.begin(9600);
  while (!Serial); // Leonardo: wait for Serial Monitor
  Serial.println("\nI2C Scanner");
}

void loop() {

  Serial.println("Scanning...");

  byte address = 0x1E;

  Wire.beginTransmission(address);
  byte error = Wire.endTransmission();

  if (error == 0) {
    Serial.print("I2C device found at address 0x1E");
  } else if (error == 1) {
      Serial.print("data too long to fit in transmit buffer.");
  }
  else if (error == 2) {
      Serial.print("received NACK on transmit of address.");
  }
  else if (error == 3) {
      Serial.print("received NACK on transmit of data.");
  }
  else if (error == 4) {
      Serial.print("Unknown error at address 0x");
  }

  delay(5000); // Wait 5 seconds for next scan
}

please add a clear, answerable question to your post

It is very clear that I am asking what is wrong ? please do not comment just to comment.

not everyone would ask the same question ... this is a Q&A site, so a clear question is required

What is your pull-up resistor's value? NACK on Addressing could happened if you have weak pull-up, or if the device is busy.

There are certain situations where the device can send a nack after a valid address is sent - search "received NACK on transmit of address". Nothing I read applies specifically to your situation.
I see nothing in the HMC5983 datasheet (https://www.farnell.com/datasheets/1509871.pdf?_ga=2.219060057.1318745487.1555987311-293789508.1555987311) that could account for what you are seeing.
I don't have an HMC5983 on a GY282 module (you mentioned the module in a different forum) as you do, but I have it's predecessor, HMC5883 which I think is largely comparable, but slower.
I tested your code and I DID NOT get the NACK error - it simply reported finding the the device.
Then, I tested the leanest HMC5883 code I could find and I saw systematic output, which changed as I moved the device.
Then I tested similar code for the HMC5983 (see https://wiki.eprolabs.com/index.php?title=GY-282_HMC5983_Module#Hardware_Connections). That code worked on my slower HMC5883 board (e.g., systematic output).
I suggest the following - double check the solder blobs on the board to make sure I2C/SPI is jumpered properly - also the 3v3 CS blobs - a picture would be helpful.
I would also suggest that you try to run the HMC5983 code that I linked and see what you get.
Hope it helps.


text:
CO2 pressure regulator for keg
Is there anything like the link below that I can read/set with an arduino/raspberry pi?
I'd like to be able to control this completely from a computer in my kegerator setup.
Any search terms that might help me find something would be useful too.
Thanks
http://www.amazon.com/Taprite-Product-Pressure-Kegerator-Regulator/dp/B0060NOX40/ref=lh_ni_t?ie=UTF8&psc=1&smid=AEUC6GAA8XY7Y

A good search term is pressure transducer.

I also need to be able to adjust the delivery pressure to the kegs though - not just measure the pressure

If it's to be cheaper, I'd be surprised if you ended up with something that costs less than some mechanical stuff. If it's for automation, you're going to have a struggle finding a pneumatic regulator that works with Arduino... you might have to use a motor to turn a dial...

For adjusting pressure, search for a solenoid valve. Just make sure that whatever you get is food grade and can handle enough gas pressure (same goes for the transducer).


text:
CH340: right endpoint?
I'm working on implementing CH340 drivers used by cheap Arduino clones on Android (Linux). What endpoints should be used as read endpoint since two endpoints have IN flag - 0x81 and 0x82?
http://usbdriverwriting.blogspot.ru/2012/10/connection-status-device-connected.html
Is there any developer documentation except some old c #1 (http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/drivers/usb/serial/ch341.c?v=2.6.25.8) and some linux driver #2 (http://0xcf.com/?wpdmdl=124)

Try looking at the (normal) Linux drivers source code.  Of course, you could always try one and see - if it doesn't work, try the other instead.

can you send me the link for normal Linux driver sources for CH340 chip?

none if them is working because of another reasons so i can't detect which one is correct. i need just to know which one is right

Plug it into a linux machine and use lsusb -v -d <vid:pid> to find which endpoint is the bulk one?  You can probably do something similar on Windows but I don't have a clue how.

according to the link above (http://usbdriverwriting.blogspot.ru/2012/10/connection-status-device-connected.html) 0x82 is bulk endpoint and 0x81 is not

So it should be 0x82 then I would guess.  The other one is probably for sending configuration or control line messages.

thanks for help, Majenko. If someone has any documentation on this please share it

The trouble with cheap Chinese chips is that you get cheap Chinese datasheets. "You gets what you pays for" as they say.


text:
How is interaction with CDC device with no interface endpoints working?
I'm working on uploading to Digispark board. It uses micronucleus bootloader and i can see uploader code. I've modified it a bit to see interfaces and endpoints count:
    nucleus->device = usb_open(dev);

    // added by me - start
    int interfaces, endpoints, j;
    struct usb_interface_descriptor *interface = NULL;

    interfaces = dev->config->bNumInterfaces;
    fprintf(stderr, "Found interfaces: %i\n", interfaces);

    interface = &(dev->config->interface[0].altsetting[0]);
    fprintf(stderr, "Endpoints: %i\n", interface->bNumEndpoints);
    // added by me - end

    // get nucleus info
    unsigned char buffer[4];
    int res = usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT);

I wonder how it's working because interface #0 has no endpoints:
$./micronucleus --type intel-hex /tmp/Start.ino.hex
> Please plug in the device ...
> Press CTRL+C to terminate the program.
Found interfaces: 1
Endpoints: 0
> Device is found!
connecting: 40% complete
> Device has firmware version 1.6
> Available space for user applications: 6012 bytes
> Suggested sleep time between sending pages: 8ms
> Whole page count: 94  page size: 64
> Erase function sleep duration: 752ms
parsing: 60% complete
> Erasing the memory ...
erasing: 80% complete
> Starting to upload ...
writing: 100% complete
>> Micronucleus done. Thank you!

Usually i expect interface to have 2 endpoints (in & out from usb.h):
#define USB_ENDPOINT_IN         0x80
#define USB_ENDPOINT_OUT        0x00

Can anyone explain me how usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT); is working without endpoint?

Micronucleus uses control transfers to upload code (it's not a CDC device). You don't need an endpoint for control transfers - they use the implicit endpoint 0 that is always present whether you define one or not.
You only need to define endpoints for interfaces that want to communicate using bulk, interrupt or isochronous transfers.
Bus 003 Device 073: ID 16d0:0753 MCS Digistump DigiSpark
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               1.10
  bDeviceClass          255 Vendor Specific Class
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0         8
  idVendor           0x16d0 MCS
  idProduct          0x0753 Digistump DigiSpark
  bcdDevice            1.02
  iManufacturer           0
  iProduct                0
  iSerial                 0
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           18
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              100mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass         0 (Defined at Interface level)
      bInterfaceSubClass      0
      bInterfaceProtocol      0
      iInterface              0
Device Status:     0x18c0
  (Bus Powered)
  Debug Mode


text:
How to reset Arduino with ESP shield?
I'm working on the wifi uploading to Arduino over ESP shield (eg. ESP-12). When uploading over USB Arduino IDE resets the boards first (using DTR) and then interacts with the bootloader. How can i control ESP's GPIOs to reset Arduino board with ESP?

Have you considered using Esp-Link ( https://github.com/jeelabs/esp-link ) on your ESP-12? It comes with the "reset" function, built-in (I had succesfully used it).

Which firmware do you have installed on the shield? If you're using the AT firmware then please post the results of AT+GMR.

You may probably send something from ESP to Arduino (through serial), that the Arduino will process and issue a software reset by itself?

@SMFSW - a commanded reset only works if whatever is currently loaded is both non-broken and intended to recognize that command.

@Chris you're totally right, i put aside the part that arduino is reflashed at this point. Two options then, find out more about the communication of the arduino core software, there may be some builtin commands. Other option with a gpio would be to bypass the reset button of the arduino board with that output from ESP (driven logic low on avr microntroller reset pin).

There are no "built in commands" of the "arduino core software" and in fact that anything is able to run at all depends entirely on the "sketch" loaded.


text:
How to power Arduino only when light is on
I want Arduino to conserve energy and turn it on automatically only when the lights is on. Can I use some kind of light sensor and put it in between power supply and arduino somehow? Ideally light sensor will power from the same power source, if possible.
I'm not an electrical engineer - just enthusiast, so please explain your idea as detailed as possible. Many thanks!

I'm quite sure there are indeed purely-electrical schematics for this. Though you could always use powersave functions on arduino?
You probably want a light sensor, with a comparator and something like a relais. Sure there are no sources for this on the internet? I don't know that much of electronics either.

Beware that Arduino boards can be very power-inefficient. You may want to use a barebones configuration, maybe just an ATmega chip alone. Then you can save significant power by just calling sleep_mode(), and save even more with power_*_disable().

For a chip like the basic Arduino's ATmega, you don't really "turn it off" to save power, rather you put it into a low-power sleep mode.
First, make sure you aren't consuming more power than needed normally.  Make sure unused peripherals like the ADC are off.  If your program spends most of its time waiting for external events, try reducing the clock speed either with a slower crystal or the 8 MHz oscillator, and with the clock prescale register.
Next, implement a sleep cycle.  Turn off everything you can, and program a hardware timer to generate an interrupt at some point in the future.  Enter sleep mode, so the processor stops and only the logic in the counter is still running.  When the interrupt fires, the ATmega CPU will wake up and continue operating, at which point you enable the ADC, use a GPIO to drive your light sensor, and take a reading from it.  If it doesn't meet your conditions, turn it all off again and go back to sleep until it's worth checking again.
In low power design you must be very careful of things outside the processor stealing power.  Watch out for any resistors pulling signals, if the signals are actively drive against the resistor.  LEDs are an obvious issue.  Also watch out for voltage regulators which may have high quiescent current.  And finally beware of peripheral chips - a stock Arduino has an entire second processor sitting there in the USB-serial adapter wasting power.  So you will either need to customize the firmware of that to shut down too, or else use a simpler board that doesn't have one (don't just hold it in hardware reset, as the reset pin has an internal pullup which will then consume power).

Conserve energy?
There are many ways to conserve energy in an Arduino(e.g. Use a USB adapter that does not waste energy as heat, instead of using Battery power)
But if you want to save energy by only switching on the Arduino when light is on, it depends on the intensity of the light.
If it is supposed to switch on only during the day, use Solar Panels to power the Arduino.
Else, use an LDR.

If it's OK for it go off (not just to sleep) when the light is off, power it from the lighting circuit. These two parts will do it without messing with the electrics:

The light socket adapter with two outlets is a hardware-store part, probably about USD$3, and the USB charger makes a compact and useful Arduino 5v power supply, USD$6 at Amazon right now. (Apple's little USB power cube might fit better but is more expensive). I use the Nokias for Arduino power supplies and their no-load voltage is just barely over 5v. If you substitute a different one, that would be a worthwhile test to make before you connect it to your Arduino.

You may keep your Arduino powered, but have it sleep when the lights are
off. During sleep, it would periodically awake to check the light level:
if it's low enough, it goes back to sleep, otherwise it resumes its
work. Here are the detailed steps:

Try to find a power-efficient Arduino or clone (no ON LED, no USB
bridge...) or learn how to build and program a barebones one. If you
can live with a 8 MHz clock, a bare ATmega, or even ATtiny, may
be a good option.
Get an LDR (light-dependent resistor) and an ohmmeter.
Measure the resistance of the LDR at the relevant light levels, and
decide for a value of resistance that will serve as a threshold for
switching on and off. I will call this LDR_THRESHOLD_RES in the
code.
Get a plain resistor with a value close to the previous threshold
(within a factor 10 should be OK), but not lower than 1 kΩ.
This will be your "pullup" resistor, and its resistance will be
LDR_PULLUP_RES.
Decide how often the program will check for the lights being turned
on. This delay, in milliseconds, will be LDR_CHECK_DELAY.
Assign both a digital and an analog pin for measuring the LDR. These
will be LDR_DRIVE_PIN and LDR_SENSE_PIN respectively.
Connect the LDR between LDR_SENSE_PIN and ground; connect the
pullup resistor between LDR_SENSE_PIN and LDR_DRIVE_PIN.
Update the code below (the first 5 #defines) and include it in your
sketch.
Add pinMode(LDR_DRIVE_PIN, OUTPUT); to your setup().
Call wait_for_lights() inside loop(), wherever you want your
program to pause if the lights are off.

#include <avr/sleep.h>

#define LDR_THRESHOLD_RES 25e3  // 25 kOhm
#define LDR_PULLUP_RES    10e3  // 10 kOhm
#define LDR_CHECK_DELAY    200  // 200 ms
#define LDR_DRIVE_PIN        2  // digital 2
#define LDR_SENSE_PIN        0  // analog 0

#define LDR_THRESHOLD_RATIO (1.0*LDR_PULLUP_RES/LDR_THRESHOLD_RES)
#define LDR_THRESHOLD_READING ((int)(1024 / (1 + LDR_THRESHOLD_RATIO)))

/* Sleep until the light is on. */
void wait_for_lights() {
    for (;;) {
        // Sense light level.
        digitalWrite(LDR_DRIVE_PIN, HIGH);
        int reading = analogRead(LDR_SENSE_PIN);
        digitalWrite(LDR_DRIVE_PIN, LOW);

        // Low reading means the light is on.
        if (reading < LDR_THRESHOLD_READING) return;

        // Wait for a few milliseconds.
        unsigned long start = millis();
        do sleep_mode();
        while (millis() - start < LDR_CHECK_DELAY);
    }
}

This should already get your power consumption pretty low. If you want
to save further power, you will likely have to dig into your
microcontroller's datasheet. You can try the various power_*_disable()
functions and turn off all the peripherals you do not need. You can also
try a deeper sleep mode than the default one (IDLE), but then your
millis() clock will freeze during sleep, and you will have to set up
some wake up source if you do not want to sleep forever. The watchdog
timer is a good option.


text:
Questions Concerning Arduino Compatible Boards
I've seen an Arduino-compatible board called Bluno from DFRobot. I'm curious if a shield, specifically the DFRobot motor shield can be connected to the Bluno.
Can anyone confirm if it can be connected with a shield?

The Bluno is identical to the Uno, except the USB-to-serial chip, also supports BT. So it won't be a problem.


text:
SoftSerial freezes on comparing getInt to int
I have a robot application on my Arduino which basically takes values from a SoftSerial instance on my 0/1 pins (connected to a Bluetooth board).
From the 'driver station' I send speed values to the Arduino through the aforementioned Bluetooth controller. The freezing happens when I compare the data (an integer) to a local integer (i.e 500). If I send the reverse command, I'm actually sending the int 500. If I compare my SoftSerial data like so:
if(softSerial.parseInt() == 500)
{
 //Reverse
}else{
 //Forward
}

it freezes. It only happens when I'm using my SoftSerial stack over Bluetooth, over USB it doesn't freeze. What are my options?

Why are you using software serial on pins 0 and 1? Why not hardware serial?

@PeterR.Bloomfield would I have any issues uploading programs to my Arduino if I do?

freezes permanently or freezes for one second? does the BT message have a whitespace character after the 500?

@BrettAM freezes permanently. It doesn't, so maybe I should do a contains method?

@KeatonBurleson What you do with pins 0 and 1 when the program is running won't affect upload. The only potential issue is having something else physically connected to those pins while the upload is happening. It depends on the specific hardware though.

Have you tried looking at the raw data coming over as opposed to trying parseInt()? Also I wonder if something w/ the Bluetooth controller is interfering with SoftSerial, but I don't know the specifics of what you are using. Are you just connecting 2 wires from the controller to the Arduino and that's that?

@sdcharle no I haven't. I shall soon enough. Its two wires, to TX/RX/

There is no point in using SoftwareSerial on pins 0 and 1, as you have HardwareSerial for that. Whatever the sketch does once it starts will not affect whether or not it uploads. If you have something connected to pins 0 and 1, during the upload, that may well stop the upload working, but what the sketch does afterwards does not.
It is hard to tell from your snippet, but if you also have activated HardwareSerial - eg. Serial.begin(9600); - then the hardware takes over those two pins and SoftwareSerial won't work anyway.


text:
Weight sensor / load cell not working
I just got all my parts together that I needed for my project and put everything together like said here: https://web.archive.org/web/20140303140445/http://cerulean.dk/words/?page_id=42 but the serial monitor gives me all random outputs:
analogValue: 865.52
             load: 43.27584
analogValue: 865.54
             load: 43.27717
analogValue: 865.50
             load: 43.27517
analogValue: 865.43
             load: 43.27151
analogValue: 865.32
             load: 43.26601
analogValue: 865.45
             load: 43.27255
analogValue: 865.45
             load: 43.27241

So I can't calibrate everything to even continue, what is wrong? I checked all my connections like 50 times and everything is wired up like shown in the tutorial.
Here are my parts:

INA125P:
http://www.reichelt.de/INA-125-PA/3/index.html?&ACTION=3&LA=446&ARTICLE=147252&artnr=INA+125+PA&SEARCH=ina125p
Load cell from a simple 5kg kitchen scale (tested it before removing
and it worked)
10 Ohm resistor

Thank you in advanced, Greetings

Doesn't look random to me. Pretty consistent. Did you calibrate, and update the values for analogvalA and analogvalB?

It always returns something around 866 - so I can't really set those values.

Does the value change if you place some weight on it?

Sometimes - but most of the time not, it stays at like 866.

I solved it by replacing the resistor with a potentiometer.

You might be driving the amplifier to its limits, and getting a value at its limits.
The INA125 isn't a rail-to-rail amplifier, so if you are wiring it up to ground and +5V as described, its output is limited to be between 0+1V=+1V and 5V-1.7V=+3.3V, so it would be easy to saturate it and bump up against those limits and give you a constant value.
If you are using the 10ohm resistor as the INA125 gain, the gain G=4+60000/10=6004x so the input voltage difference needs to be between 0.00016V and 0.00055V volts to be unsaturated within its output linear range.  If it is outside of those limits, the amplifier will act as a comparator.
You could check this by putting a voltmeter on the output of the amp and measuring what is is and if it changes.  If it isn't near 2.5V when the scale is unloaded and is saturated at the limit of the amp, then you might need to balance the loadcell closer to zero so it doesn't peg the scale, or reduce the amplification.


text:
nRF24L01+ RF24 library - can send but can't receive
I'm prototyping out a board with temperature, humidity, windspeed sensors, and using an NRF2401+ board to send values to a Raspberry Pi base station that will record the data.
Using a Leonardo clone board, I'm able to successfully run the pingair_dyn sketch to send test payloads to the RPi and receive acks.  (So I know the RPi can send and recieve OK.)
Moving the same NRF2401+ to a breadboard setup with an ATMEGA328P-PU, the same sketch can send payloads which are received on the RPi, but always hits the timeout trying to get the ack (which the RPi is dutifully sending).
In fact when running pingair_dyn as a receiver, it just spins in the loop waiting for radio.available() to return true, which it never does.
The immediate problem is that radio.available() is always returning false.  So basically I can send but can't receive.
I have checked my wiring several times, and I'm mostly confident that it's right.

CE - physical pin 14 (arduino digital pin 8 )
CSN - physical pin 13 (arduino digital pin 7)
SCK - physical pin 19, per atmega328 datasheet
MOSI - physical pin 17, per datasheet
MISO - physical pin 18, per datasheet

In the software, I construct the RF24 instance:

RF24 radio(8,7);

Any ideas?  I tried swapping CE <--> CSN, then nothing worked.  Is there some wiring problem that would cause XMIT to work but RECV to fail?
I've tried putting a 2.2 uF capacitor across the 3.3V - GND as I've seen mentioned in other threads, but no difference.
Any suggestions on what is useful information to dig out of the RF24 library to give some idea of what's going on?
More background
Here is the RF24 debug info from the mega328
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1    = 0xf0f0f0f0d2 0xf0f0f0f0e1
RX_ADDR_P2-5    = 0xc3 0xc4 0xc5 0xc6
TX_ADDR       = 0xf0f0f0f0d2
RX_PW_P0-6    = 0x20 0x20 0x00 0x00 0x00 0x00
EN_AA       = 0x3f
EN_RXADDR    = 0x02
RF_CH      = 0x4c
RF_SETUP    = 0x07
CONFIG       = 0x0f
DYNPD/FEATURE    = 0x3f 0x04
Data Rate    = 1 MBPS
Model       = nRF24L01+
CRC Length    = 16 bits
PA Power    = PA_MAX

Here is the debug info from the base station (Raspberry Pi):
pyRF24/examples/pingpair_dyn/
================ SPI Configuration ================
CSN Pin          = CE0 (PI Hardware Driven)
CE Pin           = Custom GPIO22
Clock Speed      = 8 Mhz
================ NRF Configuration ================
STATUS           = 0x0e RX_DR=0 TX_DS=0
MAX_RT=0 RX_P_NO=7     TX_FULL=0         RX_ADDR_P0-1     =
0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR          = 0xe7e7e7e7e7
RX_PW_P0-6       = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA            = 0x3f
EN_RXADDR        = 0x03
RF_CH            = 0x4c
RF_SETUP         = 0x07
CONFIG           = 0x0e
DYNPD/FEATURE    = 0x3f 0x04
Data Rate        = 1MBPS
Model            = nRF24L01+
CRC Length       = 16 bits
PA Power         = PA_MAX

FWIW, I had packet loss issues using these boards, until I introduced those 3.3 V piggy back boards to supply current. I use them on both RX and TX now, but experimentation showed that the RX was where it made the crucial difference. Omitting the filter cap also didn't make any difference.
I don't know why these 5 V to 3.3 V piggy back boards were so effective; they're just a regulator. Maybe they've got better quality specs, or their own on board filter caps have a better frequency range for driving the nRF.
They only cost about a $, and save so much agro.

The pins could be wrong for ATMega328.
It should be.
NRF24L01 - Arduino UNO
GND - GND
VCC - 3.3V
CE - 7
CSN - 8
SCK - 13
MOSI - 11
MISO - 12
or B. You need to connect a 500uF electrolytic capacitor to your NRF24L01+ VCC and GND pins directly. To reduce noise related issues. With clone arduinos/cheap regulators/clone NRFs then noise might start creating issues especially with receiving.

have a look at https://github.com/TMRh20 he's done some great work on the nrf24 radios and has code allowing connection between arduinos and pi's.
Oh and while i've played with non ip addressed data transfer a bit it wasn't the main focus of my research, but shouldn't the tx addresses be matched up?
also you mention a 2.2uf cap on the 3.3v line, but what is supplying the 3.3v line on the arduino side?
iirc the pi will supply enough current on its 3.3v line to supply the radio (i remember it working well enough) and i don't know what voltage your running the MEGA at, 3.3v or 5v with level shifters, either way i would imagine your power supply would be sufficient. Unless your running the mega at 16mhz and on a 3.3v (to be stable needs ~4.1v https://electronics.stackexchange.com/questions/58818/programming-3-3v-atmega328-running-at-16mhz)
Also iirc most nrf24's are happy enough with 5v logic level, although there are plenty of clones out there, you'll have to do your own testing.
And if you have one to hand would suggest starting off with a non breadboard arduino, get it to work before moving onto the breadboard... there is less that could go wrong :)

Answering questions in reverse order...
I mentioned that I was able to get a successful ping-and-response using an Arduino Leonardo before going to the breadboard.  So that was to establish that the nRF20L01+ hardware is in working order, and that the Pi setup was also working.
Currently running MEGA at 5V @8MHz, but supplying the radio a separate 3.3V feed off of an Arduino Uno that I have set up adjacent for use as the programmer ("Arduino as ISP").
As for TX addresses not matching, it didn't seem to matter with the Leonardo.  The Pi seems to have random value for RX_ADDR_P0.