text:
Formula for decision making when in contact with an obstacle using Arduino
I am currently working on an obstacle avoidance robot project and I have seen numerous algorithms for obstacle avoidance a very good example is this Obstacle avoidance algorithm [Editor's note: by user3880651],
but unfortunately non of those algorithm works with Arduino so upon my research I found this blog

and in there the author talks about an effective way to avoid obstacles and even has a formula he uses for avoiding obstacles at different positions e.g (Front and sides) but doesn't really explain how he got the formula so I was wondering if anyone as an effective formula or algorithm for obstacle avoidance that works with Arduino thanks for your help in advance

I'm not voting to close this because it is Arduino based, but I think you might get a better (but more generic) response on the robotics forum, but don't mention 'Arduino' otherwise it will get bounced back to here :)
Good luck

As there's the code given in the blog, you may try reverse engineer it to understand the principles?

The algorithm mentioned in the blog uses a Fuzzy Logic Controller to perform obstacle avoidance. You can read up more on fuzzy logic here: https://www.calvin.edu/~pribeiro/othrlnks/Fuzzy/home.htm

newMotorSPD_L = basicVelocity + urgMotor_L + (urgTurn_R/4) - (urgTurn_L/2) + 60;
  newMotorSPD_R = basicVelocity + urgMotor_R + (urgTurn_L/4) - (urgTurn_R/2) + 60;

Based on the code, the formula is basically made up of variables with different weight/ratio.
basicVelocity is the default moving velocity of the robot when there is no obstacle or wall detected.
urgMotor_L/urgMotor_R is the ouput of the controller for frontal object detection/avoidance by getting the difference between the left and right ultrasonic sensor.
(urgTurn_R/4) - (urgTurn_L/2) is probably the left/right bias?
+60 at the end is probably to offset the error of the motor. (Assuming all other variable are 0, the robot should be still at 60 for their case?)
To simplify what the formula does, it can be shown using this graph:

Obstacle avoidance doesn't really have any practical use unless it works alongside a goal finding algorithm.
Take a look here for a simple introduction (and a few modifications) to this excellent paper on goal finding with obstacle avoidance.
You can also experiment with the python code (add obstacles, change positions of goal and start points, and step through the decision process). Keep in mind that in this code, sensor inputs are also simulated and so the code is much more complex than that would actually need to be deployed on a robot with real world sensors.


text:
how to move my robot to the assigned coordinates
I am working on an ground surveillance robot using an Arduino mega for programming, am using components like the HMC5883L compass, Adafruit GPS for assigning of coordinates (latitude and longitude) which are the way points, I have written up the code for both the compass and the GPS and am able to get information from them, but now what I want for my robot to move to those specified coordinates (latitude and longitude waypoints) which I don't know how to do please do pardon me for asking such question cause I am new to coding GPS and compass and I would appreciate it if anyone could help me out or explain a bit in details what I need to do please find my code here http://textuploader.com/drqwv

Do you remember your high school trigonometry lessons?

@Majenko yes I do remember

Then you know where you are, and you know where you want to be. Between you is a right angle triangle. Calculate the angle of the hypotenuse turn to that angle, and drive to your destination.

yes I am aware of how to do that cause I have already done it in my code (Turning Calculation) what I need to know is how to write the code that to move the robot in-respect to the coordinates

You have code to turn left and right already. How far to turn I guess is the question. You have the angle you want, and you have a compass. There's multiple ways of working out how long to turn for. Experimentation may give you a specific time-per-degree, or you could turn some amount and see how far it actually turned then use that to calculate how long to turn for the rest of the turn. Then just drive straight until you're there.

You may find Robotics Stackexchange  useful for this question.  If so ask moderator to move it

Due to my robot I have been thinking about this problem quite a few times but I never got to coding.  So this is a purely my thinking no experience.
The problem is not only calculating where you are and where to go. The robot needs to move so it needs to know whether it needs to turn (left or right; slow or fast) to drive into the correct direction.
So basically you want a method that takes the compass direction the 2 gps locations and returns a speed and turn value.
The speed and turn value will be different for a waypoint and the final destination. I thought to do so by switching to the next waypoint before coming in the "slow down area". This should make that only one algorithm can handle both situations.
I think the algorithm is likely to look like this.
Given the 2 gps locations calculate the expected compass reading.
Given the 2 gps locations calculate the distance
Based on the distance and the difference between the expected and actual compass reading decide on the speed and turn.
As to the last step there is no "one size fits all" for instance a skid driven robot may opt to turn on the spot until it hits the expected compass reading.
If you have a slow turning robot and you are close to the waypoint you may opt to drive backwards first (like parking a car)
I hope this helps

source: Stack Exchange

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

sort: votes


text:
What bootloader does the Arduino Micro come with?
I've been looking to modify the Arduino Micro bootloader (specifically changing the VendorID and ProductID) of the Arduino. What bootloader comes pre-installed on the Arduino Micro? and how would I go about building and uploading a modified bootloader?

Try looking at https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/caterina/Descriptors.c
Inside that is:
/** Device descriptor structure. This descriptor, located in SRAM memory, describes the overall
 *  device characteristics, including the supported USB version, control endpoint size and the
 *  number of device configurations. The descriptor is read out by the USB host when the enumeration
 *  process begins.
 */
const USB_Descriptor_Device_t DeviceDescriptor =
{
    .Header                 = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},

    .USBSpecification       = VERSION_BCD(01.10),
    .Class                  = CDC_CSCP_CDCClass,
    .SubClass               = CDC_CSCP_NoSpecificSubclass,
    .Protocol               = CDC_CSCP_NoSpecificProtocol,

    .Endpoint0Size          = FIXED_CONTROL_ENDPOINT_SIZE,

    .VendorID               = DEVICE_VID,
    .ProductID              = DEVICE_PID,
    .ReleaseNumber          = VERSION_BCD(00.01),

    .ManufacturerStrIndex   = 0x02,
    .ProductStrIndex        = 0x01,
    .SerialNumStrIndex      = NO_DESCRIPTOR,

    .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
};

...
/** Product descriptor string. This is a Unicode string containing the product's details in human readable form,
 *  and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
 *  Descriptor.
 */
const USB_Descriptor_String_t ProductString =
{
    .Header                 = {.Size = USB_STRING_LEN(16), .Type = DTYPE_String},

    #if DEVICE_PID == 0x0036
    .UnicodeString          = L"Arduino Leonardo"
    #elif DEVICE_PID == 0x0037
    .UnicodeString          = L"Arduino Micro   "
    #elif DEVICE_PID == 0x003C
    .UnicodeString          = L"Arduino Esplora "
    #else
    .UnicodeString          = L"USB IO board    "
    #endif
};

and how would I go about building and uploading a modified bootloader?

You would run the Makefile which is in the same directory as the above file. Then send the resulting .hex file to your device.

authors: Юрий Багдашкин

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


text:
Attempted to disable autoreset - now the voltage regulator only outputs 4.0v
I followed the guide from the Arduino website, by placing a 10uF capacitor between GND and Reset. However, now the voltage regulator only provides 4v (Vin=13V). It correctly has 5V when being powered via USB.
What happened? Isn't there a 10k resistor between +5V and Reset that should prevent the chip from being overloaded? Or did the Reset pin sink the entire energy of the capacitor?

Is there anything else plugged into the Arduino?

Yes, but there wasn't any problems before. It's been working fine in full-time operation for several months, and all devices are powered by a seperate 7805.

How hot is the onboard LM1117 regulator?

Yes, the LM1117 5.0 is very hot. But I'm not sure if this is because some component, e.g. the ATmega chip, or a capacitor, has failed, and therefore whether it makes sense to try to replace the regulator.

It sounds like the regulator may be going into thermal shutdown. Without the capacitor does it right itself?

I've removed the GND-Reset capacitor even before asking this question, but the problem remains. The other capacitors are SMD mounted and not easy to remove. Perhaps there's no other way than to replace the whole board.

I assume you also tried removing all the other connected devices? Even though they are externally powered they may have a bearing on it.


text:
Recording and storing Midi data with arduino and midi shield
i need help getting started on writing a sketch that would let me record and store midi data from a midi controller connected to a arduino mega through a midi shield. are there any functions in the midi library that will aid in this task?

The Arduino MIDI Library allows you to read and write MIDI messages, but only in real time.
Storing MIDI data makes sense only with timestamps, so you have to call millis() or micros() when you receive a message.
How to actually store the data is something that you have to design yourself; which data structure to use depends on what you want to do with the data later.

once i have the data stored i want to be able to play it back


text:
Changing function to work with Midi controller instead of buttons
I am trying to change up this function to work with a midi controller instead of buttons most of the code for the function i will be using as is. it just the parts of the code the deal with button that i am finding a bit tricky to translate to work with a midi controller. any advice or suggestions would be a great help. here's the code for the function:
long currentMillis = 0;
long previousMillis = 0;

// Returns the position of Button pressed (0, 1, 2, or 3) or -1 if no button is pressed in the time period.
int waitForButton(int delay)
{
  int buttonPressed = -1;
  int input;
  boolean buttonBackUp = false;

  currentMillis = millis();         // The number of ms since the program started running
  previousMillis = currentMillis;   // Records the point when we start spinning the loop.

  // Keep spinning the loop until "delay" seconds have passed.
  while (currentMillis - previousMillis < delay & buttonBackUp == false)
  {
    // Read the button and record when it has been pushed down.
    for(int pin = 0; pin < 4 & buttonBackUp == false; pin++)
    {
      if(digitalRead(buttons[pin]) == HIGH)
      {
        buttonPressed = pin;

        // Show the LED pushed.
        digitalWrite(leds[pin], HIGH);

        // It is possible the button is still being pushed.
        // This loop spins until the button is let up.
        while (currentMillis - previousMillis < delay & buttonBackUp == false)
        {
          input = digitalRead(buttons[pin]);
          if(input == LOW)
          {
            buttonBackUp = true;
          }
          currentMillis = millis();
        }

        // Turn the LED pushed off.
        digitalWrite(leds[pin], LOW);

        // See if they took to long.
        if(currentMillis - previousMillis > delay)
        {
          buttonPressed = -1; // They took to long to let the button up so they lose.
        }
      }
    }

    currentMillis = millis();
  }

return buttonPressed;

How would you like to use MIDI to send commands? Could you elaborate sth more about desired inputs?

instead of button presses i want it to be for key presses from a midi controller

You get MIDI commands, so instead of reading the current state, you have events.

how would  i implement the event of  a  key press substituting into the code of that of the read current state? which midi commands would be best ?


text:
Can you pass the entries of a strut array to a int array? if so how?
typedef struct {
  uint8_t  pitch;
}LearnNote;

#define  MAX_NOTE  500

LearnNote  Noteseq[MAX_NOTE];

int learnindex=0;
void loop() {
 MIDI.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity){
Noteseq[learnindex].pitch=pitch;
learnindex++;
}

You are misusing the title. You are not supposed to squeeze your question there. Instead you should give a brief description of your Problem. Beside that in your particular case you can only cast your array from LearnNote to uint8_t. You need to loop over all entries and copy them one-by-one into an int-array.

Its not very clear what you are asking, but I think you are saying can you do this
uint8_t anArray[MAX_NOTE];
anArray = Noteseq.pitch;

In general the answer is no.  However in this specific case off the top of my head I think you probably can (maybe).  You have a struct which only contains bytes.  The compiler will probably pack the sequentially so you will effectively have a contiguous sequence of bytes which you would be able to copy to the byte array by doing:
memcpy (anArray, Noteseq, MAX_NOTE);  // THIS IS BAD PRACTICE!

You can only do this in this case because the types are both 8bit numbers.  Its not a good idea to do this copy between an array of structs and a POD type array is just asking for trouble.
Instead use a function to do it.
int* CopyPitch (LearnNote* source, int* destination, int count)
{
    for (int i = 0; i < count; ++i)
    {
        destination[i] = source[i].pitch;
    }
}

(You should really check for null pointers and stuff, but its just an example)


text:
Changing the order of GUI-elements inside Arduino ESP-Dash-library
I'm trying to add a new item "index" to GUI-elements that are created by using ArduinoJSON and the Vue.js-framework inside the ESP-Dash-library.
The library creates GUI-elements like buttons, sliders etc. and provides easy to program call-back-procdures to make the microcontroller interact with the user-input from the website.
The code as it is iterates through all defined GUI-elements and creates the HTML-code. First all temperture-showing elements then all humidity elements, then all sliders etc...
This means the sequence and the position of the GUI-elements can't be defined by the programmer.
The new functionality I want to achieve is that the programmer can define the sequence and position of all GUI-elements on the website.
This means a new item like "index" must be added and the HTML-creation-code must be changed to another kind of iteration through the GUI-elements.
Now I'm very lost on where to look into all the Arduino- or the javascript-code  to find that place where the iteration must be changed.
Here is the link to the GiPo https://github.com/ayushsharma82/ESP-DASH
and especially to the app.vue javascript https://github.com/ayushsharma82/ESP-DASH/blob/master/vue-frontend/src/App.vue
If this kind of question is inapropriate please drop a few words what is wrong.
And then add a link to "how to post good questions"
best regards Stefan

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


text:
Developing Standalone Arduino GUI Controller
I am rather new to using an Arduino.
As a part of my Graduate-Level Chemistry research, I am trying to further the development of a cheap DIY, open-source, Flow Chemistry Syringe pump system.
The device utilizes Stepper Motors, Step Motor control boards, an Arduino Uno, and a 3D printed Pump frame. Simple code was previously developed using the Arduino IDE. I have expanded on this a bit to allow for more customization (syringe size, mostly). The limitation here, is that the Serial Monitor inputs will be taxing to the users. I need to develop a simple GUI that allows for all of the inputs I need (syringe size, flow (step) rate, start and stop functions, etc.). I need this gui to be a standalone application that can be easily shared (no need to download anything extra, no installations, deploy-able on at LEAST Win and Mac).
Our labs goal is to develop a system that is easy to use and distribute, reducing the costs associated with using Flow Chemistry. I have a decent understanding of Arduino IDE, and I am willing to learn whatever I need to make this work.
I have seen a few things about Python, and 'Processing', but they seem to require the simultaneous use of Arduino IDE which would make deployment too complicated.
How should I approach this? What language do I need to learn? What advice do you have?

how do you intend to display the GUI?

I plan to have the GUI displayed on my computer monitor.

then, which part of your question is actually Arduino related?

I am searching for pointers on developing a standalone portable program to control the Arduino hardware. The Arduino hardware and Arduino IDE are understood. However, I have not found any examples that use a standalone program to control an Arduino that does not require the use of Arduino IDE on the side. Does this clarify my objective?

I use Java. The only "Arduino" portion is the serial communication to transfer commands and data (which we can help you with), but the GUI has nothing really to do with Arduino.

So, in embarking on this journey, should I learn how to develop a GUI using Java or another language first? Then learn how to incorporate the serial communication to control the Arduino?

you are not correct about this ... Python, and 'Processing', but they seem to require the simultaneous use of Arduino IDE ... google processing arduino serial

The Processing IDE is the one that Arduino "stole" to use for the Arduino IDE. It looks similar but does a completely different job. You should learn a programming language before you start thinking about how to integrate it with an Arduino.

I now know what to do to get started. Thank you all!

The Uno is connected to the PC with a Serial interface (emulated over USB). The program on the PC only sees the Serial interface. It is not important, if there is really an Arduino at the other end. Nearly every programmung language can be used for interfacing a Serial interface, each gives advantages and disadvantages. But you will not have a single portable program file, that you can start on different OS without installing anything. Either you need to compile the program for each OS individually, or you can use a portable programming language, where you first need to install it's framework on the OS (for example python).
I would propose a different solution (that I'm currently also working on): Depending on your lab situation you could extend your project with a network interface, either Wifi or LAN. Then you can present a webinterface to the user. When writing HTML/javascript websites, it is easy to have them display correctly on most mayor browsers.
That way the GUI is really independent from the OS. For adding the network connection, you could use a LAN shield, Wifi shield, or directly change the microcontroller from an Arduino Uno to an ESP board, which has Wifi build in and is also has more computation power and memory.
The webinterface can be interactive by the use of javascript (since you cannot run php or similar on the Arduino or ESP).
Wether you want to use a companion application, that you write for the PC, or a webinterface is up to you and depends on your exact lab situation.

+1 for web.  its the way to go for windows and mac.  if you just expose the command interfaces on a socket, you can make as complex a web gui page as you wish hosted elsewhere or on computer.  if hosting on arduino, keep it simple.  by making a command response program on a socket, you are essentially doing the work of php (server side stuff).

languages: C (or C++) for arduino, html and javascript for the gui

I have a similar project ahead of me. While it is quite but obvious to be able to read the output voltages using arduino, I was wondering if we could create a python file which will be saved as an executable, but have in it, code that will run the original arduino cc file to read the averaged voltages from the pins. I tried using pyqt5 and/or tkinter but I am having thread issues in that the gui hangs after a few seconds of activity.(I used pyserial library here)
It will be really helpful if someone can help me out here.

This doesn't provide an answer to the question. To ask another question, just click Ask Question above. If you wish, include a link to this question to help provide context.

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review

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


text:
Linux not recoginizing Arduino Mega2560 Clone
I have an Elegoo Mega2560 R3. On my Windows machine, it recognizes fine and loads exactly like a Mega2560. I have a System76 laptop running Pop_os!. When I attach the board, I cannot connect to the port in Arduino studio (reinstalled today with newest version).
When I check, I don't see the ttyACM1 device (ACM1 specifically because of items listed below).
lsusb before plugging in
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 5986:9102 Acer, Inc BisonCam,NB Pro
Bus 001 Device 002: ID 046d:c52b Logitech, Inc. Unifying Receiver
Bus 001 Device 004: ID 8087:0aaa Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

lsusb after plugging in
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 5986:9102 Acer, Inc BisonCam,NB Pro
Bus 001 Device 020: ID 2341:0010 Arduino SA Mega 2560 (CDC ACM)
Bus 001 Device 002: ID 046d:c52b Logitech, Inc. Unifying Receiver
Bus 001 Device 004: ID 8087:0aaa Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

dmsg after plugging in
[65178.203006] usb 1-6: new full-speed USB device number 19 using xhci_hcd
[65178.353353] usb 1-6: New USB device found, idVendor=2341, idProduct=0010, bcdDevice= 0.01
[65178.353359] usb 1-6: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[65178.353363] usb 1-6: Product: Arduino Mega 2560
[65178.353366] usb 1-6: Manufacturer: Arduino (www.arduino.cc)
[65178.353369] usb 1-6: SerialNumber: 7563331323335130F170
[65178.357650] cdc_acm 1-6:1.0: ttyACM1: USB ACM device

ls /dev/tty*
/dev/tty    /dev/tty23  /dev/tty39  /dev/tty54      /dev/ttyS10  /dev/ttyS26
/dev/tty0   /dev/tty24  /dev/tty4   /dev/tty55      /dev/ttyS11  /dev/ttyS27
/dev/tty1   /dev/tty25  /dev/tty40  /dev/tty56      /dev/ttyS12  /dev/ttyS28
/dev/tty10  /dev/tty26  /dev/tty41  /dev/tty57      /dev/ttyS13  /dev/ttyS29
/dev/tty11  /dev/tty27  /dev/tty42  /dev/tty58      /dev/ttyS14  /dev/ttyS3
/dev/tty12  /dev/tty28  /dev/tty43  /dev/tty59      /dev/ttyS15  /dev/ttyS30
/dev/tty13  /dev/tty29  /dev/tty44  /dev/tty6       /dev/ttyS16  /dev/ttyS31
/dev/tty14  /dev/tty3   /dev/tty45  /dev/tty60      /dev/ttyS17  /dev/ttyS4
/dev/tty15  /dev/tty30  /dev/tty46  /dev/tty61      /dev/ttyS18  /dev/ttyS5
/dev/tty16  /dev/tty31  /dev/tty47  /dev/tty62      /dev/ttyS19  /dev/ttyS6
/dev/tty17  /dev/tty32  /dev/tty48  /dev/tty63      /dev/ttyS2   /dev/ttyS7
/dev/tty18  /dev/tty33  /dev/tty49  /dev/tty7       /dev/ttyS20  /dev/ttyS8
/dev/tty19  /dev/tty34  /dev/tty5   /dev/tty8       /dev/ttyS21  /dev/ttyS9
/dev/tty2   /dev/tty35  /dev/tty50  /dev/tty9       /dev/ttyS22
/dev/tty20  /dev/tty36  /dev/tty51  /dev/ttyprintk  /dev/ttyS23
/dev/tty21  /dev/tty37  /dev/tty52  /dev/ttyS0      /dev/ttyS24
/dev/tty22  /dev/tty38  /dev/tty53  /dev/ttyS1      /dev/ttyS25

Have you 1) added yourself to the dialout group, and 2) disabled ModemManager?

Oh, man I am dumb. I did add myself to dialout but completely forgot I needed to re-login after.

Running avrdude as root works.
Adding permissions to ttyACM0/ttyACM1 for everybody also works. Execute
 sudo chmod 777 /dev/ttyACM0
 sudo chmod 777 /dev/ttyACM1

and after that you should be able to compile and upload the code to the arduino
The only issue with this is that you have to run that line everytime you connect the Arduino to the USB because ttyACM0/ttyACM1 is recreated. So as pointed in the comment
if thats the case than you add dialout group to your user, log out, then log in again, you should have access to the Arduino serial.
 sudo usermod -a -G dialout yourUserName


text:
Java Errors thrown by Ardunio IDE when attempting to open serial monitor
I am only getting this error on one of my Windows 10 PC's.   On another windows 10 PC and Mac, the board (Mega 2560) is working fine.
Any hellp or advice on this would be appreciated.
THE PROBLEM
After uploading the sketch and then attempting to open the serial monitor, Java error messages (shown below) are displayed in the information window in the IDE.  The serial monitor fails to open.  Other sketches that do not use the serial monitor work fine.
ANYTHING UNUSUAL ABOUT THIS PC?
The only thing that is perhaps unusual about this PC is that Serial Ports COM1: AND COM2: are real RS432 hardware serial ports.
The Ardunio IDE connects to the board via USB Serial Port COM5:
REMEDIES TRIED SO FAR

Uninstalled and reinstalled the software (including purging Arduino settings in Documents\ folder
Trying the board on other PC's / MAC (to verify that it is not a faulty board).  Tests confirm that board itself is fine

THE ERROR MESSAGES

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2
    at processing.app.AbstractMonitor.(AbstractMonitor.java:68)
    at processing.app.AbstractTextMonitor.(AbstractTextMonitor.java:53)
    at processing.app.SerialMonitor.(SerialMonitor.java:42)
    at cc.arduino.packages.MonitorFactory.newMonitor(MonitorFactory.java:49)
    at processing.app.Editor.handleSerial(Editor.java:2193)
    at processing.app.Editor.lambda$buildToolsMenu$17(Editor.java:723)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:842)
    at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:886)
    at java.awt.Component.processMouseEvent(Component.java:6539)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6304)
    at java.awt.Container.processEvent(Container.java:2239)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2297)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
    at java.awt.Container.dispatchEventImpl(Container.java:2283)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
    at java.awt.EventQueue$4.run(EventQueue.java:733)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

What version of the IDE are you using, and how did you install it?

Try running the ArduinoIDE as Administrator, test the com port to use with a terninal program like PUTTY.

The version of the IDE that I am using, on both windows PC's is 1.8.12 (Windows Store Version 1.8.33.0). The software was obtained by going directly to the Arduino.cc downloads page which then redirected me to the Windows Store.   Both Windows PC's are 64 Bit, and I log into both using my Microsoft Account.   I tried using Putty as suggested, but that just bleeped when trying to communicate with any serial port, even the ones connected to my Chess board with the RS432 interface.   The Chessboard still works fine. For the time being, I will just use the other PC for the Arduino.

Just as an experiment, I downloaded one of the 'nighly releases' directly from the Arduino site.  And, guess what - it works! Bit of a mystery why the same Windows Store version works on one of my PC's and not the other but, for the teim ebing, problem solved.


text:
UNO SPI slave read from UNO SPI Master beginTransaction
For a project I am trying to understand SPI.
The final project I will use this in, is for reading the SPI from a car radio.
That Radio writes to address 0x80 of a DDRAM LCD display. MY intent is to read for a write to this address and if the bits are correct replace waht is being written.
IE Radio says write the letter E to 0x80, using a mega2560 read this and then interject a different letter then write to the radio screen. So the radio is a master with the Mega and LCD as daisy chained slaves.
I'm using the base code from for writing to the screen. This was written to fully replac ethe radio so i'm trying to mimic the radio using an UNO as Master and the screen using a Uno as a slave.
I've got the demo working from circuits4you.com
I'm trying to modify it to use the same STI settings as seen in the base radio replacement code i'll be modifying for my final project. I know this code writes correctly to the screen. The problem is that the code uses SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3)); as its designed to replace the radio functions.
I'm trying to get that line to work on the 2 UNO's im bench testing with so I can make the mega a slave in the final project.
SPI MASTER Code

void setup (void) {
   Serial.begin(9600); //set baud rate to 115200 for usart
   digitalWrite(SS, HIGH); // disable Slave Select
   SPI.begin ();

}

void loop (void) {
    SPI.beginTransaction(SPISettings(9600, MSBFIRST, SPI_MODE3));

   char c;
   digitalWrite(SS, LOW); // enable Slave Select
   // send test string
   for (const char * p = "Hello, world!\r" ; c = *p; p++)
   {
      SPI.transfer (c);
      Serial.println(c);
   }
   digitalWrite(SS, HIGH); // disable Slave Select
   delay(2000);
   SPI.endTransaction();
}

The problem seems to arise from the SPI.attachInterrupt() not being compatible with the SPI.beginTransaction is this correct and is there a way around it?
SPI SLAVE Code
include <SPI.h>
char buff [50];
volatile byte indx;
volatile boolean process;

void setup (void) {
   Serial.begin (9600);
   pinMode(MISO, OUTPUT); // have to send on master in so it set as output
   SPCR |= _BV(SPE); // turn on SPI in slave mode
   indx = 0; // buffer empty
   process = false;
   SPI.attachInterrupt(); // turn on interrupt

}

ISR (SPI_STC_vect) // SPI interrupt routine
{
   byte c = SPDR; // read byte from SPI Data Register
   if (indx < sizeof buff) {
      buff [indx++] = c; // save data in the next index in the array buff
      if (c == '\r') //check for the end of the word
      process = true;
   }
}

void loop (void) {

   if (process) {
      process = false; //reset the process
      Serial.println (buff); //print the array on serial monitor
      indx= 0; //reset button to zero
   }

}

Please show your modification (use and position) of SPI.setDataMode() in your code above.

Okay so I have got this working now. It seems that it was the Slave not understanding the data mode. I found the SPI.setDataMode() it is listed as Do not use in the reference guide on Arduino.com but its worked spot on for me.


text:
What Are The Differences Between Arduino Language and Standard C for MCU?
What the differences between Arduino language and standard C used for MCU programming (like AVR).I heard Arduino language is C.What happen if i use Arduino language with bare-bones AVR chips.Or with PIC mcu.Will it work?
And, if i use just use AVR chip without arduino, will it work with sensor that designed for Arduino (lets say HC-SR04 ultrasonic sensor).And will sensor designed for arduino work with PIC mcu or other non AVR mcu?
I'm a beginner mcu programmer and currenly learning Arduino.Which is good starting point learning Arduino first or just go straight to MCU programming (without Arduino, just bare bones chip)?
Thank you

There's really no such thing as the 'Arduino language'. The Arduino IDE supports C & C++ with some syntactic sugar added.

@Lundin Arduino "IDE" supports C files quite happily.

@marcelm try loading a file that has int main = 10;. What's your point?

@Lundin if you include a C file in the Arduino IDE, it will treat it as C. Having just tried it int new = 5 in a .c extension file compiles perfectly well...

C files are compiled using avr-gcc, C++ files are compiled using avr-g++. The only thing you have to do to mix the two is to have #ifdef __cplusplus extern "C" #endif ... in header files that are shared between the C++ and C codes.

@TomCarpenter int main = 10; compiles perfectly fine in C. You will have trouble using standard library, but you can link directly to C runtime which has a different entry point (_start() in Linux and WinMain() in windows).


text:
Is there a way to setup an interrupt to trigger at n number of clock cycles from now?
I currently have an nRF transmitter/receiver pair setup on my desk. The transmitter is sending a single byte (0xAA) every 5ms. The receiver sets an LED high to indicate that it received the byte, which is about 10us (+/-2) after the byte was sent. I want to use this nRF pulse for a precise timing/sync application with +/-0.5us accuracy so I need to filter these receiver pulses such that I can estimate the time the transmitter actually sent the byte and the time the next one should arrive. I created an algorithm that uses past nRF pulse times (measured in clock cycles using Teensy's ARM_DWT_CYCCNT register) to estimate the next pulse and it seems to be working reasonably well - though I can't say yet if I'll get the 0.5us accuracy I want.
Now I want to take that estimate and have my microcontroller set an output pin high as soon as the clock count reaches the estimated clock value. Currently I do this by waiting in a while loop and polling the register, but the loop itself takes up several hundred clock cycles which reduces my accuracy. Is there a way to instead have an interrupt trigger when the clock cycle counter reaches my estimated value? I would somehow need to set this interrupt after computing each estimate.
Thanks!

Output Compare sounds like your best bet. Set the Output Compare value to your timeout value, and start the timer running from 0 when you get your pulse. When the timer == the OC value the output turns on.

Where's your code?

Use a timer to count the system clock and preload the counter with an offset that overflows in the desired cycles.
Use a timer to count the system clock and set a compare match a desired number of cycles out.

To expand the number of cycles, you can do fancier processing in thee Isr but the basic gist IS the same.
Other approaches also exist but the two outlined here are easier.


text:
Is it dangerous to connect two output pins together?
If I have two output pins, one set high and the other set low with digital or analog write like this
digitalWrite(PIN1, LOW);
digtialWrite(PIN2, HIGH);

and then I short them together using a wire, will current flow through the wire?

will current flow through a wire if you connect the positive and negative terminals of a battery?

Oh yeah. So a large amount of current will flow which could damage the arduino.

Yes. It is dangerous. You can imagine what would happen when you understand how a GPIO pin works in output mode.
You are effectively connecting VCC to GND via two small and weak MOSFETs which will overheat and break down.

Shorting the output pins together is a bad idea that will likely result in damage to your Arduino. According to specifications, the I/O pins are able to source (provide current to a load) or sink (accept current from an external source) up to 40mA. In almost all cases, you will want to use a current-limiting resistor. In some cases, an external circuit that you connect your Arduino to may intrinsically limit the current.
In the case of lighting up an LED, you can do this in two ways:

Set the I/O pin HIGH to source current to the LED through a current-limiting resistor to ground. The I/O pin provides the current to light up the LED. LOW turns it off.
Set the I/O pin LOW to sink current from the LED and current-limiting resistor where the power to the LED is provided by the external source. In this case, the LED floats and the I/O pn serves as ground. HIGH turns it off.

The internal pullup resistor is useful if you want to be able to drive an external transistor or logic level device.
This Arduino tutorial goes into more detail about the specific modes of operation.

You can connect but requires resistor between two pins to limit the current.

It depends on what you try to achieve. If you want to demonstrate what happens without a resistor, and you're ready to accept possible damages, you can connect two output pins directly, and drive different levels.

That's out of spec for any arduino microcontroller.
The behavior of a broken Arduino is "undefined" :)
I guess there will not flow current (after an initial peak), but at least one of the two pins is not working properly any more. But, this is just a guess.
And it's probably not dangerous for you or the connecting wire (Other than @jsotola's comparison with a shorted battery in a comment to your question). I guess the arduino will die before it gets dangerously hot.


text:
Getting external data to the Arduino
I have a new Uno R3, it's pretty cool and I've enjoyed playing with it.
Now I want to build a couple of things:
1) a market price LCD tracker.
2) a servo motor type thing to open my electric gate.
Both of these either require input from an external website or some kind of message to initiate the action on the Arduino.
How do people generally get data onto the Arduino, I found a lot of conflicting information online.
Does this thing have Wifi or Bluetooth??
I got this pack, it doesn't seem to have either Wifi or Bluetooth, if not how do ppl generally get data onto the Arduino?
I have a raspberry pi spare, can I just use that, sending data from pins?

How do people generally get data onto the Arduino, I found a lot of conflicting information online.

There are various ways depending on what the data is and how you access it.

Does this thing have Wifi or Bluetooth??

Not unless you add WiFi or Bluetooth to it, no.

I have a raspberry pi spare, can I just use that, sending data from pins?

Yes, there are ways.

How you go about getting data on to an Arduino depends very much on how the data is accessed.  It is possible to add a WiFi interface to an Arduino, either through an official WiFi shield or through adding something like an ESP8266 on a breakout board (ESP-01 is popular) although interacting with the ESP8266 can be tricky.
You can do the same with Bluetooth or any number of other wireless protocols.
The simplest method of getting data to the Arduino, though, is through the USB serial port. Since you have a Raspberry Pi available the most logical option would be to plug the Arduino directly into the Pi's USB port. The Pi can then communicate through /dev/ttyACM0 (or /dev/ttyUSB0 for some clones) and the Arduino receive the data through the Serial object. Exactly how you arrange all that is entirely up to you.

Thanks!, so it's valid to use the pi to receive data from the net, process it and send it to the Arduino to display or whatever via USB?  So I guess I wonder is this a known pattern, to use the Pi as data ingress from the web?

Sure, it's perfectly valid. Maybe not common, since the Arduino is probably pretty redundant as the Pi can do most thing natively without needing the Arduino.

ah my plan though is to make a smart gate opener... iPhone Shortcut-->Message Pi over cellular and write data over to Arduino --> Servo Motor, press physical button on gate opener. This way I can give access to anyone to open the gate (via pub/priv key pairs), and I effectively turn one physical fob into a smart remote that can serve many ppl

It depends on the kind of data and where it will be coming from. Trigging your gate really only needs a signal to start moving, though a directional signal would be better ("Open" or "Close"). What is the source of that signal and far from from the gate will it originate?
If you're willing to press a button on the gate, it's a simple matter of sensing the button with one of the Arduino's pins. If you want to operate it from your phone from right in front of the gate, a Bluetooth module on the Arduino could pick up the phone's signal. If you also need to operate it from further away - more than 5-10 meters, a pair of RF modules with stick-antennas like the ones on a WiFi router, might get you 100m.
For the market-price tracker, your data is probably coming from the internet, in which case you'd need either an ethernet module or a WiFi module that would link it to the internet through your local network. Or if this device has to be portable, you could use a cellular module to link it to the internet through the cellular network. This latter is usually expensive - the price of adding an additional line to your cellular plan, for instance.


text:
Writing elegant applications for Arduino
Coming from a C background, I was taught that tight loops that just burn CPU aren't desirable.
Is there any programming style guides on Arduino? Is it common practice to just let loop iterate as a tight loop forever?

Is your project powered by batteries or by mains?

@EdgarBonet mains, I'm just wondering if the loop section can be made more elegant or if its always just a tight loop, feels a little like while(1).

A microcontroller's execution path is a tight loop whether you like it or not.
If you take a CPU and connect it to empty memory the CPU will execute each empty cell in turn and loop back to the beginning of memory when it reaches the end (assuming empty memory cells equate to NOP and covers the whole memory space).
With no operating system, no scheduler, nothing except your specific code running, the CPU is always executing something.
The only time the CPU stops executing is when you manually send it to sleep to be woken by some external source (such as a timer, or a sensor sending an interrupt signal). You'd only do that, normally, to reduce power consumption.
On Arduino the loop() function is in fact executed from within a while(1) loop.
On microcontrollers when main() exits, or you call exit() it just disables interrupts and drops out to a while(1) loop.

On a multiprocess system, like your typical desktop, you usually have
way more processes than logical CPUs. When programming such systems you
therefore have to avoid burning more CPU cycles than needed. Instead,
when your program has nothing to do, it should just sleep, and leave
the CPU available for other processes.
On an Arduino, you only have one single program running at a time. It is
then not that useful to keep the CPU idle. Also, the power dissipation
is so low that you will not notice the microcontroller getting even
slightly warm. The extra complexity of getting into and out of sleep
mode is therefore not that useful. Only when running on batteries do you
care about saving every possible milliamp: then learning about sleep
modes starts getting useful.

Furthermore, with cooperative multitasking on a real mode system like an Arduino you WANT the main app loop to run as fast as possible (The tightest possible loop.) That way it checks for & responds to inputs as fast as possible. If you write interrupt code, you want THAT to finish as quickly as possible in order to get back to that tight main loop.

That is a difference between embedded systems programming and (many but not all) other types of programming. An embedded system is usually a controller of some kind and needs to be responsive to one or more kinds of events. Three typical ways of accomplishing this are

to use some kind of operating system to coordinate events and the code that manages each of them;
to write interrupt service routines (ISRs) to manage events and dispatch to code that manages them;
to poll for events frequently and dispatch to the code to manage them.

On processors as small as the AVRs, data memory and sometimes instruction memory, are scarce resources and an operating system is usually too expensive (in terms of memory needs) for most of them. On the ATtinys, forget it. On Uno, maybe kinda sorta, but memory will be a pretty severe limitation. On Megas, you might manage it.
ISR programming can be complex to write and is definitely more complex to debug(!). It's not out of the question, and it may be justified in a system that must be highly responsive - think automotive ABS braking, traction control, and fly-by-wire systems. On the other hand, systems like these have to be right.
Polling is the easiest to write and debug. You call each subsystem (code) in a tight loop (and there's your answer: "yes, let it iterate") that gives each one an opportunity to assess whether or not it needs to act and to do so. This is a case where burning cycles is inconsequential, while making a more responsive system.
In my hobbyists' classes, this is what I teach; it's also what use most. I call it "maybe-do" (and wrote about it here in answer to another question). In loop() I do nothing but call a number of functions in turn, each of which does:
   {
      if I dont need to act now,
         return;
      else {
         do what needs to be done -- quickly!;
         return;
      }
   }

thank you JRobert!


text:
2xArduinos, 2xDevices, I2C setup
Is it valid configuration using hardware I2C pins:

Especially: can NanoEvery initialize communication with DS2482, while it is slave for Mega2560? Using Wire library or should I use software I2C when talking to Mega2560 and leave NanoEvery as master to DS2482?
Needed to use additional Nano due to long times of reading temperatures connected to DS2482 that blocks Mega controller.
Graph source

why would the reading block the Mega? ATmega 4809 has "Independent Master and Slave operation– Combined (same pins) or Dual mode (separate pins)", but I don't know if the Arduino libraries support it

@Juraj firstly Nano and Mega were connected by serial, now I'm trying to combine them in one rail mounted case and save 2 pins, trying to not add new hardware.

you don't need the Nano. in Mega start the reading in sensor, do other things and later read the result from the sensor


text:
Different Output Voltages from Same Source?
I'm wondering whether it is possible to wire multiple buck converters with different voltage requirements and amperage draws to the same power source (this idea is for controlling a radio-controlled boat). Going off other related questions this seems to be possible (1, 2).
My background is in programming, not electronics, so the terminology is difficult for me to understand. I'm getting a grasp on voltage and amperage. My problem is always understanding how electricity can be "split" into different modules. In my understanding, this below would be a parallel circuit and that should be fine.

Are there any gotchas to consider with this type of circuit, or is this the totally normal way of doing things (eg. like wiring a house out of a breaker box)?
Is there a better way to do this?
This won't cause a short circuit, right?

Are there any gotchas to consider with this type of circuit, or is this the totally normal way of doing things (eg. like wiring a house out of a breaker box)?

That's a perfectly normal way of wiring it.

Is there a better way to do this?

No, it's how I'd do it.

This won't cause a short circuit, right?

Not intentionally, no. However it's always good to add a fuse or two to protect everything just in case anything untoward should happen. Especially where water is concerned.


text:
How do I set a variable so that after a condition is met the loop ignores input?
I have a analog inputs to my Uno that I am cleaning up and using to keep a digital pin high until the output drops to zero. At this point I want to stop reading that input because it may come back up after being low for a short time.
Is there any way to set a variable that can be triggered by that first zero that prevents the loop from sending the digital pin high from then on?
Like a latch of some sort, or could I use an interrupt somehow?

Sure. Just set a variable to some value. And use if to compare that value.

You may call that variable a "flag" which is set once your input == 0 and read before settings the output to high.

You've already described what you need to do.  Just set a boolean variable.  It really couldn't be easier.
boolean runThisPart = true;

void loop() {

  if(runThisPart) {
     // this part only runs if runThisPart is true
     //  if something happens and you don't want
     //  to run this part anymore then
     if(some-condition){
        runThisPart = false;
     }
  }
  //  The rest of your code can also set runThisPart
  //  to true or false to turn that section on or off.
}


text:
Need help with using pulseInLong to time a sensor
I have a setup consisting of a magnet suspended above a sensor coil. It acts as a pendulum and creates a ~ 4 mV signal when it swings over the coil - this goes through two stages of an LM358 to generate a 5V signal. The signal is very messy with lots of 'ringing'
This signal is fed into pin A0 of an Arduino Uno. I used MegunoLink.h and Filter.h which is an exponential filter library then applied constrain and map, finally converting to a clean 0 - 400 (units?) square wave of about 1 second with a varying duty cycle. This is the information I want as it tells me that the magnet is homing in on the sensor (the duty cycle increases as it gets close).
But when I apply pulseInLong I only get a string of zeros on the serial monitor.
What am I doing wrong?
Here is the sketch:
//  Coding by Jeremy 130520
//  further development for ricochet module
//https://www.megunolink.com/documentation/arduino-libraries/exponential-filter/
//https://www.google.com/search?q=how+to+use+arduino+pulsein

#include "MegunoLink.h"
#include "Filter.h"
// Create a new exponential filter with a weight of 5 and an initial value of 0.
ExponentialFilter<long> ADCFilter(5, 0);

int coilPin = 8;
int analogIn = A0;
unsigned long pulseLength;
unsigned long signal_1;

void setup()
{
  pinMode(coilPin, OUTPUT);
  pinMode(analogIn,INPUT);
  Serial.begin(9600);
  }

void loop()
{
 int RawValue = analogRead(analogIn);
  ADCFilter.Filter(RawValue);
 signal_1 =(ADCFilter.Current());
 signal_1 = constrain(signal_1,80, 200);
 signal_1 = map(signal_1, 80, 200,0,400);
 if (signal_1 >= 200) {signal_1 = 400; digitalWrite(coilPin, HIGH);}
 if (signal_1 < 200) {signal_1 = 0; digitalWrite(coilPin, LOW);}

 Serial.println(signal_1); //using the plotter

//pulseLength = pulseInLong(coilPin, HIGH);
 //Serial.println(pulseLength);
 delay(10);
}

You cannot use pulseInLong() because it is a blocking function. It
waits until the input rises, then waits until it falls again, and only
then it returns a value. While it's waiting, the rest of the program
cannot run. This means you will not be able to actually generate the
signal you are trying to time.
The easiest solution is to time things yourself with micros(). You
have to implement an edge detector, i.e. some logic that remembers the
previous state of the signal and notices when it changes:
static bool is_high;  // is the input currently HIGH?
static uint32_t time_of_rise;  // when did it rise?

if (!is_high && signal_1 >= 200) {  // rising edge
    time_of_rise = micros();
    is_high = true;
} else if (is_high && signal_1 < 200) {  // falling edge
    uint32_t pulse_width = micros() - time_of_rise;
    is_high = false;
    Serial.println(pulse_width);
}

Thanks Edgar that looks good - I shall try it tomorrow and get back to you

That worked very well. Clearly showing when the magnet gets close to the sensor coil allowing me to take some other action at that point.


text:
Accessing HTTPS server of ESP8266 through fetch
I have been messing around with this application for a while but seem to keep hitting roadblocks. I am trying to have a public HTTPS page make a fetch to a private ESP8266.
As you can guess I ran into several infamous CORS issues and had to become with these posts: https://developer.chrome.com/blog/private-network-access-update/
https://web.dev/cors-rfc1918-feedback/
https://wicg.github.io/private-network-access/
After reading this I became persuaded that I needed to have an HTTPS server on my ESP8266 because this is the only way that the CORS policy would allow me to make a request from a public page to a private one. My issue now is that Chrome will allow these requests with a self-signed certificate on the ESP8266, but Firefox (which didn't throw any errors about this until very recently) blocked my request because the certificate was self-signed.
Is there any easy way to have a trusted certificate (i.e. something not self-signed) on my ESP8266 so that both Chrome and Firefox will allow this request?
If not, what is the most appropriate way to allow HTTPS connections to come to my ESP8266 without having to have a user trust the self-signed certificate in their browser?

https://unix.stackexchange.com/questions/644176/how-to-permanently-add-self-signed-certificate-in-firefox

you can use a web server (or a package like node-red) as a proxy. the esp talks to the server, your browser listens to the server. you can also use websockets, which don't have as much scheme and domain restriction.


text:
Cannot successfully implement singleton
I have spent the better part of today trying to figure out why I can't get this to work...
I have this project where, because of previous design considerations, have implemented a singleton class that initializes a bunch of separate sensors in this system that I am running.
The system was originally built for the Particle Boron, but now I am trying to make it work with the Adafruit Feather M0, so I have had to refactor several things and omit lots of lines of Particle RTOS specific things.
However, in doing this, I find that my singleton class no longer works.
Sensors.h:
.
.
.

class Sensors{

    static Sensors *instance;

public:
    static Sensors *getInstance() {
        if (!instance) {
            instance = new Sensors;
        }
        return instance;
    }

}

private:
    Sensors();

.
.
.

Sensors.cpp:
.
.
.

Sensors::Sensors() : dht22(DHTPIN, DHTTYPE) {
#ifdef PLATFORM_ID
    sensorLog("app.Sensors");
#endif
}

.
.
.

main.ino:
.
.
.

// Sensors
Sensors *Sensors::instance = nullptr;
Sensors *allSensors = allSensors->getInstance();

void setup(){

.
.
.

As I try to compile this with ArduinoISP, no matter what I try, I get the following error:
sketch/main.ino.cpp.o: in function `Sensors::getInstance()':
sketch/lib/Sensors/src/Sensors.h:23: undefined reference to `Sensors::Sensors()'
collect2: error: ld returned 1 exit status
exit status 1
[Error] Exit with code=1

I have tried things like changing the line
instance = new Sensor;

to
instance = new Sensor();

making the instance public, changing the Sensor constructor, but all of this to no avail. Could this be a compiler issue? Why would this work on a Particle board, but not an Adafruit Feather M0?

is the cpp in the same folders as the ino?

Unlike RTOS, Arduino is single threat and no OS, there is really not have any benefit to implement singleton in Arduino environment...

private: Sensors() is outside your class - and your class lacks the required ; at the end of it. Your code is uncompilable as it stands.

@Majenko, the constructor is used only in getInstance. it can be private and is declared there. the compiler founds it. the error is at linking

I had the same problem when referencing classes from multiple files, remember to put at the top of your header file (ending in .h) #pragma once on files that get referenced more than once!
Edit1: Also after you declare your class you need to specify where your static variable will be stored.
After the class declaration write:
type *Class::variable;
To declare the static variable.
For example:
#pragma once
//#includes

class Screen
{
protected:
  static void (*StateMachineStep)(int);
  static SSOLED *oled;
  static Player *player;

public:
  Screen() {}

};

void (*Screen::StateMachineStep)(int);
SSOLED *Screen::oled;
Player *Screen::player;

Edit2: formatting

Singletons aren't a thing in Arduino. Sure, you could do it, but in general you'd make a class then instantiate a global object for that class. Most often that global object is instantiated in the library itself, not the sketch.
Unless you're using an advanced chip with an RTOS (such as ESP32) and making use of the threads of that RTOS heavily there is no benefit to having a singleton.
But to answer your actual question: it's probably because you are trying to use the Sensors() constructor at a time before the compiler knows what the Sensors() constructor is. You would have to add some form of forward declaration so that the compiler knows what you mean when you talk about the Sensors() constructor.  In general a simple:
class Sensors;

at near the top of your header before the class is actually defined can help in these situations;

Or the OP can simply move the private contructor from the private section to above the public section. Then it should be private (because there is no modifier above and private is the default) and declared before its usage.

@PeterPaulKiefer, ordering of class members in the class declaration doesn't matter

@Juraj You are right. Please, forget what I said. I'll leave the comment as an example of ignorance ;-) and to help other not to have the same misconception. Now, I think the main problem is that the getInstance method is implemented in the class definition and the constructor is not (just declared). So, probably it helps also if we move the implementation of thegetInstance() into the cpp file an leave only the signatur declaration in the hpp file. Or is there a reason why this would not work?

@PeterPaulKiefer, I think the cpp is not compiled, because it is in some folder ignored by IDE

@christopolise Are you still with us?  What Juraj mentioned in the answer of my last comment sounds good.  The CPP file might not be compiled. Did you investigate in that direction? Juraj mentioned that in a comment for the OP, but I have to apollogize for not having recognized it.

@Juraj Yes, I agree with you. Your idea is also underlined by the fact that, the code worked on a RTOS system, but not after using the ADUINO IDE. I hope the OP is still here, as I'm interested in the final answer ;-)


text:
How to read data from ThingSpeak for esp8266
I am trying to read data from thingspeak for esp8266 but I couldn't do that. There is a link:
GET https://api.thingspeak.com/channels/123456/fields/1.json?api_key=***********&results=2
But how can I use it?

are you able to connect to some other website like stackexchange.com?

I don't know. But probably I can.

I believe Thingspeak supports MQTT. That would be preferable in my opinion.

How are you doing that? Please post your code

@StarCat What is MQTT.

MQTT is a message protocol for sending small messages to and from IoT devices like sensor values, status messages or receiving commands. It's simple to implement and very reliable. Here is an introduction to using an ESP8266 with Thingspeak and MQTT. It might work for you.

use ESP8266HttpClient library. see the examples.

check out https://shiftr.io/try to get an idea what MQTT is about

I directly code the esp8266 with thingSpeak library. Anyone who is interested look here:How to read data from thingspeak. And it worked. Thanks for your replies.


text:
Help Convincing Wiimote a Nano is a WiiMotion Plus
I want to replace the outdated gyro in a wiimotion plus with a BNO055. Based off what I've read from wiibrew, and im currently trying to get the wiimote to recognize the nano as an extension over I2C. Theres a lot of things at play here, but this summarizes the parts related to my issue:

When playing a game that needs WiiMotion Plus (WMP), the wiimote will send out a request to a slave device with address 00x53 to read register 0xFE every ~8 seconds.
If there is an actual register there, and it has the correct two byte id (this case it should be 0x00, 0x05), it will write 0x04 to 0xFE, activating the WMP and it will subsequently start sending motion data

I got my register information by copying the registers of an actual wiimotion plus, so i know the information is correct, yet for some reason i receive the requests from the wii and it doesn't send the activation byte back, it ignores it and keeps asking for requests. Heres an outut from my code.
23:38:28.599 -> WM+ tester
23:38:37.628 ->
23:38:37.628 -> Recieving information...
23:38:37.628 -> Handling request to register 254
23:38:37.628 ->       Sending bytes: 0,5,254,0,0,0,0,159,1,255,0,44,1,236,1,93,1,59,1,79,1,0,0,0,0,201,2,190,2,218,2,148,
                                     ^^^ the extension id
23:38:37.675 ->
23:38:37.675 -> Recieving information...
23:38:37.675 -> Handling request to register 254
23:38:37.675 ->       Sending bytes: 2,183,2,164,2,149,2,13,10,0,72,97,110,100,108,105,110,103,32,114,101,113,117,101,115,116,32,116,111,32,114,101,
23:38:37.767 ->
23:38:37.767 -> Recieving information...
23:38:37.767 -> Handling request to register 254
23:38:37.767 ->       Sending bytes: 103,105,115,116,101,114,32,0,32,32,32,32,32,32,83,101,110,100,105,110,103,32,98,121,116,101,115,58,32,0,44,0,

Since the slave cant know the length of bytes requested, it sends the maximum of 32 and theoretically the wii should take what it needs. But as i noted, the wiimote doesn't accept this and keeps requesting bytes, moving up the registers as it goes. My code for these interactions is here (most of which is documentation for future use):
// All values are big-endian.
// Assume data is tightly packed.

// The i2c stream is 0x100 bytes long, and it is mirrored across the entire 16-bit address space up to 0xa4FFFF
// Peripheral Protocol is 400kHz "fast" I2C
// NOTE: the structure of this code does not allow for passthrough devices

// References:
// https://github.com/denizkoekden/arduino-wiimote
// http://wiibrew.org/wiki/Wiimote/Extension_Controllers
// http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Wii_Motion_Plus
// http://randomhacksofboredom.blogspot.com/

#include "Wire.h"

#define EMPTY_BYTE 0xFF
#define SERIAL_BAUD 115200
#define CLOCK_FREQ 400000

byte wiimote_registers[0x100] = {0xB5,0x26,0x42,0x7F,0x7E,0x7E,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x7A,0x8A,0x77,0x2B,0x77,0x3A,0x31,0x48,0xD5,0x27,0x27,0xE6,0xC8,0x30,0xB1,0xF9,0x83,0x4D,0x78,0x45,0x78,0xE0,0x36,0xDA,0xD1,0xDC,0x2A,0xCC,0x2D,0x4F,0x48,0xCD,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x25,0xE0,0x8E,0xCE,0xFA,0x1E,0x25,0x8A,0x9F,0xCB,0x8B,0xFC,0x5,0x96,0xFF,0x1A,0xD3,0xC8,0x15,0x97,0xCF,0xAF,0xB7,0xCC,0x72,0x79,0x87,0x78,0x35,0x9B,0x27,0x6C,0x9C,0x6A,0x1C,0xD4,0x88,0x8E,0xD6,0xA,0xE1,0xDA,0xBD,0x38,0xA5,0xD5,0xB,0x9D,0x3A,0xAC,0x26,0x1A,0x4D,0xFA,0x5,0x21,0x24,0xD8,0x6A,0xA3,0xED,0x60,0xEB,0x1A,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x2,0xFF,0xFF,0x0,0x0,0xA6,0x20,0x0,0x5};
static byte state = 0;

const byte inactive_expansion[2] = {0x00, 0x05};
const byte active_expansion[2] = {0x04, 0x05};

const byte inactive_address = 0x53; // starts at 0xa60000
const byte active_address = 0x52; // starts at 0xa40000

const byte inactive_id[6] = {0x00,0x00,0xA6,0x20,0x00,0x05};
const byte active_id[6] = {0x00,0x00,0xA4,0x20,0x04,0x05};

// IMPORTANT REGISTERS AND WHAT THEY SHOULD HOLD

const byte id_reg = 0xa600fa;
  // holds id, used to identify extension type

const byte activate_reg = 0xa600fe;
  // activates the wmp when 0x04 is written to it
  // activation changes the extension identifier and makes the wmp start reporting motion data
  // writing 0x05 or 0x07 to this register can also implement passthrough mode
  // but we wont allow for other extensions to be connected, making that feature useless

const byte deactivate_reg = 0xa400f0;
  // deactivates the wmp when 0x55 is written to it
  // writing 0x55 to it also activates whatever extesion is connected to the wmp
  // deactivation reverts whatever changes activation has made

const byte init_reg = 0xa600f0;
  // starts initialization of the wmp when 0x55 is written to it
  // initialization does little, except for changing init-shift and init_rand_shift registers

const byte init_reg_2 = 0xa500fb;
  // would normally start initialization process once 0x00 was written to it
  // however wmp games dont do this, so its useless

const byte init_shift_reg = 0xa600f7;
  // during initialization it changes from 0x02 to 0x04 to 0x08 to 0x0C to 0x0E then stays at 0x0E
  // yet wmp games dont read this, making it useless

const byte init_shift_rand_reg = 0xa60050;
  // after initialization, registers 0xa60050 to 0xa600cf will change briefly, but randomly, for a total of 128 bytes

const byte calibration_reg = 0xa60020;
  // 32 bytes of calibration information which are reported once activated

const byte motion_reg = 0xa40008;  // (or sometimes 0xa40000)
  // 6 bytes of gyro information which are reported once activated

/*
  This is a representation of the data to be stored in motion_reg and calibration_reg

  The motion data's bits of data are split into two parts.
  The first part is the first 0-7 bits of data
  The last part is the last 8-13 bits of data
  Unused Bytes are filled with 0x00

              struct motion_data {
                byte yaw_down_7_0;
                  // Byte 0, <7:0>

                byte roll_left_7_0;
                  // Byte 1, <7:0>

                byte pitch_left_7_0;
                  // Byte 2, <7:0>

                byte yaw_down_13_8;
                  // Byte 3, <13:8>
                  // Bit 1 reserved for Yaw Slow Mode & Bit 0 reserved for Pitch Slow Mode

                byte roll_left_13_8;
                  // Byte 4, <13:8>
                  // Bit 1 reserved for Roll Slow Mode & Bit 0 reserved for Extension Connected

                byte pitch_left_13_8;
                  // Byte 5, <13:8>
                  // Bit 1&0 are unused, Bit 1 is left as 1, and Bit 2 is left as 0
              };

  As for the calibration data,
  uid_1,2 seem to be just a unique ID.
  crc32_msb,lsb is a crc32 of all calibration data except the checksum bytes.

              struct calibration_block {
                // Gyro values at 0 deg/sec to 16 bits of precision.
                u16 yaw_zero;
                u16 roll_zero;
                u16 pitch_zero;

                // Gyro values at "scale" deg/sec.
                u16 yaw_scale;
                u16 roll_scale;
                u16 pitch_scale;

                // Angular velocity of the above scale values in deg/sec divided by 6.
                // e.g. A value of 45 would mean the "scale" values represent the gyro at 270 deg/sec.
                u8 degrees_div_6;
              };

              struct calibration_data {
                // Calibration for "fast" mode.
                calibration_block fast;

                u8 uid_1;
                u16 crc32_msb;

                // Calibration for "slow" mode.
                calibration_block slow;

                u8 uid_2;
                u16 crc32_lsb;
              };

*/

/*
 * This function pointer informs the Arduino that a byte has been
 * written to one of the registers corresponding to the Extension.
 * Specifically, if you assign the function foo to this pointer and
 * you write yy bytes starting at the register address 04a400xx of
 * the Wiimote, then this library will call foo(xx, yy).  The bytes
 * are written to the global array wiimote_registers.
 *
 * Note that count will always be less than eight.  If you write
 * eight or more bytes to the Wiimote, this callback will be
 * invoked several times.
 */
void (*wiimote_receive)(byte offset, byte count) = NULL;

static void receive_bytes(int count) {

  Serial.println("");
  Serial.println("Recieving information...");
  delay(100);

  if (count == 1) {
    state = Wire.read();
  }

  else if (count > 1) {
    byte addr = Wire.read();
    byte curr = addr;

    Serial.print("Recieved bytes to register ");
    Serial.println(addr);
    delay(100);

    Serial.print("Incoming bytes... ");
    for (int i = 1; i < count; i++) {
      byte d = Wire.read();
      wiimote_registers[curr++] = d;

      Serial.print(d);
      delay(100);
    }

    Serial.println("");
    if (wiimote_receive) {
      wiimote_receive(addr, (byte) count - 1);
    }
  }
}

static void handle_request() {

  static byte last_state = EMPTY_BYTE;
  static byte offset = 0;  // apparently offset starts at 0x08? im not sure if this is true

  Serial.print("Handling request to register ");
  Serial.println(state);
  delay(100);

  switch (state) {

  default:
    if(last_state == state) offset += 32;
    else {
      last_state = state;
      offset = 0;
    }

    Serial.print("      Sending bytes: ");
    for(int i = 0; i < 32; i++){
      Serial.print(wiimote_registers[state+offset+i]);
      Serial.print(",");

      delay(50);
    }
    Serial.println("");
    delay(100);

    Wire.write(wiimote_registers + state + offset, 32);
    break;
  }

}

void setup() {
  Serial.begin(115200);
  Serial.println("WM+ tester");

  Wire.begin(inactive_address);
  Wire.setClock(CLOCK_FREQ);

  Wire.onReceive(receive_bytes);
  Wire.onRequest(handle_request);
  delay(5000);
}

void loop() {
}

How can i get the wiimote to acknowledge the response and send the activation byte to 0xFE?


text:
Vin pin vs USB vs Barrel connector: Wemos D1 R2
@Majenko says in the leading (19 Upvote) answer here not to use VIN and USB socket at the same time.

You must never ever connect VIN to a power source and connect the USB socket. That can destroy the USB port in your computer. There is zero back-powering protection on [LoLin v3 board] board.

I need to do diagnostics on my Wemos (LOLIN) D1 R2 V2.1.0 while it's connected via 9-12V barrel jack and the Vin pin connected to an L9110H H-bridge as an output (bridge input).
Does the Wemos (LOLIN) D1 R2 V2.1.0 (ESP8266) work like this as well? Would I be able to run diagnosics with Serial through my USB socket while running this setup?

So that means, that you only have one power source: the USB port, right?

Power source is from the barrel jack (9-12V) @chrisl

The D1 R2 uses the same power supply arrangement as the Arduino Uno (albeit with a better switching regulator for the 5V instead of the Arduino's basic linear regulator).
So it should be safe to use both the USB and the barrel jack at the same time.
The NodeMCU doesn't include a 5V regulator and doesn't have the power switching circuitry of the Uno / D1 R2, and thus is a completely different arrangement.

I have a "Uno-like" Wemos D1 R2 (almost said R2 D2 then! :) ) which also powers a NRF24 board connected to it. When I power it from the barrel connector the Wemos Wifi works but the NRF24 board won't communicate. When I power via USB everything works fine. Perhaps the onboard switching regulator you speak of does not have enough grunt to power both but a USB source does?


text:
How do I configure WEMOS D1 R2 Vin pin to output max voltage?
I am in need of 12VDC from my Wemos D1 R2. How do I configure the Vin pin to output the max (I think its 12VDC)?
board: Wemos D1 R2 V2.1.0 - ESP8266 (LOLIN D1 R2)
Pinout here in pictures below

Your Wemos D1 cannot generate a higher voltage than what is provided as input (via the barrel connector). It will only output 12V if you connect your own 12V power supply to the barrel connector.

you should learn how to use a mosfet as a switch in these types of situations.

After looking into it and seeing all the previous answers, I noticed the Vin pin can be used as an output but only up to the input from the barrel connector.
When using a 9V input to the barrel jack, the voltage difference between the ground pin and Vin pin was just under 9V. Similarly, when measuring the voltage difference when using a 12V supply, the multimeter reported just under 12V.
This is in line with @StarCat comment.

You cannot. You are misunderstanding, what that pin is. Vin means Voltage In. It's a voltage input, connected to a voltage regulator, which will regulate the provided voltage at that pin down to 3.3V for the Wemos to work with. It is not an output. The regulator cannot convert the 3.3V from the Wemos to 12V. That is not, what it is build for.
To get 12V you either need a separate 12V power source, or you need to buy a stepup/boost converter, which brings the 3.3V (or 5V, if you are powering from USB) up to 12V. For the latter, be sure, that the converter and the source, where you get the input voltage of the converter, can provide enough current for your use case.


text:
what is the use of Serial.begin(9600)
I mean what it does, why it is needed, what if we don't use it, similarly   for Serial.println(sensorValue).

Can you tell me what if i don't write it m program, what will happen

Serial.begin() initializes serial-port hardware and data structures so you can use the serial port.  See Serial.begin and Serial.println doc pages at arduino.cc for details, and see the answers to What is Serial.begin(9600)? for more background.

As the name suggests, serial.begin(9600) is a command you give to the Arduino to begin serial communication. I'm assuming you're a beginner. Anyway, as you might've seen on the IDE, there's a serial monitor. It outputs data that you configure it to output. It won't work unless you begin the serial communication using. The serial.begin(x); command. X is a variable baudrate, and I highly suggest going with 9600.
Okay, also, serial.println(sensorValue) is a command that the program gives to the Arduino to print the variable sensorValue to the serial monitor. Keep in mind that you can also print this through a Bluetooth module by connecting the tx to the rx and the rx to the tx pins. Hope this helped! :)

Serial.begin(9600); configures the UART interface and sets it to the right baud rate. If you don't to that you can't use the UART interface.
Serial.println(sensorValue); outputs the sensor value to the UART. If you don't use that you won't see the value of the sensor on the UART.
If you don't want to use the UART then don't use it. If you do want to use the UART then you must use the commands that control the UART.


text:
Can we code XBee more than once?
How many times we can rewrite code in
 XBEE, can we write code more than one or once a code is written it cannot be overwritten

code in XBEE ... it is unclear what you are referring to

@jsotola a friend of mine said you can only burn program once in Xbee and then you can never change it

He said Xbee are like old cd only one burn is allowed


text:
WiFiEsp not working on Software Serial, working fine on Hardware Serial
What I want to achieve
I want to connect to my wifi network using Arduino UNO and ESP8266 using WiFiEsp.h library over `SofwareSerial, since UNO doesn't have additional H/W serial.
What I am able to do already
I have a Mega, which I am able to connect to my wifi network(using ESP8266) using its hardware serial (RX1 and TX1), I've been following up this code example. Though it has code to deal with both cases( when H/W serial is present and when it's not) It doesn't seems to work on Software Serial on UNO, works perfectly on MEGA's H/W serial. I have made a little change in code as to set the Serial1 baudrate to 115200 as this seems to be supported by my ESP's firmware (1.54)
ERROR
[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module

What I've tried

Tried running Software Serial on MEGA on pins 10,11 and 6,7 (Rx,Tx) (Same Error).
Swapping Rx,Tx :P
Changing pins to 10,11 instead of 6,7 on UNO
Switching Baudrate to 9600 on UNO (no help)

Yeah, Not much, but it seems so straight forward I can't figure out what could go wrong. It seems like it can't communicate to ESP, but why?

Yes it looks like you can't talk to the ESP over Software Serial.  I have seen that sort of think mentioned on here a few times.  Have you tried hooking the ESP direct to your PC and see if you can read what it is saying.  You baud rate of the ESP looks like 9600, even though the default is 115200.

115200 is too fast for the uno/mega software serial. 9600 can be a problem. 57600 is usually stable. Make sure both ends use the same baud, It has to be rx>tx, tx>rx. Post the code from each.

If you're going to talk to your ESP at 9600 baud - and that's about the upper limit for SoftwareSerial - you need to first change the ESP board's baud rate to 9600 baud. It is probably at 115200 right now.
You can do that with either kind of serial. Even though SoftwareSerial can't receive at 115200, it can usually transmit (Uno -> ESP) that fast. You need to send it the command:
AT+UART_DEF=9600,8,1,0,0

If you do it with SoftwareSerial, the reply coming back from the ESP after changing its baud will be garbled because your serial terminal will still be listening at the faster speed. So at this point, change the speed of your terminal and send the command:
AT

The ESP should respond with
OK

If it does - and it probably will - you're all set and can continue using it at 9600 baud. If not, go back to 115200 baud on your serial terminal and try it again. (I've never had to do it twice).
Update:

I tried sending AT commands @ 115200, Its actually sending and receiving back well at 115200. Is this normal ?

With hardware serial, yes. The Uno's hardware UART can probably go at up to 4x that! But I've never had any luck receiving with SoftwareSerial at 115200; the most I could count on was 9600.

I liked your solution very much, before applying it I tried sending AT commands @ 115200, Its actually sending and receiving back well at 115200. Is this normal ?

i had a similar problem, followed the solution mention, changed the pin to 10,11 did the trick :)

authors: Данил Григорьев


text:
Serial Monitor (user input)
I'm trying figure out how to make the serial monitor printing specific content based on the user input. For instance if the user has typed '1' it should constantly print ("Hello") and when user has typed '2' it should print ("Bye") and vice versa. I'm new to programming, so I would be grateful if any can help me with this.
  String readString;

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

       void loop()
       {

         if(Serial.available()>0)

         {
            char c = Serial.read();
            readString +=c;
            delay(2);

                   if (c == '1')
                    {
                     delay(1000);
                     Serial.println("Hello");
                     c = "";
                    }

                                 if (c == '2')
                                  {
                                    delay(1000);
                                    Serial.println("Bye");
                                    c = "";
                                  }
             else
            {
             readString= "";
            }
          }
        }

Fix your code indentation.

Welcome to Arduino SE.  Be sure to take the tour to see how it works here:  https://arduino.stackexchange.com/Tour

You have most of what is needed but you have it structured incorrectly.
Because you want to print continuously, you need to split your program into 2 sections. One section deals with the serial input and the other with the printing.
The serial handling part checks if there are any characters to be read. If so, it simply stores the character that you read into a global variable.
The printing part executes every time through the loop and prints the value you want based on the global variable, which may, from time to time, change if something new arrives on the serial port.
This code is untested:
char cMode;

void loop()
{
  if(Serial.available())
  {
    char c = Serial.read();

    if (c == '1' || c == '2')
      cMode = c;
  }

  if (cMode == '1')
    Serial.println("Hello");
  else if (cMode == '2')
    Serial.println("Bye");

  delay(1000); // to slow down the loop?
}

You missing setup() loop here where you have to initialize serial communication. Check out my code, you will be find what I mean.

Try out this code. It will helpful for you.
char serialData;

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

void loop()
{
  if(Serial.available())
  {
    serialData = Serial.read();

    if(serialData == '1')
    {
      Serial.println("Hello");
    }
    else if(serialData == '2')
    {
      Serial.println("Bye");
    }
  }
}


text:
Blink 2 LEDs one at a time every x seconds
Newbie here - literally opened my Arduino about 3 hours ago. I have been able to code 2 LEDs to blink randomly, but what I want to do is have one of the two blink every 10 seconds.
My current code:
void setup() {
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
}

void loop() {
  // set 2 random on/off values
  byte on4 = random(2); //returns a random choice of 0 or 1
  byte on5 = random(2);

  //Write the value of each variable to the pins.
  digitalWrite(4,on4);
  digitalWrite(5,on5);
  delay(500);
}

I know I have to do something to the loops, I just can't figure out what.

Try out this code. It will helpful.
const int kPinLed = 4;      // LED at pin 4

void setup()
{
  pinMode(kPinLed, OUTPUT); // LED as OUTPUT
}

void loop()
{
  digitalWrite(kPinLed, HIGH); // LED ON
  delay(10000);                // 10 Sec delay
  digitalWrite(kPinLed, LOW);  // LED OFF
  delay(10000);                // 10 Sec delay
}

Choose if you want to keep pin 4 or 5.
Remove every reference to the other.
Move the declaration of the remaining pin outside of the loop, before the setup function. Ex: byte on4;
inside setup, assign a value (1 or 0) to the surviving pin. Ex: on4 = 0;
inside the loop, change the value of the pin. EX: on4 = !on4;
digitalWrite changes the state of the pins driving the LEDs.
Remove the one you do not want.
delay expresses how long the system waits, in milliseconds.
Change accordingly.
byte on4;

void setup() {
  on4 = 0;
  pinMode(4, OUTPUT);
}

void loop() {;
  on4 = !on4;
  digitalWrite(4,on4);
  delay(10000);
}

This should work, but I have not tested it.

You need to split the logic into 2 parts. One part will select the pin that you want to blink and the other will blink the pin.
I'll show how you do this using delay() but, clearly, it would be better to use the BlinkWithoutDelay methods of counting time so the processor can do something else. This code is untested and is set up so that you can just add pins to the ledPin array with no other changes and it will always work properly.
uint8_t ledPin[] = { 4, 5 };  // Arduino pins with the LEDs

#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))

void BlinkOne(uint8_t pin)
{
  digitalWrite(pin, HIGH);
  delay(5000);
  digitalWrite(pin, LOW);
  delay(5000);
}

void setup(void)
{
  for (uint8_t i=0; i<ARRAY_SIZE(ledPin); i++)
    setMode(ledPin[i], OUTPUT);
}

void loop(void)
{
  uint8_t thisPin = ledPin[random(ARRAY_SIZE(ledPin))];  // select which pin

  BlinkOne(thisPin);  // blink that pin
}


text:
Arduino Nano and ESP8266
I am trying to use Arduino Nano with ESP8266 (01). I tried to follow a lot of online tutorial with no result.
In particular this one http://www.martyncurrey.com/arduino-to-esp8266-serial-commincation/.
I think connections between Arduino Nano and ESP8266 are fine, when I upload the code on Arduino the red led on the ESP8266 turns on, I set the Arduino Monitor to 9600 BAUD and try to send command like "AT" but I got not reply from ESP8266. I also tried to switch to 115200 BAUD with no result too.
I don't if is something wrong or ESP8266 is damaged. Is there any tutorial that you may suggest?
Thank you.

The Serial Monitor's baud rate must match what you have in
Serial.begin(9600);

The EDP8266's baud rate is specified in the line
ESPserial.begin(9600);

and that is the one you need to change to try different baud rates with the ESP8266. The newer AIThinker firmwares default to 115200 baud, not 9600 baud.
Be warned, though, that SoftwareSerial isn't that great at 115200 baud - you tend to get some data corruption. It is best to change the baud rate to 9600 baud with
AT+CIOBAUD=9600

I'd also recommend investing in one of the ESP-01 programming boards from eBay. Make sure you get one of the ones with a switch on it that switches between programming and UART mode. Something like this one. It makes working with the ESP-01 much simpler - you can directly use your PC to set it up right for your system, and even upgrade the firmware (or program it directly with a sketch from the Arduino IDE if you install the right core) with minimum hassle.

many ESP's default to 74880 baud

Thank you a lot, I solved setting  ESPserial.begin(115200);


text:
'[Class name]' does not name a type in C++ Error
    #include <Servo.h>
Servo tilt, pan;

// Arduino pin numbers
const int SW_pin = 2; // digital pin connected to switch output
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output
int x, y;

// Second joystick pin numbers

const int SW_pinn = 4;
const int X_pinn = 3;
const int Y_pinn = 5;

void setup() {
  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);
  Serial.begin(115200); // setting serial baud rate tp 115200
  tilt.attach(7);
}

void loop() {
  x = X_pin; // defining the variable
  y = Y_pin;
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pin));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pin));
  Serial.print("\n\n");
  x = map(analogRead(X_pin), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec
  y = map(analogRead(Y_pin), 0, 1023, 900, 2100);
  tilt.write(x); // sets the servo position according to the scaled value
  pan.write(y);
  delay(5);

}

  x = X_pinn; // defining the variable
  y = Y_pinn;
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pinn));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pinn));
  Serial.print("\n\n");
  x = map(analogRead(X_pinn), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec
  y = map(analogRead(Y_pinn), 0, 1023, 900, 2100);
  tilt.write(x); // sets the servo position according to the scaled value
  pan.write(y);
  delay(5);
}

When I compile this code in the Arduino IDE it gives me the error
   arduino-builder/arduino-builder -compile -core-api-version 10611 -build-path /tmp/166416428 -hardware arduino-builder/hardware -hardware arduino-builder/packages/cores -tools arduino-builder/tools -tools arduino-builder/packages/tools -built-in-libraries arduino-builder/latest -libraries /tmp/358566849/pinned -libraries /tmp/358566849/custom -fqbn arduino:avr:uno -build-cache /tmp -verbose=false /tmp/358566849/sketch_may12a

Multiple libraries were found for "Servo.h"

Used: /home/admin/builder/arduino-builder/latest/Servo-1.1.2

Not used: /home/admin/builder/arduino-builder/latest/Printoo_Library-1.0.2

/tmp/358566849/sketch_may12a/sketch_may12a.ino:40:3: error: 'x' does not name a type

x = X_pinn; // defining the variable

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:41:3: error: 'y' does not name a type

y = Y_pinn;

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:42:3: error: 'Serial' does not name a type

Serial.print("X-axis: ");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:43:3: error: 'Serial' does not name a type

Serial.print(analogRead(X_pinn));

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:44:3: error: 'Serial' does not name a type

Serial.print("\n");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:45:3: error: 'Serial' does not name a type

Serial.print("Y-axis: ");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:46:3: error: 'Serial' does not name a type

Serial.println(analogRead(Y_pinn));

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:47:3: error: 'Serial' does not name a type

Serial.print("\n\n");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:48:3: error: 'x' does not name a type

x = map(analogRead(X_pinn), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:49:3: error: 'y' does not name a type

y = map(analogRead(Y_pinn), 0, 1023, 900, 2100);

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:50:3: error: 'tilt' does not name a type

tilt.write(x); // sets the servo position according to the scaled value

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:51:3: error: 'pan' does not name a type

pan.write(y);

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:52:8: error: expected constructor, destructor, or type conversion before '(' token

delay(5);

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:53:1: error: expected declaration before '}' token

}

^

exit status 1

In short, it saying that x does not name a type in this part of the code
x = X_pinn; // defining the variable
  y = Y_pinn;
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pinn));

Even though I defined it as a variable at the beginning... Any ideas?

You seem to have a chunk of your code twice.

The error is due to that the code is outside a function block e.g. loop().

If that is really your code then the errors are caused by one error.
As Majenko says lines 58 through to 71 should not be there.  It could be a cut and paste error when you wrote the post, but if it isn't that will cause a problem.
Some tips regarding your style that might help spot these faults in future.

Don't give variables a larger scope than they need.  See x and y, these don't need to be global variables.  You only use them within the loop() and you don't store the value between loops.  In fact lines (42 and 43) aren't needed which means you could define them as const int values on line 50 and 51.
Braces {} - I know people like to write braces in the java style now, because it saves a line of text and all those 2 bytes will eventually add up, but If you had always put braces on line on there own you would have seen the error because line 57 doesn't have an opening brace.
Encapsulate related data - I appreciate its only a little scrap program, but I would have placed the pin information in a class.  This would have let you have better variable names.

const PinInfo joystick1 (2, 0, 1);
const PinInfo joystick2 (4, 3, 5);


text:
How to light up all LEDs of a 7x5 LED matrix?
I want to light up all the LEDs of a 7x5 matrix with arduino uno. How can i do so?

Mark Smith has answered the question you asked.  If you didn't get an answer to what you want to know (and I presume you want to how to turn them on/off under program control) then edit the question to ask what you actually want to know.  Include LED part numbers and/or links, because LED current requirements will affect how best to do this; and how to treat common anode may differ from common cathode, and affects multiplexing if that's needed

You don't need an Arduino for that, and one will give you no benefit.
Connect all anodes to power, and all cathodes to the appropriate resistors, then ground.

The first thing I thought of when reading this answer was "I would have answered LEDs are not flammable; add some gasoline, enlight the uno with a blowtorch and then you will be able to light them up"


text:
serial write pixels of a bmp image
I'm looking for a way to read a 24 bpp bmp file from a SD cart, and than convert it to text and write it to the serial monitor.
So the output should look something like this:
R255,B255,G255
And that for each pixel

Start here: https://en.wikipedia.org/wiki/BMP_file_format

SO, I have to skip the header somehow, and then read the pixels one by one. But how can you do that in the arduino IDE?

The worst thing with a BMP file is it's backwards. It starts at the bottom of the image not the top. Really annoying. You need first to read the header and get the right data out of it to then know how to get the image data.

And what if you know the data out of the header already, so it's always the same size and format. Can you begin with reading the pixels directly?

Sure, if you know the offset, ordering, and packing already. Just seek to the right location and start reading.

And what will be a command to Read the data in the arduino IDE?

The same one used in all the SD card reading examples.

To read the pixels, start with this:
int32_t readNbytesInt(File *p_file, int position, byte nBytes)
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

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

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

    Serial.print("Initializing SD card...");
    if (!SD.begin(53)) {
        Serial.println("initialization failed!");
        while (1); // <- this is how you should block execution, not with returns
    }
    Serial.println("initialization done.");

    // Open
    bmpImage = SD.open("Circle.bmp", FILE_READ);
    textFile = SD.open("test.txt", FILE_WRITE);

    int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

    // Change their types to int32_t (4byte)
    int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
    int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
    Serial.println(width);
    Serial.println(height);

    int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

    if (pixelsize != 24)
    {
        Serial.println("Image is not 24 bpp");
        while (1);
    }

    bmpImage.seek(dataStartingOffset);//skip bitmap header

    // 24bpp means you have three bytes per pixel, usually B G R

    byte R, G, B;

    for(int32_t i = 0; i < height; i ++) {
        for (int32_t j = 0; j < width; j ++) {
            B = bmpImage.read();
            G = bmpImage.read();
            R = bmpImage.read();
            textFile.print("R");
            textFile.print(R);
            textFile.print("G");
            textFile.print(G);
            textFile.print("B");
            textFile.print(B);
            textFile.print(" ");
        }
        textFile.print("\n");
    }

    bmpImage.close();
    textFile.close();

    Serial.println("done write");
}`

Source: Arduino StackExchange Question: How to read bitmap image on arduino
The text output of this should be a file with an array of strings like R10G100B25, where R is the red component of the pixel, G is the green component and B the blue one. Work out how to print these to the serial output.
Note this is only compatible with the 24bpp format.

If you feel this answers your question, you may want to "accept" the answer What should I do when someone answers my question?

There is no "command" to read BMP files. They're files like any other. If you know how to read files on an SD card with an Arduino, then you know how to read BMP files. Interpreting the bytes of the file you just read is another matter. If the details of the BMP (width, height, depth, array offset, etc.) are known already, you may seek to the pixel array directly and begin parsing it (in your case, 3 bytes at a time in BGR order), remembering that BMPs are typically arranged bottom-to-top unless the height field in the header is negative.