text:
Can't understand this codes process
    void loop()
    {
    if ( Serial.available() > 0 )
      {
    static char input[inputLength];

    static uint16_t i;

    char c = Serial.read();

    if ( c != '\n')
      input[i++] = c;

    else
    {
      input[i] = '\0';
      i = 0;

      uint16_t array[80];
      uint16_t j = 0;

      if ( !strncmp(input, "SEND", 4) )
      {
        char* p = input + 4;

        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 16);

        ir_start(array);
        Serial.println("WURKS");
      }
    }
  }
}

Hello I can't seem to figure out what this code is doing. I know the main goal but I can't figure out the proccess. If someone could please make the code dumber for me I would appreciate it :). Full code is here since its hard to copy code: https://anonfiles.com/z6ldWff0pf/no_lib_ino

Sorry, I don't want to download some random file from a random site. Please include all relevant code into your question. Where did you get that code? I stumble across the while loop. I currently don't see how this would work, as `p = strchr(p, ' ') will set the pointer p to the next occurrence of a space character. Then the code tries to convert that space character as a hexadecimal string to an integer. Are you sure, that is code actually works?

Yes im sure it works :)

It's easier to follow if you indent it properly. I'll do that, and add comments as I go:
void loop() {
    if ( Serial.available() > 0 ) { // If there is something in the serial RX buffer

        static char input[inputLength]; // Create a working string to store data in
        static uint16_t i; // This is the current index in that working string

        char c = Serial.read(); // Read the next character from serial

        if ( c != '\n') // If it's not a "line feed" character...
            input[i++] = c; // then store it in the input string and increment i

        else { // Otherwise...

            input[i] = '\0'; // Terminate the string with a NULL to make it valid C
            i = 0; // Reset the index to 0 ready for next time

            uint16_t array[80]; // Create an 80-int array (temporary)
            uint16_t j = 0; // And an index variable

            if ( !strncmp(input, "SEND", 4) ) { // If the string starts with SEND
                char* p = input + 4; // create a "pointer" to the string that starts 4 characters in

                while ( (p = strchr(p, ' ')) != NULL ) // While there is a space somewhere in the string
                    array[j++] = strtol(p, &p, 16); // convert the first portion to a number, store it in the array, and advance the pointer to the next space.

                ir_start(array); // Send the array through IR
                Serial.println("WURKS"); // Tell us it worked
            }
        }
    }
}

So you see it receives data through serial and stores it, byte by byte, in input until it receives \n at which point it looks to see if it starts with SEND, then effectively "cuts off" the SEND by only considering everything after the SEND. Then it slices the remainder of the string up by looking for the next space each time and convert each portion to an integer which it stores in an array.
It then sends that array.

I was dumb, turns out it was converting the hex into a int. I sent the array through serial and looked at it.


text:
Arduino Object Oriented Programming
Can anyone send me a link tutorial about Arduino Object Oriented Programming? I want to learn Arduino, I am just a beginner.

A little information that is missing from the answers: OOP has a small overhead because of a some boiler plate and object instantiation. This overhead is so marginal on desktops, servers and even mobile devices that we usually don't even mention it. On the arduino however, with it's severe restrictions on memory and computing power and where every byte may count, this overhead can become noticeable. Depending on your use case, this might be something to consider.

Agreed with @Douwe - the Arduino is not the place to lean OOP because it is not an environment where OOP can really leverage its power.  OOP is a design strategy that came out of a need to simplify and abstract complex programs.  The arduino is so small and so simple that programs never really get that complex to begin with.  A desktop or mobile environment is a much better place to learn OOP because everything you're using in that environment are already objects - there's a whole framework to learn from.  On the arduino there's nothing except what you build.

"Arduino" is just plain old C++ with (in some cases) bits removed and some helper functions and classes.
For the smaller (lower powered AVR for example) there is no full STL in the C++ library, and some functions are of a reduced complexity (such as no floating point support in the printf family of functions by default).
For OOP you don't need to know anything "Arduino" - it's just C++. Any C++ OOP tutorial will teach you what you need to know for Arduino OOP.

Thank you, I will look into it

Have you programmed OOP before? For alot of projects you can get away with not knowing it.
I'll also point out that if you are just a beginner, I don't recommend starting off with OOP. Stick to simpler scripts (Trust me, OOP is a pain sometimes).
If you still INSIST on starting your arduino knowledge with OOP, look up "C++ classes" or "C++ OOP" as the default language that the arduino IDE uses is just a modified version of "C++"

Yes, I already done oop in different language like c#, I just want to familiarize the arduino c++ syntax.

http://paulmurraycbr.github.io/ArduinoTheOOWay.html really helped me understand what was happening. i had some previous oop expierence with java, but i still have a hard time using multiple files vs writing more methods in one file

I used OOP with C++ on an Arduino Due in an open source project.
Since I did not find any tutorila for the same the example might be helpful for You.
https://github.com/eschlot/Box-Joint-Jig-Control
W.r.t. the usability of OOP in embedded systems for scenarios like the above one there are plenty of good reasons to use OOP. A good example is the menu structure and the display control in the project.
Nevertheless from my experience it is important to understand the effects of automatic object creation and tentative memory reorganization to the behavior of real time systems. This is much less predictable with C++ then with plain C and can be a reason to not use OOP in any real time system.

source: Stack Exchange

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

sort: votes


text:
My Arduino IDE won't compile even simple sketches suddenly... How can I fix that??? this is the error message I get... I did work well at first!
private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/hardware -hardware /Users/daniellecomte/Library/Arduino15/packages -tools /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/tools-builder -tools /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/daniellecomte/Library/Arduino15/packages -built-in-libraries /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/libraries -libraries /Users/daniellecomte/Documents/Arduino/libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=0X2341_0X0042 -ide-version=10805 -build-path /var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660 -warnings=all -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.1.1 -prefs=runtime.tools.avrdude.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2 -verbose /var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/untitled1415726107.tmp/sketch_may19a/sketch_may19a.ino
/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/hardware -hardware /Users/daniellecomte/Library/Arduino15/packages -tools /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/tools-builder -tools /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/daniellecomte/Library/Arduino15/packages -built-in-libraries /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/libraries -libraries /Users/daniellecomte/Documents/Arduino/libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=0X2341_0X0042 -ide-version=10805 -build-path /var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660 -warnings=all -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.1.1 -prefs=runtime.tools.avrdude.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2 -verbose /var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/untitled1415726107.tmp/sketch_may19a/sketch_may19a.ino
Using board 'mega' from platform in folder: /Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21
Using core 'arduino' from platform in folder: /Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21
Detecting libraries used...
"/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR   "-I/Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino" "-I/Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21/variants/mega" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660/sketch/sketch_may19a.ino.cpp" -o "/dev/null"
Generating function prototypes...
"/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR   "-I/Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino" "-I/Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21/variants/mega" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660/sketch/sketch_may19a.ino.cpp" -o "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660/preproc/ctags_target_for_gcc_minus_e.cpp"
fork/exec /Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2/bin/avr-g++: no such file or directory
Error compiling for board Arduino/Genuino Mega or Mega 2560.

What update did you do just before it broke?

This indicates something has gone wrong with your Arduino AVR Boards installation. To make sure it has been fully uninstalled you need to take some drastic action. Be aware this is somewhat advanced and will remove all boards you have installed via Boards Manager:

Click the link on the line following File > Preferences > More preferences can be edited directly in the file. This will open the /Users/daniellecomte/Library/Arduino15 folder.
Delete all files and folders under the Arduino15 folder except for preferences.txt. Please be very careful when deleting things from your computer. When in doubt, back up!
Restart the Arduino IDE

Verify that you can now compile for your board before reinstalling any packages via Boards Manager.

You were absolutely correct... it works now...  many many thanks sir!

@DanielLecomte Since you agree this answer helped, please "accept" it so that the Stack Exchange software does not keep prompting for a good answer.

avr-g++: no such file or directory

Try downloading the IDE again. It looks like it has lost sight of where the compiler is. Preferably not a nightly build but one of the stable versions.

recommended is to install Arduino AVR Boards newest version through this simple steps, go to Tools -> Boards -> Board Manager -> Install "Arduino AVR Boards (X.Y.Z).

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


text:
Ethernet shield compatibility
Does anyone know if there is an Ethernet shield is compatible with the Arduino Ethernet shield (R3)? The R3 does not seem to be in production anymore and I need a replacement shield. Found some from Velleman, or maybe Ethernet Shield 2?

Arduino Ethernet Shield R3
Arduino Ethernet Shield 2
Velleman Ethernet Shield

Added links to the boards

No, it is not compatible.  It uses the ENC28J60 chip from Microchip, whereas the others all use the W5100 Wiznet chip. A very different chip.
You can use it if you refactor all your code to use the Ethercard library instead of the Ethernet library.
There are cheap Chinese (or other far east) clones of the Ethernet Shields, that use the W5100 (or a counterfeit copy) that people have varying amounts of luck with if you really need W5100 compatibility. I have one, but have had problems with it starting up properly sometimes and needs a bit of a kick with the reset button.

UIPEthernet library https://github.com/ntruchsess/arduino_uip for the ENC28J60. I didn't try it yet

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


text:
Issue sharing MISO with multiple RC522 RFID Readers
so for about the last 8.5 hours (almost non-stop) I have been trying to figure out one issue and I have exhausted every search I could possibly think of.
I'm building a puzzle that requires 5 RFID readers on the 1 Arduino, but for the sake of testing i've only been using 2.
Both readers work independantly, I can read out the UIDs of the little cards, which is all I need to do, but as soon as I make them share the MISO line, it simply stops printing anything out. I have no idea why.
Both readers have a common external 3.3v power supply and ground, they share all other lines but have an individual Slave Select. For testing I put both of their MISO cables into a breadboard which then leads into the Arduino on PIN 12, but it will only print out the UID when only ONE cable is plugged into the breadboard.
So is there something special I need to do to make this work? Is there a reason why the readers sharing a MISO line would break it? Even if i don't initialise one of them, just for the fact that it's plugged in still breaks it. I have tried setting one to HIGH and one to LOW, both to LOW, both to HIGH, nothing changes it.
Also, something else kind of confusing to me, it's meant to be active LOW to activate the SS, but when only 1 is plugged into the MISO line, it doesn't seem to matter which state it's in, it always prints...
I did a little bit of testing on my sketch just a moment ago and realised that when both are plugged into the MISO, the sketch will not progress past this line (which is also the first line in the loop)
if ( ! mfrc522_2.PICC_IsNewCardPresent())
        return;

I know everything else is working because it works when there is nothing else plugged into the MISO line, but I need it to work when all the others are plugged in too.
Please please please, if you have any idea, let me know.
I'm using the MFRC522 Library
EDIT:
This is basically the setup i'm using:

I'm not using any voltage translators or shifters, everything is 5v from the arduino except for the power to the readers which is coming from an external 3.3v supply like mentions previously.
I'm pretty certain that this is the datasheet for the RC522 i'm using, though i'm not sure if it's V1 or V2, but given the differences between them I don't think it matters:
http://www.nxp.com/documents/data_sheet/MFRC522.pdf
I don't know if they are able to share MISO lines like someone below said, I just assumed I could?

You are using a 5V arduino board without voltage translators, right? If so, you are out-of-specs for those modules, so this can make them malfunction

@frarugi87, that the readers work individually suggests that's not the problem.  Also, MISO is an input to Arduino and 3V3-system outputs to 5V-system inputs are said to work ok.

Jesse Mount, please edit question and specify voltages used; whether voltage translators/shifters are used; and the model numbers of the readers.  While SPI slaves typically use open-drain outputs so MISO can be wired together, some don't.  Without a model number, who can say?

@jwpat7 Surely you mean tri-state outputs, not open-drain outputs...

@Majenko, thanks, that's what I should have meant, regarding SPI.  Was thinking of IIC by mistake.

@jwpat7 Incidentally, I can find no mention of tri-state on MISO in the MFRC522 datasheet. Doesn't mean there isn't, but also doesn't mean there is...

Jesse Mount, perhaps look at the May 06, 2014 11:34 pm post on raspberrypi.org/forums and indicate here if your RFC22's match one of the 2 shown there (3rd link's bad).  That post also tells how to verify protocol is SPI etc.  Note, that thread implies your hookup diagram should be ok but if desperate you could use a multiplexer, eg a  74LS153 would let you select 1 line of 4

The one I have looks like the red one, but it's blue.
'Image Here'.
I'm sure it's using SPI as I have no trouble communicating with the Serial from the RC522. The only issue i'm having is using more than 1. If there is another RC522 plugged into the MISO line, it causes a communication error and prevents any data from being printed out on the Serial from either device, regardless of if the 2nd one is initiated or not, or at which logic state the SS pins are set at.

@jwpat7 actually the problem is not on the arduino side, but on the device side. You are sending 5V on pins which can support only 3.8V if I remember correctly (Vcc + 0.5). So you are working out of specs. If they happen to work even in these conditions ok, but you can expect strange behaviors from this setup. IMHO the first thing to do is to lower the 5V inputs to 3.3. Even a passive voltage divider can work. Then, when you are sure that you are working following the specs, you can modify something else

Where you able to figure anything out?  I'm having a similar issue.  http://arduino.stackexchange.com/questions/29494/connecting-saleae-logic-8-to-miso-pin-12-on-uno-3-w-nrf24l01-halts-program
Sounds like it might be the same type of problem.

I don't have reputation to comment but I want to thank Michael. His solution is perfect, I was stuck for days. So, Multi RFID with software SPI works as a charm!

I am joining this conversation VERY late, however maybe my answer can help someone who is just now looking into this.
I was able to get SEVEN RC522 readers working on one Arduino! My solution was very similar to your idea, except instead of the SS pin, I used the MISO pin.

If you look into how the pins work, all of them are outputs going from the master (Arduino) to the slaves (RC522), EXCEPT for the MISO pin which is an input going from the slaves to the master.
So I gave each RC522 scanner it's own MISO pin on the Arduino, and the rest of the pins were shared with all the scanners.
To get it working with the code, the simplest solution I found was to initialize a new RFID using the corresponding MISO pin each time I wanted to read from one of the RC522s.
This worked for the Arduino because you can set several of the digital pins as MISOs, however I haven't figured out how to get this working on a Raspberry Pi yet (without using a multiplexer) because the Pi has a few specific pins that are used for MISO.
I was using the old Sunfounder library. At the bottom of this page (http://wiki.sunfounder.cc/index.php?title=Mifare_RC522_Module_RFID_Reader), if you download the "RFID-RC522_test_experiment" zip file it will have the library included. Just copy and paste the RFID1 folder into your Arduino Library folder. Here is a simple tutorial for that library: https://www.sunfounder.com/learn/RFID_kit_V1_for_Arduino/lesson-29-rfid-entrance-guard-system-rfid-kit-v1-0-for-arduino.html
Here is some example code. It is pretty ugly but it worked.
void checkRFID(int i){
  if(i==0){
    rfid.begin(2,4,5,7,3,6);
  }
  if(i==1){
    rfid.begin(2,4,5,8,3,6);
  }
  if(i==2){
    rfid.begin(2,4,5,9,3,6);
  }
  if(i==3){
    rfid.begin(2,4,5,10,3,6);
  }
  if(i==4){
    rfid.begin(2,4,5,11,3,6);
  }
  if(i==5){
    rfid.begin(2,4,5,12,3,6);
  }
  if(i==6){
    rfid.begin(2,4,5,13,3,6);
  }
  delay(100);
  rfid.init();
  uchar status;
  uchar str[MAX_LEN];
  // Search card, return card types
  status = rfid.request(PICC_REQIDL, str);
  if (status != MI_OK)
  {
    return;
  }
  // Show card type
  rfid.showCardType(str);
  //Prevent conflict, return the 4 bytes Serial number of the card
  status = rfid.anticoll(str);
  if (status == MI_OK)
  {
    memcpy(serNum, str, 5);
    rfid.showCardID(serNum);//show the card ID
    Serial.println();
    Serial.println();
  }
  delay(100);
  rfid.halt(); //command the card into sleep mode
}

were you using an Arduino Uno or one of the other Arduinos?

How do you assign the digital pins as MISO? What library were you using for your SPI?

@sa_leinad I used normal Arduino Uno

@sa_leinad and I used sunfounder's libary. Here is their tutorial: https://www.sunfounder.com/learn/RFID_kit_V1_for_Arduino/lesson-29-rfid-entrance-guard-system-rfid-kit-v1-0-for-arduino.html
With their library you initialize the RFID by providing all the pins that should be used for each RC522 pin, like this: rfid.begin(irq,sck,mosi,miso,nss,rst); so it was as simple as changing the miso pin that i provided.
So for example I would do rfid.begin(2,4,5,7,3,6); to check one reader, then do rfid.begin(2,4,5,8,3,6); to check the next reader, and so on.

Michael, you're awesome!!! I had problems to connect 5 rfid-modules for a week and nothing helped. You fixed my problem, thank you. It works perfectly :)

@Michael did you connected only SCK,MOSI,SS,MISO? did you left unconnected IRQ and RST? SS pin is the SDA, correct?

Hey man, you saved my time. Thank you. I just wonder why that library isn't in libraries or another places?

In fact, the "trick" don't really came from the RFID LIB from Sunfounder, but from the "sub librairy" they re using, which is in the same folder and which is.... SoftSPI! This lib seems to act a bit like Software serial as it allow you to declare the PINS you want for SPI. Very interesting!!!!

Looking at the datasheet for the MFR522, it is not clear that it even supports multidrop SPI. It does not mention anything about the state of the SPI output pins when the chip is not selected. It also mentions that the chip uses the slave select line to detect what communication mode to use upon startup, but does not mention anything about how the chip will react to changes on that pin after startup.
Considering this, along with the fact to your library also does not seem to support connections to multiple MFR522, my guess is that this chip only supports a 1-to-1 SPI link.
Further, the SPI Timing characteristics in the datasheet specify how lon gthe SS (called NSS) must be high before communication can begin, but does not specify how long after SS goes low that the MISO goes tri-state, which would be an important thing to know if the chip did support multidrop SPI.
This is all backed up by the behavior you are seeing. If both chips are driving the MISO line simultaneously, then communication will not be possible when both are connected.
To support multiple MFR522 connections, you could possibly...

Use a multiplexing buffer to only enable SPI lines to one chip at a time. Downside is you would need Extra hardware, but upside is that you could probably use existing library intact by selecting the desired MFR522 before making the linrary calls.

Connect each MFR522 to different GPIO pins on the Arduino and bit bang the SPI to each chip independently. Upside is that you don't need any extra hardware and you potentially have a lot of flexibility on how you access the MFR522's. Downside is you will have to retrofit this bit-banged SPI into the library or use (or write) a different library.

I've seen this question come up many times over the years, so if you do choose option #2, please publish your code so others can use it!
An Experiment
I'd propose you do this to find out if your chips are compatible with multi-drop SPI...

Power up your system with a RC522 reader.
Check and make sure it works.
Disconnect the SS and MISO lines from the RC522 so they are no longer connected to the Arduino (or anything else). Leave the RC522 powered up - if it resets it might loose the auto-detected SPI configuration.
Use a jumper to connect the SS line to ground.
Connect the MISO line to ground with a 1K ohm resistor.
Use a multimeter to check the voltage on the MISO line.
Connect the MISO line to Vcc with the 1K ohm resistor.
Use a multimeter to check the voltage on the MISO line.
Connect the SS line to Vcc.
Repeat steps 3-6.

Report back the table of the 4 voltage readings you got and we should have our answer!

While the data sheet could be clearer, It is extremely unlikely that a chip which claims to be an SPI peripheral will fail to ultimately tristate the MISO line when not selected.  At any rate it should be easily tested.

I'd be inclined to agree, but a quick google search shows many people with the exact same problem - connecting a 2nd MFRC522 to the MISO line inhibits the 1st one from working. Also note that other NXP datasheets specifically mention tristate when available (ie the PCF85063BTL states that the SPI data out line is "is high-impedance when not driving". Without having a couple of the chips in hand to test there is no way to know for sure, but based on all the evidence I think most likely this chip does not support multidrop SPI.

If anyone has 2 of these in the NYC area, LMK and we can scope them up and get a final authoritative answer!

You don't need two of them to test that behavior - you can test it with one and a resistor.

"along with the fact to your library also does not seem to support connections to multiple MFR522" -- this doesn't seem to be true.  It contains example code for using multiple readers: https://github.com/miguelbalboa/rfid/blob/master/examples/ReadUidMultiReader/ReadUidMultiReader.ino

I do not know if every module has a pull-up resistance in sck and mosi if that is the case, it could be that for every module connected over teh lines the resistance gets lower. so maybe the module can not drop the voltage so there is no comunication. check with a multimeter the resistance between Vcc and MOSI it has to be around 4.7k generally.
hope this could help.

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


text:
How come some Arduino Nano pins (D3, D4, A3, A4, A6, A7) cannot be set high?
I made a sketch to switch on all digital and analog pins, and found out several pins did not work as expected. Note: I manually put a jumper wire from each digital and analog pin (one at a time) to a resistor, LED and GND pin.
What I noticed was that some pins did not work (D3, D4, A4, A6 and A7) and pin A3 was only lit about half intensity. I tried two different Nanos and they performed both equally (also pin A3 at half intensity).
I also tried the jumper wires directly touching the pins (without a breadboard in between, to rule out a breadboard problem). Same behavior (so the breadboard is ok).
My questions:

How come pins D3, D4, A4, A6 and A7 are not output VCC (3.3V) ?
How can I switch pins these pins on?
What is the reason pin A3 is blinking at half intensity?
How can I switch this pin fully on?
Bonus question: I used numbers, why are the pin names A0..A7 and D0..D12 not defined in Arduino IDE?

Test sketch:
const int NR_OF_PINS = 22;

int pins[NR_OF_PINS]   =
// 0  1  2  3  4  5  6   7   8   9  10 11   12  13  14  15  16  17  18  19  20  21
//D0 D1 D2 D3 D4 D5 D6  D7  D8  D9 D10 D11 D12 D13  A0  A1  A2  A3  A4  A5  A6  A7
 { 1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26 };

void setup()
{
  for (int n = 0; n < NR_OF_PINS; n++)
  {
    pinMode(pins[n], OUTPUT);
    digitalWrite(pins[n], HIGH);
  }
}

void loop()
{
}

A6 and A7 are analog only on classic Nano. 3.3 V on Nano?

Also D0 is pin 0, not pin 1.  Why are you bothering with an array?

@Juraj Ok, thanks, but the other analog pins work (except A3 partly).

your array is wrong. A0 is 13

@Majenko Yes, I accidentaly switched D0 and D1, I need an array because I want to use them in a loop (not for my test program but in my real program).

you use pin numbers not valid for Nano, you skip D3 and D4

@Juraj Yes I now notice that the numbering is already built in the functions pinMode and digitalWrite.

@Juraj I used this table: http://www.circuitstoday.com/arduino-nano-tutorial-pinout-schematics  there A0 is 19.

that are pins of the PCB. sorry A0 is 14. https://github.com/arduino/ArduinoCore-avr/blob/7a2e1cd815266fef3012a5c9b48f88d78551f838/variants/standard/pins_arduino.h#L56

@Juraj Thanks (nice that the built in LED has its own separate 'pin' )

@MichelKeijzers, with what Arduino board did you work until now? Because Nano is really only a small Uno.

You don't need an array, and your "base" pin is wrong - you start at pin 1, not pin 0. Also pins A6 and A7 can only be analog inputs, not digital outputs.
It's simpler to write:
void setup() {
    for (uint8_t i = 0; i < NUM_DIGITAL_PINS; i++) {
        pinMode(i, OUTPUT);
        digitalWrite(i, HIGH);
    }
}

void loop() {
}

That will work correctly on all Arduino boards regardless of the number of pins, since the board definition defines how many pins there are, and pins are always contiguously numbered from 0.

Thanks for the answer (btw, as a side question, I noticed there is not a NUM_ANALOG_PINS declared). Why not? (and also I thought analog pins could be used as digital pins, but not the other way around).

It's defined as NUM_ANALOG_INPUTS not NUM_ANALOG_PINS.

And the NUM_DIGITAL_PINS incorporates all the analog pins that can be digital inputs and outputs.

thanks (quite confusing to be honest, but at least now it's more clear). However, I rather have it this way... initially I thought my soldering work was a mess ;-)

https://arduino.stackexchange.com/a/36683/37523

@MichelKeijzers Well, an analog input may not be a physical pin. There are chips around that have temperature sensors (for example) built in that connect to the ADC MUX - so an analog input exists that connects to that sensor, but it doesn't have a "pin" as such - so calling them analog pins is a misnomer.

@Majenko ok clear (and sounds logical), I just have Arduino's and STMs ;-) ... Btw, just tested and in NUM_DIGITAL_PINS are all digital pins and analog pins [A0..A5] Pins A6 and A7 are analog only (or at least not in the range of NUM_DIGITAL_PINS).


text:
HC-05/Arduino receiving spam data
I connected everything properly. On the first try I did receive data as  I was supposed to. I then wrote some logic, re-uploaded and started receiving crazy spam.
My serial monitor is getting spammed with:

question marks if the variable is char, or;
25252525252 if the variable is int, or;
-1 if variable is String.

I'm monitoring at 38400 baud which is the same as my Serial.begin().
Any ideas ?
Code:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define MIN_PULSE_WIDTH 650
#define MAX_PULSE_WIDTH 2350
#define DEFAULT_PULSE_WIDTH 1500
#define FREQUENCY 50

char data = 'a';

void setup()
{
  analogReference(DEFAULT);

  Serial.begin(38400);

  pwm.begin();
  pwm.setPWMFreq(FREQUENCY);
  Serial.println("hello world");
}

void loop()
{
  data = Serial.read();
  Serial.println(data);
  Serial.flush();
  if (data == 'a'){
    pwm.setPWM(0, 0, pulseWidth(90));
  }
  if (data == 's'){
    pwm.setPWM(0, 0, pulseWidth(30));
  }
  delay(1000);
  //printing time in seconds
}

int pulseWidth(int angle)
{
  int pulse_wide, analog_value;
  pulse_wide = map(angle, 0, 180, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
  analog_value = int(float(pulse_wide) / 1000000 * FREQUENCY * 4096);

  return analog_value;
}

Thanks, that seems to work for the spam. I changed my variable to integer and tried sending a number. No matter what I send, I receive either 120, 128 or 248, multiple times. What's the deal ?

you should first connect the Arduino to Serial Monitor and learn the basics of Serial communication on examples

It does, but why is it the same no matter what character I send ?

I cannot use answer since I am not logged in, which I cannot do since I have my password on remember on another machine.
I changed print to write, however I still am getting weird results.
1 corresponds to "x?" (with a reverse question mark) and 2 corresponds to "???". I'm so lost.

has the BT module a baud rate 38400 baud?

Serial.read() returns -1 if no data is available. It doesn't wait for the byte. Test for -1 or use Serial.available() as any example does.
Replace Serial.print(data) with Serial.write(data) to get the data echoed back unchanged.


text:
Making a current GPS code run once, and only once, after the code is 'activated'
I have a GPS code that I need to run only once, but every different try gives me errors, including placing the whole code in void setup(). Is there any way that this code can be run just once? As of now, the code repeats itself, putting out data over and over again - I need just one set, right when the code is activated.
Here is the code:
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(3, 2);
Adafruit_GPS GPS(&mySerial);
#define GPSECHO  true
boolean usingInterrupt = false;
void useInterrupt(boolean);

void setup() {
  Serial.begin(115200);
  Serial.println("Adafruit GPS library basic test!");
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
  GPS.sendCommand(PGCMD_ANTENNA);
  useInterrupt(true);
  delay(1000);
  mySerial.println(PMTK_Q_RELEASE);
}

SIGNAL(TIMER0_COMPA_vect) {
  char c = GPS.read();
#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;
#endif
}

void useInterrupt(boolean v) {
  if (v) {
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  } else {
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

uint32_t timer = millis();
void loop() {                  // run over and over again
  if (! usingInterrupt) {
    char c = GPS.read();
    if (GPSECHO)
      if (c) Serial.print(c);
  }
  if (GPS.newNMEAreceived()) {
    if (!GPS.parse(GPS.lastNMEA()))
      return;

  if (timer > millis())
    timer = millis();

  if (millis() - timer > 2000) {
    timer = millis(); // reset the timer
    Serial.print("\nTime: ");
    Serial.print(GPS.hour, DEC); Serial.print(':');
    Serial.print(GPS.minute, DEC); Serial.print(':');
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    Serial.println(GPS.milliseconds);
    Serial.print("Date: ");
    Serial.print(GPS.day, DEC); Serial.print('/');
    Serial.print(GPS.month, DEC); Serial.print("/20");
    Serial.println(GPS.year, DEC);
    Serial.print("Fix: "); Serial.print((int)GPS.fix);
    Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
    if (GPS.fix) {
      Serial.print("Location: ");
      Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
      Serial.print(", ");
      Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
      Serial.print("Location (in degrees, works with Google Maps): ");
      Serial.print(GPS.latitudeDegrees, 4);
      Serial.print(", ");
      Serial.println(GPS.longitudeDegrees, 4);
      Serial.print("Speed (knots): "); Serial.println(GPS.speed);
      Serial.print("Angle: "); Serial.println(GPS.angle);
      Serial.print("Altitude: "); Serial.println(GPS.altitude);
      Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
    }
  }
  }
}

I've been trying to get this for a while, and I'm new to programming!

How is the code 'activated'?

Here's your sketch, modified to use my library, NeoGPS.  It is smaller, faster, more reliable and more accurate than all other libraries.
I added a waitForFix routine that, well, waits for the GPS to get a fix.  Then it calls printFix, just once:
#include <NMEAGPS.h>
#include <NeoSWSerial.h>

NeoSWSerial gpsSerial(3, 2);
NMEAGPS     GPS;
gps_fix     fix;

void setup()
{
  Serial.begin(115200);
  Serial.println( F("Run once!") ); // F macro saves RAM!

  gpsSerial.begin(9600);
  gpsSerial.println( F("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28") ); // RMC & GGA only
  gpsSerial.println( F("$PMTK220,1000*1F") ); // 1Hz update rate

  waitForFix();
  printFix();
}

void loop()
{
}

void waitForFix()
{
  uint8_t fixes = 0;

  do {
    if (GPS.available( gpsSerial )) {
      fix = GPS.read();
      fixes++;
    }
  } while ((fixes < 2) && !fix.valid.location);

} // waitForFix

void printFix()
{
  Serial.print( F("Time: ") );
  if (fix.valid.time) {
    if (fix.dateTime.hours < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime.hours);
    Serial.print(':');
    if (fix.dateTime.hours < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime.minutes);
    Serial.print(':');
    if (fix.dateTime.hours < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime.seconds);
    Serial.print('.');
    if (fix.dateTime_cs < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime_cs);
  }
  Serial.println();

  Serial.print( F("Date: ") );
  if (fix.valid.date) {
    Serial.print(fix.dateTime.day);
    Serial.print('/');
    Serial.print(fix.dateTime.month);
    Serial.print('/');
    Serial.print( fix.dateTime.full_year() );
  }
  Serial.println();

  Serial.print( F("Fix status: ") );
  if (fix.valid.status)
    Serial.print( (int) fix.status );
  Serial.println();

  if (fix.valid.location) {
    Serial.print( F("Location: ") );
    Serial.print( fix.latitude(), 4 );
    Serial.print( F(", ") );
    Serial.println(fix.longitude(), 4);
  }

  if (fix.valid.speed) {
    Serial.print("Speed (knots): ");
    Serial.println( fix.speed() );
  }

  if (fix.valid.heading) {
    Serial.print( F("Angle: ") );
    Serial.println( fix.heading() );
  }

  if (fix.valid.altitude) {
    Serial.print( F("Altitude: ") );
    Serial.println( fix.altitude() );
  }

  if (fix.valid.satellites) {
    Serial.print( F("Satellites: ") );
    Serial.println( fix.satellites );
  }
}

The NeoGPS library waits for a complete batch of sentences, because the speed is in one sentence (RMC) and the altitude is in another sentence (see this table).  NeoGPS provides complete "fixes", as assembled from all the sentences your GPS device sends.  The fixes are available once per second, or whatever you have configured your device to provide.
You may also notice that I used another library I maintain, NeoSWSerial.  SoftwareSerial is very inefficient because it disables interrupts for long periods of time.  This can interfere with other parts of your sketch or other libraries.
If you can put the GPS on pins 8 & 9, AltSoftSerial would be even better.  It only works on those two pins.
Your original sketch uses 12124 bytes of program space and 1031 bytes of RAM.
The NeoGPS version uses 10680 bytes of program space and 446 bytes of RAM.  A significant savings!

But when trying to verify this sketch, I still get the same error, that the timer wasn't declared.

Sorry, that wasnt the error, got mixed up.

The error says;    #include <NeoSWSerial.h>
                     ^

compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.

Did you download and install NeoSWSerial from the link? It's a standard Arduino library that you download, unzip, and copy the NeoSWSerial-master directory to a new Arduino/Libraries/NeoSWSerial subdirectory.

Put everything from your void loop() into your void setup. Put them AFTER the original setup and you should be good to go.
DO NOT DELETE THE VOID LOOP!! ONLY KEEP IT EMPTY!!
Here, try this:
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(3, 2);

Adafruit_GPS GPS(&mySerial);

#define GPSECHO  true

boolean usingInterrupt = false;
void useInterrupt(boolean);

void setup()
{

  Serial.begin(115200);
  Serial.println("Adafruit GPS library basic test!");

  GPS.begin(9600);

  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);

  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);

  GPS.sendCommand(PGCMD_ANTENNA);

  useInterrupt(true);

  delay(1000);

  mySerial.println(PMTK_Q_RELEASE);

  if (! usingInterrupt) {

    char c = GPS.read();

    if (GPSECHO)
      if (c) Serial.print(c);
  }

  if (GPS.newNMEAreceived()) {

    if (!GPS.parse(GPS.lastNMEA()))
      return;

    if (timer > millis())  timer = millis();

    if (millis() - timer > 2000) {
      timer = millis(); // reset the timer

      Serial.print("\nTime: ");
      Serial.print(GPS.hour, DEC); Serial.print(':');
      Serial.print(GPS.minute, DEC); Serial.print(':');
      Serial.print(GPS.seconds, DEC); Serial.print('.');
      Serial.println(GPS.milliseconds);
      Serial.print("Date: ");
      Serial.print(GPS.day, DEC); Serial.print('/');
      Serial.print(GPS.month, DEC); Serial.print("/20");
      Serial.println(GPS.year, DEC);
      Serial.print("Fix: "); Serial.print((int)GPS.fix);
      Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
      if (GPS.fix) {
        Serial.print("Location: ");
        Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
        Serial.print(", ");
        Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
        Serial.print("Location (in degrees, works with Google Maps): ");
        Serial.print(GPS.latitudeDegrees, 4);
        Serial.print(", ");
        Serial.println(GPS.longitudeDegrees, 4);

        Serial.print("Speed (knots): "); Serial.println(GPS.speed);
        Serial.print("Angle: "); Serial.println(GPS.angle);
        Serial.print("Altitude: "); Serial.println(GPS.altitude);
        Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
      }
    }
  }
}

SIGNAL(TIMER0_COMPA_vect) {
  char c = GPS.read();

#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;

#endif
}

void useInterrupt(boolean v) {
  if (v) {

    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  } else {

    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

uint32_t timer = millis();

void loop()                     // run over and over again
{
}

Dat Ha...  After uploading this code, i recieved the error ' timer' was not declared in this scope, in this line if (millis() - timer > 2000) {

Do you know what might be causing this??

void setup is a loop that run once. void loop is a code that runs and repeat. Open a blank sketch a see what happens. If it works, please consider accepting the answer to mark this question as resolved.

Well, the error tells you that the variabele 'timer' was not declared... Which basically means you're missing your declaration of the timer variable: 'uint32_t timer = millis();'

authors: เพ็ญพยอม คํานวณ


text:
Set Low Power Level or Enable Pin of stepper driver, so stepper does not get hot
I am using the code below with this stepper shield:
https://www.dfrobot.com/wiki/index.php/Stepper_Motor_Shield_For_Arduino(DRV8825)_SKU:DRI0023
Everything works, but tends to get hot (62.3 Celsius) while holding in idle position. What I understood so far, to reduce the temperature I can:

Set enable pin only when I need to turn the motor, but loose my position.
I can use what the driver manual describes as low level. Which I did not entirely understand.

If I set the enable pin to low by doing digitalWrite(M1en,LOW); do I put the stepper in low power mode or do I switch off the power to the stepper ?

I could only enable the stepper (if by setting it to LOW or HIGH I enable, disable) when I need it. Which would be the best as I understood it.

Where in my code below would I have to add the digitalWrite LOW,HIGH to achieve this ? Or do I need to just set it LOW (for low power mode).

Or is there a much better way I don't know about.

Code:
const int dirPin = 4;
const int stepPin = 5;
const int M1en = 12;

int speed = 200;    // desired speed in steps per second
int steps = 0;      // the number of steps to make

void setup()
{
  pinMode(dirPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
  digitalWrite(M1en,LOW);// Low Level Enable
  Serial.begin(9600);
}

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

    if(isDigit(ch)){             // is ch a number?
      steps = steps * 10 + ch - '0';        // yes, accumulate the value
    }
    else if(ch == '+'){
      step(steps);
      steps = 0;
    }
    else if(ch == '-'){
      step(-steps);
      steps = 0;
    }
    else if(ch == 's'){
      speed = steps;
      Serial.print("Setting speed to ");
      Serial.println(steps);
      steps = 0;
    }
  }
}

void step(int steps)
{
  int stepDelay = 1000 / speed;  //delay in ms for speed given as steps per sec
  int stepsLeft;

  // determine direction based on whether steps_to_mode is + or -
  if (steps > 0)
  {
    digitalWrite(dirPin, HIGH);
    stepsLeft = steps;
  }
  if (steps < 0)
  {
    digitalWrite(dirPin, LOW);
    stepsLeft = -steps;
  }
  // decrement the number of steps, moving one step each time
  while(stepsLeft > 0)
  {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(1);
    digitalWrite(stepPin,LOW);
    delay(stepDelay);
    stepsLeft--;      // decrement the steps left
  }
}

The product page you gave has a link to the DRV8825 datasheet.
Reading this, it is clear that the enable pin(s) comlpetely disable the H-Bridge that drives the motor coils. This is low power mode. It'd doesn't mean low, but non-zero holding current. The driver only supports enabled and disabled.
If your steppers are getting hot, perhaps the current being supplied by the driver is too high. The maximum drive current is set by the current-sense resistors attached to the driver chip. These may not be easy to change. To decrease the maximum current, you increase the current-sense resistor.
The product page notes that the shield has the current set at 1.6A per coil.


text:
How to insert a power button on Arduino Nano
I've an Arduino Nano to which a Micro Servo 9g is connected. The Arduino board and consequently the servo are powered by a USB powerbank connected to the board with a USB mini cable.
My question is: Is there a way to insert a power switch so I can turn on/off the board without plug/unplug the USB (that now is the way I use) ?
I was thinking to cut the USB cable and work with the positive of it but if someone has an alternative or any tips I'd really appreciate it. Thanks!
EDIT: If is needed I could make a wiring diagram.

Cutting a usb wire would be the easiest. Otherwise you'd have to cut traces in the pcb and attach wires. Not recommend for beginners. You can actually buy usb cable with a switch.
Another alternative would be to put the microcontroler in sleep mode and have it use very little power.

Thanks for your reply. If Arduino is in sleep mode does the servo still work?

I think that if you deattach the servo in software it doesn't use that much power. Otherwise you'd have to connect power to the servo using a transistor, so you can power it down during sleep.

As Gerben said, you can buy a cable with a switch built in.


text:
Is it possible to make 4hz readings with the DS18S20 temperature sensor?
My current code that doesn't convince me:
#include <OneWire.h>

int DS18S20_Pin = 3; //DS18S20 Signal pin on digital 3
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
//Temperature chip i/o
OneWire ds(DS18S20_Pin);  // on digital pin 3

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

void loop(void) {
  if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        float temperature = getTemp();
        Serial.println(temperature);
    } //just here to slow down the output so it is easier to read

}

float getTemp(){
  //returns the temperature from one DS18S20 in DEG Celsius

  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
      //no more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44,1); // start conversion, with parasite power on at the end

  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad

  for (int i = 0; i < 9; i++) { // we need 9 bytes
    data[i] = ds.read();
  }

  ds.reset_search();

  byte MSB = data[1];
  byte LSB = data[0];

  float tempRead = ((MSB << 8) | LSB); //using two's compliment
  float TemperatureSum = tempRead / 16;

  return TemperatureSum;

}

the outcome of few seconds of recording:
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31

EDIT: I inserted the suggestion of @frarugi87 and I inserted the sensor in my pants to test it:
22.50
22.50
22.50
23.69
23.69
23.69
23.75
23.75
23.75
23.75
23.75
23.75
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
24.00
24.00
24.00
24.06
24.06
24.06
24.19
24.19
24.19
24.25
24.25
24.25
24.31
24.31
24.31
24.44
24.44
24.44
24.50
24.50
24.50
24.56
24.56
24.56
24.56
24.56
24.56
24.62
24.62
24.62
24.69
24.69
24.69
24.75
24.75
24.75
24.81
24.81
24.81
24.87
24.87
24.87
24.87
24.87
24.87
24.94
24.94
24.94
25.00
25.00
25.00
25.00
25.00
25.00
25.06
25.06
25.06
25.12
25.12
25.12
25.12
25.12
25.12
25.19
25.19
25.19
25.25
25.25
25.25
25.25
25.25
25.25
25.31
25.31
25.31
25.37
25.37
25.37
25.44
25.44
25.44
25.44
25.44
25.44
25.50
25.50
25.50
25.50
25.50
25.50
25.56
25.56

I still find the change of temperature slow

I would expect some variations in temperature, but I would not say that is a problem caused by the 4Hz readings. You can test my assumption by reading every 3 seconds, does the temperature value change or is it still the same?
I see two potential problems:

your DS1820 is defect.
from your code I assume that you use parasitic power. In that case the chip consumes power from the data wire ( one wire ;-) ) through a pull up resitor (~4.7 kOhms). If you do not provide a special handling, to drive more current while the DS1820 is converting or copying data to EE or from EE memory to the scratchpad, then there will be (most likely) voltage drops.
Then the Temperature conversion will not happen and you read the old value from the scratchpad in your read cycle.

You can test point 2 by adding VCC to the DS1820, and do not use parasitic power.
If that is your problem, you can fix it with a switching FET Transistor, that provide more current (see DS1820 Datasheet from Maxim) or by using an additional VCC wire.

There's no variation because it's just measuring the room temperature.

But the DS18S20 produces heat. So a change of +-0.01 should be probable. Your second time series is very interesting. There are blocks of  some measures (3-5) with the same value.  Why isn't it increasing continously. It seams that the conversion speed is too high. The first jump is over 1.07 degree, followed by 2 times 0.06 degree, followed by 0.07 degree. Then 2 times 0.6 degree, followed by 0.07 degree and so on. That may be by coincidence but I think it is interesting. Perhaps it's a matter of resolution or conversion time. It's time to reactivate my old DS18S20 and uv your question. ;-)

I hope it will be the same with your sensor

The rate of change of the temperature reading depends on the thermal properties of the sensor package, not on the rate at which you read it. The less expensive, plastic packaged sensors that most of us use will be the slowest to respond to change just because that is the thermal nature of the plastic. Do note that the ground pin of that package has more influence than the package itself, so do your best to ensure the ground pin is exposed to the temperature you're trying to measure, or is at least thermally insulated from the surrounding air, unless the air temperature is what you are trying to measure. If you need faster response to temperature change, you'll need to pay attention to keeping the entire device at or close to the temperature of interest and insulated from surrounding temperatures.

Is it possible to make 4hz readings with the DS18S20 temperature sensor?

Yes, but only at 9-10 bits resolution. See Table 2. Thermometer Resolution Configuration. At full resolution, 12 bits, the conversion time is 750 ms. With the commands, reset, etc, this gives just over 1hz.
I guess this also gives you a hint on what to fix in your sketch.
Cheers!

unfortunately no, this doesn't give me an input

for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
}
this is the part to modify? It's the only option I see at the moment

no I think it's here the hot spot
}
int16_t raw = (data[1] << 8) | data[0];
if (type_s)
{
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10)
{
// "count remain" gives full 12 bit resolution
raw = (raw & 0xFFF0) + 9 - data[6];
}
}
else
{
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw & ~7;
else if (cfg == 0x20) raw = raw & ~3;
else if (cfg == 0x40) raw = raw & ~1;

Not sure if this is the only problem, but when shifting bytes you will lose the msb. This can be solved by casting the variable to an int.
And moreover you don't need the two variables MSB and LSB.
Try to correct it with this:
float tempRead = ((((int)data[1]) << 8) | data[0]); //using two's compliment

The temperature change is still slow when I apply the finger.

@GabrieleGiordano Ok, so it is slow. But.. Is it accurate? I mean, after a lot of time, is the reading correct or not?

I suppose yes. Seems also in other fields the reading of skim temperature has a low variance

If it is accurate, then the problem can be a bad thermal coupling or a high thermal capacitance, even if it seems too high. Can you make measurements at "full speed" and see if the time is the same? Can you try to make a measurement, leave it running for some seconds *just tu see the trend) and then reset the device? If it is a software problem you will see a "jump" in the temperatures, if it is a thermal problem nothing will change the trend

"and see if the time is the same?" which time?


text:
Can I use two sensors with different baud rate without problems on arduino?
One sensor has a baud rate of 115200, the other 9600. I think this will create problems in the serial because I can only choose one baud rate.
What do you think?
The first sensor is the pulse sensor, while the other is the gsr sensor by grove.
Link: http://pulsesensor.com/
Link 2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor

Do you have a link to the pulse sensor? And do you mean this (http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor) "Grove GSR sensor"?

details updated

I think you have totally misunderstood the example code. Both of the examples you linked to used the Serial port to send data to your PC, not the sensor. For that purpose just choose one rate (eg. 115200).

You can only have one sensor on one serial port, and the baud rate is set on the serial port.
So as long as you have two serial ports, or SoftwareSerial ports (I wouldn't, it causes more problems that it solves - get a board with multiple UART interfaces) then yes you can have two baud rates.

ohh I'm disappointed I didn't consider this before

I don't understand if genuino 101 has two serials or just one "Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins are connected to the Serial1 class."

I would assume the Serial port is connected direct to USB (CDC/ACM) and Serial1 connected to the GPIO headers. The 101 is all a bit of a mystery since it's all based around an Intel module that no one outside of Intel knows much about.

if you are using multiple sensor use Arduino Mega board because it have 3 serial ports and Software Serial on UNO supports max baudrate of 115200 but sometimes this max baudrate will create the issues and you will receive the garbage

Yes I read about the Mega and I wondered if it's the only one in the market with this advantage. I'm wondering what does Intel and Raspy offer

You might be better off looking at Teensy or chipKIT rather than heavy Linux embedded computers.

There seems to be a misunderstanding. I've checked the particular sensor (http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor). And it uses analogread. Probably, the two code-examples would use different baud-rates for transmitting "log info" to the USB connection. Just using the same baudrate for both logging is possible (which means you can use both sensors).

seems that now I just need to search a way to plug them on the breadboard without using the grovehat, or I can use 3 on 4 pin of the digital port of the hat? The pulse sensor has 3 pins and not four.

One sensor has a baud rate of 115200, the other 9600. I think this
  will create problems in the serial because I can only choose one baud
  rate.

Why do you think the sensor has a baudrate?

Both the sensors seem to use the "serial connection" of the Arduino to log their information.

What do you think? The first sensor is the pulse sensor, while the
  other is the gsr sensor by grove. Link: http://pulsesensor.com/ Link
  2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor

I think it'll work fine.

Looking at the facts of your sensors, the pulse sensor does have some kind of weird low-level timing/ADC access. But your Grove GSR sensor can basically be read out through an analog input.
So what to choose?
You could choose 9,6k or 115k2 (9600 or 115200). It wouldn't make all that much difference. 9600 or 115200 will work fine. 115200 is a lot faster, but for debugging purpose 9600 is used, since it's often default and (often) more reliable.
Wrapping up
I don't think there is an issue with the two serials. You can easily log both messages to the same serial output.
Try using 115200 since timing is essential in your case, you want your sensor to be response/fast.
They do both use the same analog to digital converter on your board. An Arduino can't check both sensors at the same time. But by switching between them very fast, you will get a resolution that's good enough.

I will try to use the GSR with 115k. Do I change also the serialBegin of the GSR code to make it work or it's enough to change it just in the Serial monitor?

The code and monitor need the same baudrate.


text:
Setting Up a JavaEE app on an Arduino Yun Board
I'm looking for some reference material to start on a project I'd like to do.
I have an Open House at my school. My group project has been to create a little timesheet app using JavaEE. I just started looking for how to do this and if I can. But I would like to wow people a bit by setting this up using an Arduino Yun board. I know it has WiFi and I'm pretty sure I can run Linux on the little guy.
Any help would be greatly appreciated.

Sorry, forget it. 64Mb ram, 16Mb flash what the Yun has.
Java EE is magnitudes bigger (and bugger) than that.
You might try with Java SE embedded, the smallest profile might fit to 11Mb:
http://www.oracle.com/us/technologies/java/oracle-javase-embedded-ds-365290.pdf
and then you can roll your own web server.
(Personal comments: For little timesheets JavaEE is overkill, for anything modern JavaEE is obsolete - consider modern Java micro web frameworks, which offer magnitudes better performance than JavaEE).
What you can try is Raspberry PI, which works well with network, and Java (SE).
Not that well but also Java EE works: https://blogs.oracle.com/theaquarium/entry/glassfish_4_on_the_raspberry

Unfortunately we have to use JavaEE thank you for your support. I have acquired a Raspberry Pi 2 I will post my results :)

I am developing enterprise software for 20+ years, and I know that many companies still stick to JavaEE (for some really really awkward and twisted reasoning). On the other hand, many professionals say that JavaEE is obsolete for 10+ years, basically since the advent of Java microframeworks and full stack frameworks. Which are quite mature, and surprisingly good. :)


text:
Does the reset button work when not powered?
I'm working on a project and my dad hit the reset button on my Arduino board, unknowingly. If it wasn't connected to any power source or computer, did it still reset? Do I have to upload my code to the board again? Or does the board need power to be reset?

Was the board turned off?  The reset button doesn't do anything if no power is attached to the board.

The reset on an Arduino does not erase anything. It merely restarts execution of an already uploaded program. Also the AVR needs to be powered on for it to realize whether it has been reset.
Every time you power on an Arduino it automatically starts code execution from the beginning of the program in the flash memory.

Everything in RAM (non persistant memory) will be erased. progmem/flash and EEPROM are persistant and will not be erased.

you can't erase RAM any more than you can erase a projector screen; electrons+photons erase themselves.

Actually, pressing RESET doesn't erase RAM. It resets the CPU and sets all SFRs to power-on defaults, but the RAM remains the same. It's the code that is added to the start of your program (crt0.o) that erases the BSS area and copies any other defaults into place from flash. The rest of RAM continues to hold what was in there before. Of course, with no power applied it's all rubbish anyway, since nothing is happening.


text:
Thingspeak Library returns 0 using ESP8266 on Arduino
I have tried using the thingspeak-arduino library and tested some of the examples:
#include <WiFi.h>
#include <WiFiClient.h>
#include <SPI.h>
#include <ThingSpeak.h>
char ssid[] = "Benok4G";    //  your network SSID (name)
char pass[] = "password";   // your network password
WiFiClient  client;

unsigned long myChannelNumber = 344468;
const char * myReadAPIKey = "xxxxxxxxx";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  WiFi.begin(ssid, pass);
  ThingSpeak.begin(client);
}

void loop() {
  // put your main code here, to run repeatedly:
  float voltage = ThingSpeak.readFloatField(myChannelNumber, 1, myReadAPIKey);

  Serial.print("Latest voltage is: ");
  Serial.print(voltage);
  Serial.println("V");

  delay(30000);
}

When i run this code, I get this on the Serial Monitor.

Why is it 0.00? It's supposed to be 24.0
http://184.106.153.149/channels/344468/fields/1/last
Did I do something wrong? I am very frustrated because I've tried a lot of methods already just to fetch the data from ThingSpeak to my Arduino using ESP8266. I can send but when receiving I am really lost and confused.

Are you sure that those libraries support ESP8266 over AT commands? Is WiFi.begin even successful?

I have a similar problem. Arduino Mega + Exp8266 connected to Serial1 (RX1, TX1). With WiFiEsp.h library, it connects to the router but no reading on thingspeak, always timeout 605. I wonder if you can post the working program. Thanks and good job.

#include <WiFi.h>

From the WiFi library reference page:

With the Arduino WiFi Shield, this library allows an Arduino board to connect to the internet.

From the Arduino WiFi Shield product page:

It is based on the HDG204 Wireless LAN 802.11b/g System in-Package. An AT32UC3 provides a network (IP) stack capable of both TCP and UDP.

But you're not using an Arduino WiFi Shield or anything compatible. You're using an ESP8266 which is completely different. Thus you can't use the WiFi library for your project.
Instead you will need to use the appropriate ESP8266 library. If you are programming the ESP8266 directly that will be the ESP8266WiFi library, which is bundled with the ESP8266 core for Arduino. If you are using the ESP8266 as a WiFi module controlled via AT commands that will be the WiFiEsp library

Thank you for your response. I have solved my problem. I included the WiFiEsp library and set the SoftwareSerial Serial1(6, 7); // RX, TX and set the baud rate at 9600. Works like charm. Thank you again.

Just a follow up. It worked but sometimes I get "Timed Out" response and Sending the data takes too long than doing AT commands. Is this normal?


text:
Problem with shift register
I have a problem with the shift register 74HC595.
The sketch I use is able to enable a specific led (8 are connected).
When I enable led 0 to 7 it behaves like normally (they switch on when I enter the numbers).
However, for the led connected to pin 15 (other side of the ic, see layout) it behaves differently.
 When I switch this led on, ALL leds go off. When I retry, nothing happens. When I enable another led, after a short time (but can be seconds) the led for pin 15 is emitting light together with all others which where already enabled.
This seems like a malfunction in the IC (I checked already another led, another cable, another resistor). The only think I haven't checked is moving the IC to another position of the breadboard (that would take a lot of time since I have to rewrite everything). Is it possible I missed something or is the shift register broken?
The code to switch on a led:
void updateShiftRegister()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  digitalWrite(latchPin, HIGH);
}

where leds are the indices of the leds (0..7).

Please edit your question to include a Minimal, Complete, and Verifiable example of code, instead of just a snippet.  Also, if  “led 0 to 7” refers to 8 different LEDs (0 1 2 3 4 5 6 7) you will need to specify which pin each of those 8 LEDs are connected to.  The question seems to say you have a ninth LED attached to Q0 on pin 15.

Showing the wiring (and also a photo of your breadboard circuit) may help invesitgae on this issue. Also, I'd be curious to see code that sets leds value and how leds variable was declared (unsigned Vs. signed may have surprising effect on your code).

Thanks for all remarks, however, what I try is finding another project (instruction) for using it and check if I have the same problem; if still do, I can post it (and make a minimal example

You cannot directly give an index (0..7) to a shift register if you want the index to represent the LED number to be switched on.
You have to build a table similar to the following:
byte led[8] = {
0b00000001,
0b00000010,
0b00000100,
0b00001000,
0b00010000,
0b00100000,
0b01000000,
0b10000000
};

and later . . .
shiftOut(dataPin, clockPin, LSBFIRST, led[leds]);

where leds is a number 0..7

Or more cheaply shiftOut(dataPin, clockPin, LSBFIRST, bit(leds));

Nice. I knew there had to be an even quicker way for such a simple mapping.

Thanks ... my example uses the shiftOut, but I will find another example and check if it also gives problems and than post the layout/full code if needed.

Somehow it seems to work, after using another scheme (although it looked exactly equal). So I'm really not sure why the problem existed; now it seems to work ... wondering if I should remove the question since  there might be useful information for others (regarding the table and shiftOut function.


text:
Serial print message results in gibberish
I'm trying to print messages to the serial monitor, and all I get is some unreadable format.
Looping Serial.println("Wait...!"); gives me the following results:
ö’ö’ƒÕ•¬ƒ´¼Õƒö“ƒ²ƒƒƒ¬‘¼¬Õ”’“ƒ¬•

Why is it unreadable, and how do I make it print a readable format?

By printing at the same baud rate that you are reading at?

Please show the code that initializes the Serial communication (Serial.begin(...)). Then show the settings of your serial monitor. I think just doing that should give you the solution.

This "weird" result usualy happens when you select then wrong baud rate or a different one then the one you beginned the serial communication with in the program. Thus by using Serial.begin(9600);, you have to make sure that the serial monitor is actually set to a baud rate of 9600.

Thanks! I had no idea what baud rate is, but I figured it out with your answer


text:
ESP8266 fail to connect MQTT broker
I am using NodeMCU dev board with ESP8266 WIFI.
Every time I try to connect to my local broker it returns this error:
failed, rc=-2 try again in 5 seconds

I am using Ubuntu 18.04, my local brokers are Mosquitto and EQMTT. I tried both of them through pubsubclient library and it doesn't connect. Using MQTT Box works connecting to my local brokers. Connecting to my WiFi also works. When I connect to a MQTT broker using pubsubclient e.g. mqtt://test.mosquitto.org:1883/ it works. It just doesn't seem to work with local broker. This is the code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "mywifi";
const char* password = "password";
const char* mqtt_server = "127.0.0.1";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup() {
  pinMode(D7, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(D7, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(D7, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(1000);
    }
  }
}
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}

Note: The brokers are running, I can even connect it through MQTT Box (attached picture).

127.0.0.1 is not the address of your computer.  That is the address of the "loopback" interface - a virtual interface that allows a device to talk to itself.
That means that when you are using the MQTT server itself you can connect, because it's all the same computer.  However the ESP8266 is trying to connect to itself, not the MQTT server.
You need to replace 127.0.0.1 with the actual IP address of your MQTT server.
The simplest way of getting your computer's IP address is to open a terminal window and type:
hostname -I

Thank you for responding. Where can I find the actual IP address of my MQTT server?

type ip address in a terminal and find the interface you are connecting with. It'll probably be 192.168.xxx.xxx.

Alternatively you can run hostname -I (that's a capital i) and it will give you all your non-loopback IP addresses.

It returned 192.168.100.3, I have replaced it in my code, but it still shows rc = 2. Any ideas? It's only like that using local broker.

What IP address is your ESP8266 being given?

ESP8266 is given 192.168.100.12

Try running netstat -an4 | grep 1883 | grep LISTEN and tell me what it tells you

Thank you. It suddenly worked, that is after your suggestion to hostname -I.

Can you help me again? It's not working suddenly. It seems to be very inconsistent. I haven't changed the code since yesterday (last time it worked).

netstat -an4 | grep 1883 | grep LISTEN gives me
tcp        0      0 127.0.0.1:11883         0.0.0.0:*               LISTEN      tcp        0      0 0.0.0.0:1883            0.0.0.0:*               LISTEN

The last line of that output is mosquitto listening on all interfaces, so that's fine. If it has worked, but isn't now, it may be something to do with your network or computer. It wouldn't be your sketch, since that doesn't change.

How would I able do diagnose it correctly? I am using Ubuntu 18.04 on WiFi connection.

However, I would handle your connection differently in your sketch.  Hold on, let me upload an example for you that I am using live in front of me right now (5 channel digital audio mixer controlled by MQTT)...

Another note, I listed all devices connected to my WiFi network, I tried pinging ALL online ones with their IP Address but it results in From 192.168.100.3 icmp_seq=3 Destination Host Unreachable. Only the ping to NodeMCU works 64 bytes from 192.168.100.12: icmp_seq=3 ttl=255 time=11.9 ms. May that be the problem?

Oh wow really weird! It's connected to MTTQ now. I just let it rest.

Here's an example: https://github.com/majenkotech/AmpControl/blob/master/AmpControl.ino - focus on what's in loop - the rest is pretty much irrelevant.

To give you an overview: you don't need to wait for a WiFi connection. You just need to see if it is connected or not - and if it is, then check if the MQTT is connected and connect it if it isn't, subscribing once the connection is established

Hm thanks for the help, but I don't really get the difference, it's basically linear with my logic. I just have trouble getting the MQTT connection, which I suspect has something to do with my WiFi/ host.

It takes about > 20 of these
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds until it gets connected.

I would suggest getting rid of (or massively shortening) that 5 second delay.


text:
Problem with "converting a string constant to 'char*'" in the WiFi library
error:
C:\Users\mrtas\Desktop\sketch_may23a\sketch_may23a.ino: In function 'void setup()':

C:\Users\mrtas\Desktop\sketch_may23a\sketch_may23a.ino:41:24:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

   WiFi.begin(SSID, PASS);   //Begin WiFi
              ^     ^

code:
#include <DHT.h>
#include <WiFi.h>
#define DHTTYPE DHT11
#define DHTPIN 5

DHT dht(DHTPIN, DHTTYPE);

String msg = "GET /update?key=TWE505JXFTXDPNB3";
float temp;
char SSID;
char Pass;

int hum;

String tempC;

int error;
void updateTemp();
#define SSID "wifi name"

#define PASS "wifi pass"

#define IP "184.106.153.149"

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

  // Connect to WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(SSID);
  WiFi.begin(SSID, PASS);     //Begin WiFi

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

void loop() {
start:
  error = 0;

  temp = dht.readTemperature();
  hum = dht.readHumidity();

  char buffer[10];
  tempC = dtostrf(temp, 4, 1, buffer);
  updateTemp();

  if (error == 1) {
    goto start;
  }
  delay(5000);
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  Serial.println(cmd);
  delay(2000);

  if (Serial.find("Error")) {
    return;
  }
  cmd = msg ;
  cmd += "&field1=";
  cmd += tempC;
  cmd += "&field2=";
  cmd += String(hum);
  cmd += "\r\n";
  Serial.print("AT+CIPSEND=");
  Serial.println(cmd.length());

  if (Serial.find(">")) {
    Serial.print(cmd);
  }
  else {
    Serial.println("AT+CIPCLOSE");
    //Resend...
    error = 1;
  }

  Serial.println("AT+CWMODE=1");
  delay(2000);
}

boolean connectWiFi()
{
  String cmd = "AT+CWJAP=\"";
  cmd += SSID;
  cmd += "\",\"";
  cmd += PASS;
  cmd += "\"";
  Serial.println(cmd);
  delay(5000);

  if (Serial.find("OK")) {
    return true;
  }
  return false;
}

We need the full error message, including the information where the compiler found the problem in your code. Please add that to your question

C:\Users\mrtas\Desktop\sketch_may23a\sketch_may23a.ino: In function 'void setup()':
C:\Users\mrtas\Desktop\sketch_may23a\sketch_may23a.ino:38:24: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
WiFi.begin(SSID, PASS);     //Begin WiFi
^
                      ^

Please add the error message to the question (click on “edit”) rather than as a comment. 2. This looks suspiciously like an issue of the WiFi library that was fixed five years ago. What version of the library are you using?

that's a warning, not an error ... does the compilation actually abort?

WiFi.h and AT commands mix? what are you doing?

i am working on a iot project and i found the code online .I am trying to fix it piece by  piece but i am not an expert in coding ,this is my first project i am still a student so if you can help  i would really  appriciate it

What is your hardware setup? Do you have a link to the place where you found the code?

This is a software issue. Hardware is irrelevant.

It's basically a bug in the library which is expecting "char *" when you are supplying "const char *.
You could work around it by changing:
#define SSID "wifi name"
#define PASS "wifi pass"

to:
char SSID [] =  "wifi name";
char PASS [] =  "wifi pass";

That makes them non-const so the error message should go away.
Not tested. But that is the general idea.


text:
How do I use a transmitter and receiver to send string messages conditionally to a receiver?
I'm working on a project to build a plant monitor that works from the outside with Arduino that picks up light and water values from it's environment then uses a nRF24L01 with an antenna and I've come across a roadblock in the code with using a transmitter and receiver, heres the code fully below.
Appreciate any help, been stuck for weeks trying to figure this out.
Transmitter Code
/*
 * NAME: <Mario Ronci>
 * Healthy Plant Monitor  V2  T
 *
 *
 */

 //** **/
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

int ldrValue;
int sensorPin = A0;    // select the input pin for the Water Comparator
int sensorValue = 0;
int light_threshold = 650;
int water_threshold = 850;
String dark_message = " ALERT:Plant is Dark!";
String bright_message =" Brightness Achieved! ";
String water_message1 = " Plant has enough water.";
String water_message2 = " Need Water...!";
String healthy_message = "Plant is Healthy!";
String unhealthy_message = "Unhealthy...!";
//String engineerinfo = "Mario Ronci 2023";

void setup() {

  pinMode(LDR, INPUT);
  pinMode(POT, INPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  Serial.begin(9600);
  Serial.println(engineerinfo);
  // put your setup code here, to run once:
radio.begin();
  //set the address
  radio.openWritingPipe(address);
  //Set module as transmitter
  radio.stopListening();

}

//This checks if the plant is getting enough light,//
//by taking a acceptable or unacceptable light value
//from a LDR and prints the value to the serial monitor
//and if the light value is acceptable

void ldrCheck(int device, int duration1,int duration2){

ldrValue = analogRead(device);

if(ldrValue >= light_threshold)

{
  messageLight = light_message + String(ldrValue);
  sendByteMessage(); // Call the function to send the byte message
   delay(duration1);// Wait for some time before sending the next message

}

if(ldrValue < light_threshold){
  messageLight = dark_message + String(ldrValue)
  byte messageBytes[message.length() + 1]; // Create a byte array to store the message
  delay(duration2);
}

void sendByteMessage() {
  byte messageBytes[message.length() + 1]; // Create a byte array to store the message

  // Convert the string message into a byte array
  message.getBytes(messageBytes, message.length() + 1);

  // Send the byte array through the transmitter
  radio.write(&messageBytes, sizeof(messageBytes));
}

}

////This checks if the plant is getting enough water,//
//by taking a acceptable or unacceptable hydration value
//from a LDR and prints the value to the serial monitor
//and if the hydration value is acceptable , the yellow LED will turn on
//and blink, if it's not it will print a message to the serial monitor
//to alert you

//********* Note replace POT with hydrometer code*********//
void potCheck(int device,int duration3){

potValue = analogRead(device2);

if(potValue > water_threshold)
{
  Serial.print(potValue);
  Serial.println(water_message1);

}

else{
  Serial.println(water_message2);

}

}

//This checks if the plant is getting enough water and light
//, if it's not it will print a message to the serial monitor
//to alert you and if it is getting enough it will print a
//message to the serial monitor telling you the plant is healthy

void healthyCheck(int led_4,int duration4,int duration5){

if((ldrValue >= light_threshold) && (potValue > water_threshold)){
digitalWrite(led_4, HIGH);
Serial.println(healthy_message);
delay(duration4);
}

else{
digitalWrite(led_4,HIGH);
delay(duration5);
digitalWrite(led_4,LOW);
delay(duration5);
Serial.println(unhealthy_message);

}

}

void loop(){

//This calls the function/method

//in loop call transmitter

ldrCheck(LDR, 1000,100 );
sendByteMessage(LDR)
potCheck();
healthyCheck(2000,800);

}

Receiver Code
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

//Create an rf24 object

RF24 radio(9,8) ; //CE,CSN

//address through which two modules communicate.

const byte address[6]  = "00001";

void setup() {

while(!Serial);
 Serial.begin(9600);

 radio.begin();

 //set the address
 radio.openReadingPipe(0, address);

 //set module as receiver
 radio.startListening();

}

void loop() {
  //Read the data if available in buffer

  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.print(ldrValue);
    Serial.println(light_message);
  }

What specifically do you need help with?
I'm trying to modify original code to work with the transmitter and receiver functionality
before I had code that used leds meaning the plant monitor would turn on certain colored LEDs based on condition.Now in V2 of this project i decided to do away with the LED's and make the goal to have communication between the componets from the outside to send messages about the plant status inside where another arduino would print to the serial monitor
I need help with having the transmitter code work with the conditional statements atm I'm confused where to insert the each piece of code so the transmitter sends a message to the receiver and prints in the serial monitor.It should work as the componets take inputs from the environment like the ldr, then that value is stored and applied to if statment , if x is this value then send this message and then the transmitter sends the message to the receiver that prints it to the serial monitor
What have you tried?
I've tried to create a seperate variable for the message I want to send along with the analog sensor values from the ldr.( I've not gotten to the hydrometer yet I only got the wiring for it done) Turn the ldr from int to a string and then call the variable in the byte message function within a function for checking for ldr values. Then in the receiver code i tried testing by writing Serial Print for each value but It's not working and I think its because the value is out of scope.Not in the same sketch.
What do you think the problem is?
I think it may be the order of the code and or syntax,maybe if I put the transmitter code outside of the ldr check function it would work, but im not sure. Could also be that the datatypes are strings and ints and changing that to the bytes isn't as straightfoward as I thought.
The actual build and components
Master  (  transmitter ) takes inputs from the environment using a Ldr and hydrometer
both water and light values and sends it to the slave microcontroller the receiver, wiring is correct.

Slave ( receiver) processes the values from the transmitter and prints them in the serial monitor the messsage it recieves will depend on conditions such as light value thresholds  and water value thresholds in simple terms if the light  or water values exceed a certain value or are below a certain value it will send a different message for each situation.

at this time, your post is equivalent to I need help with building a car ... please focus on only one problem ... start with the communication link ... forget all about LEDs, water, and plants ... focus on sending a single byte between the two devices, nothing more

Ok i get the idea of working one step at a time. But i was already able to send message to the transciever and print  it  to the serial monitor ,  but when I added the code where I added the conditional if statements it fell apart. That's my issue : Can i send the message  using the conditionals?

your code is a mess ... it is not formatted properly ... looks like there are extra braces, but it is not immediately evident ... do yourself a favor and format your code and then examine it ... correctly formatted code looks something like this ... https://www.programiz.com/cpp-programming/examples/vowel-consonant-frequency-string ... for example, there is no guessing which code executes when an if statement runs ... you should never see two successive closing braces at equal indent level as are in your code

I would restructure the code. The transmitter side should regularly collect data from the environment (light value, water value, other health values) and bundle these  raw data items into a single fomatted message (C++ struct) for transmission. The receiver, on receiving such a message, unpacks it, interprets it and generates any messages on the display etc. This matches your text description near the pictures but not your code. Incidentally, where in the receiver do the values ldrValue and light_message come from?

Use Ctrl+T in the IDE to attempt to format the code better. (Tools menu -> Auto Format).

You say the radio part works? But when you add  "conditional" code it does not? What I do w/my battery operated radio linked remote devices is always send an "unconditional" message and use it as a "heart beat".  To tell if the battery of the remote transmitter is dead. Do not set this too often if you are using batteries as it will put an extra drain on them.  But, for testing, just temporarily drop in a send in your LOOP function.

@MarioRonci can you highlight which conditional statements you are talking about specifically?

I figured the issue out.

code was a mess but after troubleshooting it for a while the if statements didn't make sense and had no good flow to them plus too complicated. I had copied and pasted some code without making sense of it.

It worked when I focused on one component like @jstola said. The photoresistor only and so the main thing is to add the conditional then turn string into a byte message and then void loop sends byte message to receiver arduino. Then the next part there were symbols appearing in the serial monitor and that was weird. So I experimented with the char data type instead of string and worked. Also use chatgpt as well for some syntax help.

Now I have base to work from. So next is to tackle the hydrometer.
Transmitter Code - with photoresistor only
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(9, 8); // Create an instance of the RF24 object

const byte address[6] = "00001"; // Set the pipe address

int ldrValue;
int sensorPin = A2;    // Select the input pin for the LDR
int light_threshold = 650;
String light_message = "Plant has enough light :";
String dark_message ="Alert: Plant is Dark! :" ;
String water_message1 = " Plant has enough water.";
String water_message2 = " Need Water...!";
String healthy_message = "Plant is Healthy!";
String unhealthy_message = "Unhealthy...!";

void setup() {

  pinMode(sensorPin, INPUT);
  radio.begin();
  radio.openWritingPipe(address);
  radio.stopListening();

}

void loop() {
  ldrCheck(sensorPin, 1000, 100);
}

void ldrCheck(int device, int duration1, int duration2) {
  ldrValue = analogRead(device);

  if (ldrValue >= light_threshold) {
    String message = light_message + String(ldrValue);
    sendByteMessage(message);
    delay(duration1);
  }
  else {
    String message = dark_message + String(ldrValue);
    sendByteMessage(message);
    delay(duration2);
  }
}

void sendByteMessage(String message) {
  byte messageBytes[message.length() + 1];
  message.getBytes(messageBytes, message.length() + 1);
  radio.write(&messageBytes, sizeof(messageBytes));
}

reciever Code - with photoresistor only
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(9, 8); // Create an instance of the RF24 object

byte address[6] = "00001"; // Set the pipe address

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1, address);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    char message[32] = ""; // Create a character array to store the message
    radio.read(&message, sizeof(message));
    processMessage(message);
  }
}

void processMessage(char* message) {
  String receivedMessage = String(message); // Convert the character array to a String
  Serial.println(receivedMessage);
  delay(1000);
}

result:

Video


text:
Using Lua in Arduino project
I want to write code for my Arduino in Lua. Where I can find the necessary (pins) I/O lib and examples for Arduino IDE?
UPD: I've got arduino mega with many memory.

You want to code in Lua? And have that code run on the Arduino? Which Arduino do you have in mind?

@NickGammon , that's true, I want to write program for arduino uno.

@NickGammon: ok, now I've got an arduino mega.

It looks like the ESP8266 runs Lua, but I haven't seen it running on an Arduino.

Lua is an interpreted language. That is, the compile phase turns Lua source code into intermediate "pseudo-code" which the Lua interpreter then runs. It doesn't compile into machine code, and therefore there is nothing that could be uploaded to your Uno as a "hex" file.
In any case, with only 2 KB of RAM, it wouldn't be very practical to attempt to run Lua on a Uno. I like Lua personally, but running it on the (AVR) Arduinos just isn't practical.

Lua is a language (a spec of syntax and semantics). Its most widespread implementation is an interpreter, but there is nothing in the Lua language that prevents one from writing a compiler that emits Arduino code (or any other code). I find it actually unexpected that no one has made it yet.

AFAIK, Arduino IDE supports C++ only. You can use other languages to communicate with Arduino from your PC. Take a look at Firmata.

An enterprising person might cross compile Lau to C++ ... Once upon a time our AT&T C++ compiler only emmitted C and the cc command turned that into object coed.