text:
Dealing with USB Unplugging?
The following code, debugs SerialUSB Native Port, plugged to a PC, and connected through a Terminal Monitor (such as Termite, with any bps, 8N1, RTS/CTS).
At start, the ports seeks for communication, and you see fast blinks.
If SerialUSB, Plugged and Connected, communication happens, a.k.a. slow blinks.
But if USB is Unplugged after SerialUSB, even if you Disconnect it before, the code turn into an Halt state, a.k.a. no blinks.
If you Plug back the USB, it returns to !SerialUSB, so if you Disconnect (if it were connected) and Connect back the terminal, it recovers the SerialUSB state, not without a reset() line to react.
Seems the same happens for Serial.
Any clue about why the Arduino goes into that Halt state after a USB disconnect?
How should we deal with that? How one should prevent this state?
Most people asserts this is a power source problem. This happens with and without the 5V Barrel Power Source.
// ARDUINO DUE BLINK LED
void setup(){
  pinMode(13,OUTPUT);
  Serial.begin(115200);
  SerialUSB.begin(115200);
  while(!Serial){
    digitalWrite(13,HIGH);delay(500);
    digitalWrite(13,LOW);delay(500);
  }
  Serial.println("System Reset");
}
void loop(){
  int n=0;
  while(!SerialUSB){
    Serial.println("USB Unplugged or Terminal Disconnected");
    digitalWrite(13,HIGH);delay(50);
    digitalWrite(13,LOW);delay(450);
    n=n+1;
    if (n>=5){
      Serial.println("Resetting to Connect if Disconnected");
      digitalWrite(13,HIGH);delay(450);
      digitalWrite(13,LOW);delay(50);
      rstc_start_software_reset(RSTC);
    }
  }
  SerialUSB.println("USB Plugged and Terminal Connected");
  Serial.println("USB Plugged and Terminal Connected");
  digitalWrite(13,HIGH);delay(50);
  digitalWrite(13,LOW);delay(50);
}

This is not possible to do because the protocol CDC/ACM don't send that type of information so you can't detect if the Arduino is connected or not, that's why it halts. (You could make a keep-alive function but I don't know if this is possible with what you're doing)


text:
Accessing Physical Pins in Arduino Due from Arduino IDE
It is possible to access the Physical Pin 93, Pin PC11 on ATSAM3X8E in Arduino Due  from the Arduino IDE?
I am programming a Barebone ATSAM3X8E, and it do not seems to be allocated by Arduino Due nor by ATSAM3X8E for any other purpose than the PC Port.

you can configure your own board for Arduino IDE https://arduino.stackexchange.com/questions/54484/adding-a-custom-board-to-the-arduino-ide/60660#60660

Modifying/Making a variant
If you wanted to do it in an Arduino-like way it would require editing the Arduino Due variant.cpp or copying the making your own variant, say from a copy of the Due, and editing the extern const PinDescription g_APinDescription[] array to include an entry that matches for PC11.
Example changes
As an experiment I made the following changes to files in the packages/arduino/hardware/sam/1.6.12/variants/arduino_due_x under the arduino15 directory.
In variant.cpp, an entry for in the g_APinDescription array is insert an index number 79, between the existing two entries (shown for context):
  { PIOB, PIO_PB23B_SPI0_NPCS3,ID_PIOB,PIO_PERIPH_B,PIO_DEFAULT, PIN_ATTR_DIGITAL,                  NO_ADC, NO_ADC, NOT_ON_PWM,  NOT_ON_TIMER }, // NPCS3
  // Addition line here VVVV (this is the line for PC12, copied with PIO_PC12 changed to PIO_PC11
  { PIOC, PIO_PC11,          ID_PIOC, PIO_OUTPUT_0, PIO_DEFAULT, PIN_ATTR_DIGITAL,                  NO_ADC, NO_ADC, NOT_ON_PWM,  NOT_ON_TIMER }, //
  // 79 .. 84 - "All pins" masks

  // 79 - TWI0 all pins
  { PIOA, PIO_PA17A_TWD0|PIO_PA18A_TWCK0, ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT, (PIN_ATTR_DIGITAL|PIN_ATTR_COMBO), NO_ADC, NO_ADC, NOT_ON_PWM, NOT_ON_TIMER },

This is a copy of the entry for PC12, with PIO_PC12 changed to PIO_PC11.
In variant.h, PINS_COUNT changes to 80u, because we've inserted  the pin:
#define PINS_COUNT           (80u)

and later in the file the pin number associate with CAN are bumped up by one also because they're all numbered after the point of insertion:
/*
 * Complementary CAN pins
 */
static const uint8_t CAN1RX = 89;
static const uint8_t CAN1TX = 90;

// CAN0
#define PINS_CAN0            (91u)
// CAN1
#define PINS_CAN1            (92u)

I programmed a sketch the blinks PC11 by way of digitalWrite(79, state); and carefully placed a logic probe on the the unrouted pin on the Due board, and it "blinks" just fine.  That's as far as I've tested.
Direct control
Alternately you could control the pin in your code manually, doing what digitalWrite or digitalRead would normally do.  In other words, you could read the description of something like digitalWrite here and substitute all of the references that it would have gotten from g_APinDescription with hard-coded values.

If I get a chance I will try altering the variant here.  It looks like the new pin would have to be inserted before the PINS_COUNT index, which would need to be made larger by one.  And then PINS_COUNT and a few other named values for pins would have to change to reflect all their indices increasing by one.

I made the six line changes indicated, for some reason the 93 physical pin, PC11, in our sketch at 79, it stays at 3.3V. I will keep trying

You remember to pinMode(79, OUTPUT); ?

Yes... as all other pins. As reference, it is the 93 physical pin in ATSAM3X8E, it is located close to the A0 connector, in the Arduino Due board.

I gather from the that and the update that you're concern we're not talking about the same pin, but I'm pretty sure we are.  Here is the contact I'm making to probe.

Right... perhaps i am omitting some step. I will keep checking.

source: Stack Exchange

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

sort: votes


text:
What module can I use for receiving 433.42 MHz transmissions with ASK/OOK modulation?
I am looking for a module that would be able to receive communication in the 433.42 (ch01) range with ASK/OOK modulation. Can someone recommend anything that would work and not be an expensive general purpose SDR module?
Long story: I have tried using the cheap RF 433MHz modules(picture below). I was able to modify the transmitter by de-soldering 433.92 crystal & soldering-in 433.42 one (picture two).
Now I have no way of testing this, as I am not receiving any communication while using the standard receiver that is tuned to 433.92 MHz. There doesn't seem to be any obvious way to tune the receiver to 433.42 MHz.
Reference ebay example for the crystal oscillator.

I was able to solder the crystal ... solder where? ... are you sure that it is a crystal?

please add a reference to the pictures into your post ... edit the post, do not write a comment

This is quite a good description of those modules and how to use them https://lastminuteengineers.com/433mhz-rf-wireless-arduino-tutorial/. If the receiver is no longer tuned to your modified transmitter, then you could try adjusting its [the receiver's] trimmer (brass coloured screw in the green cube).

It turns out that:

the receiver DOES work with the different frequency when the range is sufficiently small (a couple centimetres at most)
the library that I was using was expecting different kinds of transmissions so it wasn't showing anything useful
only low level interrupt service routine is actually giving me access to the actual data from the module
the issue that is complicating things with those modules is that in the absence of actual transmission noise is getting amplified and the module is outputting gibberish, so serious thinking needs to go into recognising when actual transmission starts & ends

Welcome to the wonderful world of RF transmission! :-D Additionally you will learn a lot of communications engineering including the differences between theory and practice.

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


text:
How to send Json to a webservice from pc/RPI with live data from Arduino(serial)
I'm making a project where my plan is to take sensor input from the Arduino, and then pass that info (by serial/usb connection) through either a laptop or a Raspberry Pi and convert it to Json and send it to a webservice in asp.net c#, where it gets stored in a database, and then the data can be shown on a website, so the visitor can see live data from the Arduino sensor on the site and also be able to see what the sensor measured yesterday, last month, or the average for a extended period of time, or a graph.
It might be easier to illustrate what I'm talking about:

The PC / RPI part is optional, it can be using either one.
There are a few options, as I see it, as to which methods could work. But I am unsure about how to implement them and what programs to use for it.
First one is to log data to a file on the PC/RPI and then have some shell script either listen for changes and then combine a Json string with the newly added info to the file and send it of to the webservice.
Second one is to somehow take the Serial data from the Arduino and have some shell script or program listen for any data coming from the Arduino and converting it to Json, and sending it of to the webservice. The pro's by this method would be omitting the extra "file-step", but it would make the system more vulnerable to any interruptions in the connection.
Does anyone have experience with doing something like this? Or maybe have an idea how I can do what I'm trying to do ? Or just a nudge in the right direction, as to which approach you think is best, or what programs I could/should use.
Any help is very much appreciated!
Best regards
Daniel

None of this is actually an Arduino problem; it merely has an Arduino as one of the cogs in the system.

No, and I never claimed it to be an Arduino problem, but its still related to Arduino. I'm not asking about the whole setup, just if someone knows how to handle the Serial input from the Arduino.

But that's the thing. You could just as easily say "serial input from the BBB" or "serial input from the DAQ board" and absolutely nothing would change.

Well, I would also need the system to go the other way, and turn on a motor driver shield, would that make it more Arduino related for your preferences?

It has nothing to do with my preferences. You have a very good question here, but I don't believe that it will get the attention it deserves on this site. However, if you move it to another site then the fact that you mention "Arduino" may bias people towards moving it back here even though it's not the important part. I honestly think you should post this on Stack Overflow but first obscure the Arduino with "embedded device", mentioning in passing that the device is an Arduino but that you're not actually asking for help with the Arduino (since serial transfer with it is a solved problem).

That's a very good point. I thought you we're just on a "smear campaign". The reason that I posted here, was that I was sure that there must be some Arduino people, that had tried something like this before. But you're right, it will get much more attention on the general forum. I'll try and go post it there, thanks for your help. :)

You might even explicitly say that the Arduino site concluded it was not an Arduino question.

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


text:
How to serially transfer/read an image to Arduino
I am using Arduino Uno and the image size is 12.7 kb. I want to read a jpeg image from computer and convert into bitmap in arduino. Later on it will be implemented using SD card.Is it possible to read a .jpeg image from computer to Arduino using serial communication? If yes, then how?

Which Arduino? How big is this image? Why do you want to do this? Please read How do I ask a good question?

This is almost certainly a bad idea.  On the more conventional Arduino boards, you could only accomplish it by streaming the image from the source, through whatever processing you are doing and to the permanent storage, as you just don't have the on-board RAM to hold more than a tiny part of it at any time.  Depending on the processing you want to do you may need simultaneous access to more of the image than you can fit in memory at once, unless you can "rewind" the source or destination to multiply process it.  Much better to do your conversion on the real computer!

@ChrisStratton I am not going to implement this idea in the final project. All I am asking is for experimenting purpose. And besides the final project will be on Arduino Mega, one entire image can be loaded from SD card, processed and written back to SD card. I just want to know if right now I can do with serial communication or not.

You can send anything you like through the serial port. It is just 8-bit raw data. The onus is on you, however, to implement a suitable high level protocol with which to transfer the data.
One important thing to bear in mind though: JPEG is a highly compressed complex image format. I am not aware that anyone has ever managed to squeeze JPEG decompression into a lowly Arduino. Instead you will need to use a decompressed image format such as BMP, or do the decompression on the computer before-hand and send the raw RGB image data over the serial instead.

As an addendum to this: I wrote a crude JPEG decompresser for chipKIT boards. It requires about 100KB of RAM to operate, so no chance of it ever working on an Arduino.

Of course you can, but as stated in the comments and in the other answer JPEG use a complex algorithm to compress the images, and most computers have a dedicated hardware to perform the cosens discrete transform. Anyway the answer to your question is yes, and it's not hard.
You just have to split the image into bytes, send them through the serial port and make Arduino read and save them into an array. To avoid errors create a protocol that can decode what are you doing.
For example:
0b1111000 for 3 times = Start sending
0b00011000 = new line
and so on..
The first thing that come in my mind is to use the pySerial library, that can automate the process. Python is perfect for prototyping: open the image (maybe using the numpy library instead of using lists) and with a for loop send every byte over the serial port in according to the protocol you created.
On the Arduino just code the protocol to understand every bite and save the image in an array.

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


text:
Why does the pin 2 of arduino Mega stay always HIGH?
Without declaring the pin 2 as INPUT or OUTPUT, it remains constantly HIGH. Can anyone explain why is it so?

Pin 2 connects to the controller's PE4, which is a GPIO pin, which can also be used for PWM. You should be able to use it either as input or output, and both high and low. It could be that setup initializes it as output high, while you would usually have uninitialized pins as input.

Have you tried to make it low, or make it input?
digitalWrite(2, LOW);

should make it low, while
pinMode(2, INPUT);
int pin2Status = digitalRead(2);
digitalWrite(13, pin2Status);

will copy the status of pin 2 to the on-board LED.


text:
Why does timer ISR not execute?
This is my code which I have written as a library
#include "avr/interrupt.h"
#include "Arduino.h"
#include "AllTimer.h"

AllTimer::AllTimer()
{}

void AllTimer::dofun(void)
{
     //TIFR1 |= _BV(OCF1A);

    TCCR1B = 0X00;
    //TIFR1 = 0X01;
    digitalWrite(13,!digitalRead(13));
    Serial.print("I printed");
    TCNT1 = 0X0000;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    //sei();
}

 void AllTimer::setTimer(void)
 {
    TCNT1 = 0x0000;
    TCCR1A = 0x00;
    TCCR1B = 0x00;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    TIMSK1 |= (1<<TOIE1);
    sei();
 }

ISR (TIMER1_OVF_vect)
{
     AllTimer::dofun();
}

Code in Arduino IDE:
 #include <AllTimer.h>

 AllTimer mytimer;

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

 void loop()
 {
     mytimer.setTimer();
    //delay(200);
  }

But I am not getting anything on the serial monitor. What is the error I have made?

Using Serial.print inside an ISR is asking for problems. Does the led blink? Also, there is no need to write TCCR1B and TCNT1 inside doFun.

The Arduino main() calls loop() continuously, in a tight loop. Thus
your AllTimer::setTimer() is called continuously, and each time it
resets the counter (TCNT1 = 0x0000;). Thus the counter can never
overflow.

So put mytimer.setTimer(); inside setup instead of loop.

also, in TCCR1B |= (1<<CS12) && (1<<CS10); shouldn't it be | instead of the logic &&?

@SimSon: Indeed! I hadn't spotted that. Good catch.


text:
Is PulseIn fast enough for Quadcopter?
I've been trying to use interrupts to control a quadrotor with a tx/rx to no success. I'm using an arduino mega as my control board. I have successfully read a singe channel using attach interrupt and PulseIn. I have also successfully read multiple channels with pulse but failed to do so with attach interrupt and pinchange int. Should I just go ahead and use PulseIn

Your referring to reading ppm signals from an RC radio with pulseIn?

Yes. I have been told to avoid it but nobody who tells me this explains why

You should avoid pulseIn for a quadcopter, the main reason being that pulseIn takes too long to execute.
pulseIn waits for a pulse to start, then waits until that pulse finishes, and then returns how long it took to finish. Standard RC signals pulse at 50-60Hz, with the "high" part of the signals being between 1 and 2 milliseconds. 60Hz is one pulse per 16 milliseconds or so.
What that amounts to is pulseIn taking at most 18 milliseconds, but never less that 1 millisecond to execute per channel. lets say you want to measure 4 channels (throttle, pitch, yaw, roll); the average time would be around 40 milliseconds.
In general 40 milliseconds isn't so long, but your quad will need to read the accelerometer and gyroscope and stabilize itself more often then that in the air. A loop that takes 40 ms is running at 25Hz, but the stabilize loop in all the quadcopter implementations I'm familiar with is run at 100Hz or higher (thats areoquad, multiWii, and ardupilot).
You should use interrupts to read the values, because interrupts are non blocking, and give higher quality readings. Some specialized quadcopter boards have other processors read the actual RC signals and send the result back to the main processor to cut down on the number of interrupts they have to use.

FYI, The standard servo output library sends new signals at 50Hz. Those open source quadcopters use their own implementations that run at higher output frequencies, since brushless ESCs support that. There is a pull request with code to add support for different refresh intervals to the arduino servo library here that I have tested; You could try appling it as a patch to your installation if the output rate gives you trouble down the road.

Thanks for the servo library information. Great. I did try it on my quad and I got this error information stated below after refreshing my servo library.  Any idea what causes this and how to correct this?                                                                        C:\Program Files (x86)\Arduino\libraries\Servo\src\avr\Servo.cpp:40:69: error: 'usTOTicks' was not declared in this scope
^
exit status 1
Error compiling for board Arduino Nano.


text:
Compiling is slow
Compilation of even the simplest program (like Blink) is extremely slow, the progress bar often hangs halfway for nearly half a minute.

Is this normal? I understand that not all computers are equally fast, but there's a huge difference between 3 seconds and 30 seconds
edit
It appears from the report that every time I switch programs they're built anew completely:

Build options changed, rebuilding all

even when nothing has been changed. How can I avoid a complete rebuild?

Have you tried enabling verbose compilation so that you can see exactly what's happening?

@Ignacio: updated the question

Try using version 1.5. 1.6 is just out, so it might have some bugs.

@Gerben: before I upgraded (today) I used 1.0.6, and it acted the same. Thanks for your comment.

Run check disk and also run spin rite on your drive. It's possible your spinning disk is failing.

@portforwardpodcast: That would surprise me. Every other software I use runs smoothly. It just seems to be all this unnecessary recompiling

Try moving all of your third-party libraries and any others you can identify as special-purpose ones, to a differently-named folder temporarily. Try recompiling Blink, which will only need the standard Arduino ones, and see if its compile-time changes. Then you might move them back a few a at a time until the compile time jumps back up again - the last added group contains something strange. It certainly takes me longer to compile the world, than to compile and link one sketch, but 30 seconds is insane! BTW, what is your dev machine?

I have found that this is a common issue across my development machines, however using Visual Micro for Visual Studio reduces this time by a significant factor.
I primarily use it for other Visual Studio features like Intellisense, refactoring, and solution management. Visual Micro has some compelling features of its own, like debugging tools, however I haven't used them.

Visual Micro
Visual Studio Community Edition

I haven't personally tried, but I would expect that you can avoid the rebuild using the project/solution options in Visual Studio - I found that the compile time is fast enough in most cases with this environment for it to not matter.

Any reason for the downvote? - Visual Micro does consistently compile faster than the Arduino IDE. Even simple programs take a long time to compile in the Arduino IDE at the best of times compared to using other tools.

Setting the option "High Speed Parallel Builds" under vMirco options really speed up the build for me. 'm using VS Studio Communiti Edition with Visual Micro.

If you find compilation slow then yes, it is probably recompiling things that it doesn't really need to recompile.  This has always been a major failing of the Arduino environment, and is one of the major impetuses for the complete re-write of the whole compilation system in my IDE UECIDE.
That includes very aggressive caching of compiled library and core files as proper ".a" files which are stored away separate from your board selection and kept until something really does need compiling.  That way the first time you compile something for a board it may take 30 seconds, 50 seconds, whatever.  All subsequent compilations for that same board, even for different sketches (not including the compilation time of "fresh" libraries) would be around 2 seconds, even less.
That caching is especially important when you're running on a very slow system, such as a Raspberry Pi, when compiling can take many minutes without the caches in place, but only a few seconds on all subsequent compilations.

Do you plan to support FreeBSD? - UECIDE looks promising. For now, I have to run a slow VM with windows. Would like something snappy like this IDE.

The IDE itself is just a Java application. As such it should run fine on FreeBSD. I had it going on there myself once - even made a port for it (in the early days that is). It should still run fine, though may require a little bit of bending. Use the Linux ZIP version and edit the uecide script file to suit. The hard part though will be getting the plugins to work. They need native binaries, such as compilers, programmers, etc. If you can find those kind of things for FreeBSD then you may have some success at making it work - if not, not.

You can try using the FreeBSD Linux Binary Emulation system instead of a Windows VM to run the Linux version of UECIDE along with the Linux binaries. Not sure what the plugin system would make of that though.

Sounds about as painful as expected :/ I'll grab UECIDE for my VM instead ;)

I had the same problem until today. Like many answers around the web, the problem seems to come from the anti-virus. My setup is Windows 10 x64 with a SSD and I use Windows Defender as the AV.
I tried by excluding the main arduino folder in "c:\program files (x86)\arduino", but it didn't improve the compilation time.
I checked the "verbose" option in the Arduino IDE and I've seen that it was calling the compiler from the AppData folder. So I add this folder to my AV exclusion list and it worked!
The compilation time improve by ten folds.
TLDR; In Windows 10, add the folder in %USERPROFILE%\AppData\Local\Arduino15 to the AV exclusion list.

Specifically, look to see if you've got Trusteer Rapport installed. Its some kind of banking protection mechanism, but I found it slowed down my compile horrendously. Removed and it's so much snappier. I've lived with this for soooo long so glad to have nailed the cause.

This thread, Arduino IDE and ESET: Slow compilation, may be helpful if you use ESET (at least one user has reported that it helped), but it didn't help me since I'm using Comodo (and may be there are some other reasons).
Here's another thread, SLOW ARDUINO IDE regarding a solution which helped many users, since 2009 (the latest comment on the forum is dated year 2014).
Several useful posts here as well, Unbelievable slow compilation of simple sketches. Ok, I haven't tested all the solutions myself, but let me collect useful links here so that other guys can find them and I'll check them out, too.

Hi Yakov and welcome to SE Arduino. Thanks for providing the links, I am sure that they are useful. However, it is much better if you can provide answers that you have tested yourself and that have worked for you. If you obtained the solution, that worked for you, from a thread such as those which you have posted, then all well and good. However, try to refrain from just googling links and posting them as answers, without trying them first... :-)

Hi @Greenonline, fair enough, I'll report my results once I test these suggestions. It's just the issue doesn't seem to be simple and many users suffer it because of different causes, so I think some solutions successful for others are no less useful than the one which will help me.
As for the issue, I have to test several things, including

IDE recompiles the whole thing each time? (this is mentioned in some threads, but I have no idea how to check this)
smth consumimg CPU? (don't see anything in task manager)
anything I can configure in Comodo? (HIPS.. looks like all is permitted for )

Ok, there's a simple way to understand weather your firewall (HIPS or other tech) causes the problem: just turn it off and try to compile again. In my case, this didn't accelerate compiling. Interestingly, sometimes even opposite: without firewall compiling seems to be always ~45 sec, but with firewall on it sometimes takes 17 sec.

I would download the non-install version and try compiling the blink sketch in it.  This will let you know if it is a computer specific issue or something related to your install.  I experienced something similar with a library that wasn't updated correctly between versions which caused all sorts of buggy behavior.

The occurrence of “Build options changed, rebuilding all” (as mentioned in edited question and shown in screen shot) probably is causing the large delay.  My belief (correct or not) is that lots of libraries are being rebuilt when that message appears.  Ordinarily, libraries should be rebuilt only upon initial install or when changing target board type.
An arduino.cc thread, “"Build options changed, rebuilding all" even when nothing changes ==> very slow”, from 2014 treats the issue superficially, merely pointing out that Arduino 1.5.8 Beta is suitable for Yún and Arduino Due boards, not “regular Arduino” boards.
A 2011 Google code thread probably is mostly irrelevant, but it's worth trying some steps mentioned in posts #14 and 15  ‒ eg, starting arduino via a path with no spaces in names ‒ if your platform is MS Windows.  If the Arduino IDE cannot find its options or preference files it probably assumes it is starting from scratch.
Note, please edit the question to specify how you started the Arduino IDE running, where the IDE is installed on your system, what your op system is, and what your computer is.


text:
How to ssh via USB Ethernet adapter
For a few days now, I have been connecting to my board which is hooked up to my router through a clutter of wires, over Wi-Fi. To spare my family from the risk of tripping, or hogging the extension cords all to myself, I'm looking for a way to establish an ssh connection directly from my computer (either via a USB Ethernet or a Thunderbolt Ethernet adapter).
My question is what address will I be looking for? Is it something like arduinoname.local?

Ehhm, so your Arduino is connected to your Wifi network and you are asking, what IP it has to reach it from your PC? Have you looked at the webinterface of your router? Normally there you can find a list of connected devices with their IP addresses. When your Arduino uses DHCP, the router is the one, who sets the device to a specific address. So you should look there

No, no, no! I have been connecting over Wifi, but I want to be able to connect over cable instead (computer-to-board instead of computer-to-router-to-board)

ssh root@[arduinoname].local

does the trick. Just replace [arduinoname] with your board's name: ssh root@myboard.local
Seems to take a minute or two to initialize, so if it doesn't work immediately don't give up right away!
This however won't allow you to access your internet, so I'll still have to connect to my router if I'm going to be downloading anything.


text:
Library ADC MCP33121
I'm looking for the Library of the ADC MCP33121 for Arduino UNO or functional code, I don't have enough tools for testing so I'd like to get some code already tested.
I appreciate any help.
Thanks... Josh

There don't seem to be such a library for that specific chip. At least I found none when googling for it. You might need to write the code yourself.

You don't really need a library for that chip. You just do a pair of SPI transfers with the CS pin low.
For example:
digitalWrite(pinCS, LOW);
uint8_t msb = SPI.transfer(0xFF);
uint8_t lsb = SPI.transfer(0xFF);
digitalWrite(pinCS, HIGH);

uint16_t val = (((uint16_t)msb << 8) | lsb);
val = val >> 2; // For 14 bit devices shift it twice. For 12 bit do it 4 times.

Thanks for your answer, I was checking the datasheet and looking at the code that you provide, the digitalWrite(pinCS, LOW)... until the digitalWrite(pinCS, HIGH), it neglects the timing aspect. I mean the datasheet provides some timing for acquisition and conversion so, should I have to worry about that timing?

T_CNV is at worst 1300ns. That's only 20 clock cycles on a 16MHz Arduino. By the time you get round to sampling again that time will have passed. The T_EN is a mere 10ns. That's a sixth of the length of one clock cycle. You would have to be doing something really bizarre with your Arduino to even come remotely close to needing to even think about the possibility of timing being an issue.

Thanks for sharing.


text:
Arduino and ZMPT101B But Not Stable Sigma Output In 7segment Display(TM1637) using filter library
#include <Arduino.h>
#include <math.h>
//TRUE RMS START
#include <Filters.h> //Easy library to do the calculations
#include <TM1637Display.h>
float testFrequency = 100;                     // test signal frequency (Hz)
float windowLength = 100.0 / testFrequency;   // how long to average the signal, for statistist
int Sensor = 0; //Sensor analog input, here it's A0
int Sensor2 = 0; //Sensor analog input, here it's A1

float intercept = -0.04; // to be adjusted based on calibration testing
float slope = 0.0405; // to be adjusted based on calibration testing
float current_Volts, output_volts; // Voltage

unsigned long printPeriod = 500; //Refresh rate
unsigned long previousMillisTRUE = 0;
int truermsflag = 0;
int inputvolt = 0, outputvolt = 0;
RunningStatistics inputStats;
RunningStatistics inputStats2;
int sigmaint = 0;
//TRUE RMS end
//#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
//#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

// Module connection pins (Digital Pins)
#define CLK 3
#define DIO 2

#define CLK1 4
#define DIO1 5

#define switcht 6
#define Relay1 8
#define Relay2 9
#define Relay3 10
#define Relay4 11
#define TRelay 12
// The amount of time (in milliseconds) between tests
int i = 0;
int timerflag = 0, onetimeflag = 0;
int volt = 0, voltoutput = 0;
TM1637Display display(CLK, DIO);
TM1637Display display2(CLK1, DIO1);
const uint8_t DONE[] =
{
    //SEG_B | SEG_C | SEG_D | SEG_E | SEG_G,           // d
    SEG_D,   // O
    //SEG_C | SEG_E | SEG_G,                           // n
    //SEG_A | SEG_D | SEG_E | SEG_F | SEG_G            // E
};
const uint8_t Dely[] =
{
    SEG_B | SEG_C | SEG_D | SEG_E | SEG_G,           // d
    SEG_A | SEG_D | SEG_E | SEG_F | SEG_G,           // E
    SEG_F | SEG_E | SEG_D,                           // L
    SEG_F | SEG_B | SEG_G | SEG_C // Y
};
const uint8_t HIVOLT[] =
{
    SEG_F | SEG_E | SEG_B | SEG_C | SEG_G,           // H
    //SEG_B | SEG_C,           // I
    //SEG_F | SEG_E | SEG_D | SEG_C | SEG_B, // V
};

const uint8_t L0VOLT[] =
{
    SEG_F | SEG_E | SEG_D,                           // L
    //SEG_A | SEG_B | SEG_C | SEG_D | SEG_E | SEG_F,//0
    //SEG_F | SEG_E | SEG_D | SEG_C | SEG_B  ,// V

};

int ledPin =  13;      // the number of the LED pin
unsigned long previousMillis1 = 0, previousMillis2 = 0, previousMillis3 = 0;      // will store last time LED was updated
//unsigned long currentMillis;
unsigned long previousmacro = 0;
unsigned long currentMacro = 0;
int acVoltage(int adcpin);
int average(int pin);

void setup()
{
    //
    //  sbi(ADCSRA, ADPS2);
    //  cbi(ADCSRA, ADPS1);
    //  cbi(ADCSRA, ADPS0);
    analogReference(EXTERNAL);  // set ADC positive reference voltage to 1.1V (internal)
    pinMode(switcht, INPUT);
    pinMode(switcht, INPUT_PULLUP);
    pinMode(Relay1, OUTPUT);
    pinMode(Relay2, OUTPUT);
    pinMode(Relay3, OUTPUT);
    pinMode(Relay4, OUTPUT);
    pinMode(TRelay, OUTPUT);

    //For Optocuplar Relay
    digitalWrite(Relay1, HIGH);
    digitalWrite(Relay2, HIGH);
    digitalWrite(Relay3, HIGH);
    digitalWrite(Relay4, HIGH);
    digitalWrite(TRelay, HIGH);

    pinMode(ledPin, OUTPUT);

    display.setBrightness(0x0f);
    display2.setBrightness(0x0f);
    //display.setSegments(Dely);

    //  delay(3000);
    //  display.clear();
    //  display.setSegments(HIVOLT, 3, 0);
    //
    //  delay(3000);
    //  display.clear();
    //  display.setSegments(L0VOLT, 3, 0);

    //display2.setSegments(Dely);
    //display.clear();
    Serial.begin(57600);

    //delay(1000);
}

void loop()
{
    if (truermsflag == 0)
    {
        //TRUE RMS

        truermsflag = 1;
        //END TRUE RMS
    }
    unsigned long currentMac = micros();

    if (currentMac - previousMillis3 > 3)
    {
        previousMillis3 = currentMac;
        //Easy life lines, actual calculation of the RMS requires a load of coding

        inputStats.setWindowSecs( windowLength );
        inputStats2.setWindowSecs( windowLength );
        Sensor = analogRead(A0);  // read the analog in value:
        Sensor2 = analogRead(A1);  // read the analog in value:
        inputStats.input(Sensor);  // log to Stats function
        inputStats2.input(Sensor2);  // log to Stats function

        //Serial.println("run") ;

    }

    if ((unsigned long)(millis() - previousMillisTRUE) >= printPeriod)
    {
        previousMillisTRUE = millis();   // update time every second
        current_Volts = intercept + slope * inputStats.sigma(); //Calibartions for offset and amplitude
        current_Volts = current_Volts * (56.613);             //Further calibrations for the amplitude
        inputvolt = round(current_Volts);
        Serial.print(" START ");
        Serial.print("Input Volts:");
        Serial.println(inputvolt);
        Serial.print("Input Sigma");
        Serial.println(inputStats.sigma());
        Serial.println(" END ");
        output_volts = intercept + slope * inputStats2.sigma();
        output_volts = output_volts * (56.613);
        outputvolt = round(output_volts);
        //Serial.print("Output Volts:");
        //Serial.println(outputvolt);

    }

    //end
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis3 > 1000)
    {
        // save the last time you blinked the LED
        previousMillis3 = currentMillis;
        digitalWrite(ledPin, LOW);

        // display.showNumberDec(inputvolt, false, 3, 1);

    }

    /*
      unsigned long currentMillis = millis();

        if ((currentMillis - previousMillis1 > 1000) && timerflag == 0) {
          previousMillis1 = currentMillis;
          digitalWrite(ledPin, HIGH);

          if ((digitalRead(switcht) == LOW) && timerflag == 0 && onetimeflag == 0) {

            i = 10;
            onetimeflag = 1;
          }
          if ((digitalRead(switcht) == HIGH) && timerflag == 0 && onetimeflag == 0) {

            i = 180;
            onetimeflag = 1;

          }
          display2.showNumberDec(i--);
          if (i == 0) {
            digitalWrite(TRelay, LOW);
            timerflag = 1;
          }
        }
        //Timer Relay Function END

        //ADC Functions

        //display.setSegments(HIVOLT, 1, 0);

    if (timerflag == 1) {
          display2.showNumberDec(outputvolt, false, 3, 1); // Expect: _14_

          if (outputvolt > 245) {
            display2.setSegments(HIVOLT, 1, 0);
            digitalWrite(TRelay, HIGH);
          }
          else if (outputvolt <= 180) {
            display2.setSegments(L0VOLT, 1, 0);
            digitalWrite(TRelay, HIGH);
          } else {
            display2.setSegments(DONE, 1, 0);
            digitalWrite(TRelay, LOW);
          }
        }

    */

    if (240 < current_Volts)
    {

        digitalWrite(Relay1, LOW);
        digitalWrite(Relay2, HIGH);
        digitalWrite(Relay3, HIGH);
        digitalWrite(Relay4, HIGH);
    }
    if ((90 <= current_Volts) && (current_Volts <= 120))
    {
        digitalWrite(Relay1, HIGH);
        digitalWrite(Relay2, HIGH);
        digitalWrite(Relay3, HIGH);
        digitalWrite(Relay4, LOW);

    }
    if ((121 <= current_Volts) && (current_Volts <= 150))
    {
        digitalWrite(Relay1, HIGH);
        digitalWrite(Relay2, HIGH);
        digitalWrite(Relay3, LOW);
        digitalWrite(Relay4, HIGH);

    }
    if ((151 <= current_Volts) && (current_Volts <= 240))
    {
        digitalWrite(Relay1, HIGH);
        digitalWrite(Relay2, LOW);
        digitalWrite(Relay3, HIGH);
        digitalWrite(Relay4, HIGH);
    }
    //ITimer2.init();
    //ITimer1.init();
    // ITimer1.attachInterruptInterval(TIMER2_INTERVAL_MS, TimerHandler2);
    //ITimer2.attachInterruptInterval(TIMER2_INTERVAL_MS, TimerHandler2);
}

int acVoltage(int adcpin)
{
    int adcvalue = 0, returnresult = 0;
    unsigned long sum = 0, avg = 0, squre = 0;
    double root = 0;

    for (int j = 0; j < 10; j++)
    {

        unsigned long currentMacro = micros();
        unsigned long currentMillis;
        if ((currentMacro - previousmacro > 2000))
        {
            previousmacro = currentMillis;

            adcvalue = average(adcpin);
        }
        squre = (long)adcvalue * adcvalue;
        //delayMicroseconds(667);
        sum += squre;
    }

    avg = (long)sum / 10;
    //Serial.print("after average of squre");
    //Serial.println(avg);
    root = sqrt(avg);
    returnresult = (int)root;
    return returnresult;
}

int average(int pin)
{
    int sum = 0;
    float avg = 0;
    int val = 0;
    int funsend;
    for (int i = 0; i < 5; i++)
    {
        val = analogRead(pin);
        sum += val;

    }

    avg = (float)sum / 5;
    funsend = round(avg);
    //Serial.print(" average function");
    //Serial.println(avg);
    //Serial.print("Value");
    //Serial.println(funsend);
    //delay(20);
    return funsend;

}
</code>```

Please describe what you mean when you say "not stable".


text:
How to connect neo 6m 6pin module with nodemcu v3
I got this neo 6m gps module from a broken drone. and i would like to connect it to nodemcu v3 board.
most of the gps module that i have seen are with 4 pins (vcc,gnd,tx,rx) , but this module has 6 pins (gnd,vcc,txd,rxd,scl,sda) .
i am not sure how to wire it up and what library to use.

Have you read the datasheet for the NEO M6?

@MatsK  i am a just beginner, don't understand much about diagram.

Ok, then just hook up 3 wires like this: GND - GND, Tx - Rx, Rx - Tx. And then start to read this: https://lastminuteengineers.com/neo6m-gps-arduino-tutorial/  NB The NodeMCU is a 3,3 volt device and the url is using a std Arduino, a 5 volt device, please adapt accordingly.

The 4 pins VCC/GND/TX/RX are the same as any other GPS module.
The other two pins, SCL and SDA, are nothing to do with the GPS. They connect to the HMC5883L compass chip.
Use the normal TinyGPS library for the GPS, and a HMC5883L library (such as this one) for the compass.

Rx and tx pin are for UART communication and SCL and SDA are for I2C communication. Most common gps module use UART communication method .... You can go with UART too this will help you to choose better  library option. Most library file are coded for UART method.  I recommend you to use vcc , gnd ,rx and tx pin. Escape scl and sda pins.

The I2C is not connected to the GPS. It's only connected to the HMC5883L.

I have just cleared about communication protocol ...not suggested to use i2c communication


text:
Problem with serial input from android serial usb app
I'm using two (nrf24L01 + Arduino Uno) nodes to communicate with each other. Serial input from node1 will be sent to node2. A special character 'p' when sent to node2, it will reply that it's available. It is working fine when using arduino ide serial monitor on pc. When I use serial usb app on android to get serial input only the text is sent to another node and the special character sent does nothing and prints like any other message.

Please show your code.

if it works correctly with a PC, then the problem is not with the Arduino .... make sure that the android app is set up correctly

I checked the Android app settings and turned off newline controls. Now everything is working fine.

I solved this problem by turning off CR+LF and selecting None for newline in send section. CR+LF was adding something extra to my input. By removing that program works fine with Android.
About CR,LF :
"Newline is a control character or sequence of control characters in a character encoding specification that is used to signify the end of a line of text and the start of a new one. Some text editors set this special character when pressing the ↵ Enter key." - (Wikipedia)


text:
Cannot detect Bluetooth device when connected to female receiver with PS4 Joystick
I am trying to connect the Bluetooth transmitter to a female receiver via an Arduino Uno. The button blinks, but the Bluetooth is not visible in any device.
i want to connect PS4 controller using HC05
I am sharing my code below:
#include<SoftwareSerial.h>

/* Create object named bt of the class SoftwareSerial */
SoftwareSerial bt(2,3); /* (Rx,Tx) */

void setup() {
  bt.begin(9600); /* Define baud rate for software serial communication */
  Serial.begin(9600); /* Define baud rate for serial communication */
}

void loop() {
  if (bt.available()) { /* If data is available on serial port */
    Serial.write(bt.read()); /* Print character received on to the serial monitor */
  }
}

Can anyone help me out with this ?

There is no "female" with bluetooth, just master and slave. Maybe you need to first configure the HC-05 to work as a slave device. Did you try that?

@chrisl Perhaps he has the same experience like me. Master = female, slave = male (me). Sorry I couldn't resist. :-) I'm also curirous about the button that blinks.  And now seriously: (Karan wagh) The HC05 has to be configured. Here is a link that might help: https://create.arduino.cc/projecthub/electropeak/getting-started-with-hc-05-bluetooth-module-arduino-e0ca81

I tried that but got no success @chrisl

Then please also explain what you tried and how it didn't work. We need more information, or we are not able to help

we followed this https://www.instructables.com/Connecting-HC-05-Bluetooth-Module-to-Arduino/  @chrisl


text:
Ok to Connect 2.9V Stepper to 3.3V pin?
So I have a stepper motor that's rated for 2.9V and 0.8A and I connected it to a L9110 Driver and I wanted to drive it with my arduino. But I don't know how to drive it safely without damaging the motor. I am using the stepper.h library and thought of connecting it to 3.3V pin on the Arduino but I am a bit concerned.. is it Ok to power it with 3.3V if no then What can I do?
Edit: the L9110 module I am using is a dual H Bridge.
Edit2: I was Indead Powering the Stepper and the Module directly from the arduino.. luckily the arduino survived.
Edit3: So I didn't have a 3V power supply so I used a Voltage Divider with a 9V battery and connected the L9110s module with the battery (after its voltage divided) and the module powers on.. but when the arduino starts driving the stepper the module's led starts Flickering instead of staying on and the stepper doesn't turn... I don't know what is the problem.

I don't think the motor will be your problem. I think the arduino is in danger. If the motor is powered 0.4V higher than specified, who cares. But you try to draw 800 mA from the arduino 3.3V output. That's too much. Just use an external power to drive the motor, not the arduino. BTW: I assume you' ll use a L9110 Module with two driver chips. One L9110 alone is only useful for DC motor; not for steppers.

It may just because I'm not completely awake, but I'm finding it difficult to follow your wiring description.  A diagram or schematic would be better.

It is unclear from your description / question if you are connecting a stepping motor directly to the pins on an Arduino.  Further, we do not know which Arduino you are using.  But, in general, an Arduino's outputs are likely directly connected to the processor.  And there are no (or very few) processors that can survive getting 800mA pulled from one of their output pins.  So do be very careful or you may burn out the processor.

Oops... I powered it directly from the arduino... but it's still alive(I think)

Is it fine if I used a 1n4007 diode to "protect" The Arduino UNO from The Motor? Or it will be useless??

"I didn't have a 3V power supply so I used a Voltage Divider" - You cannot use a voltage divider to power a circuit, because the voltage will be dependent on how much current your circuit draws. There is no cheaping out there. You should really buy a fitting voltage regulator. They are not that expensive. And if your circuit is dtationary, you could get stable and powerfull 5V from typical USB phone chargers. Then buy a voltage regulator for getting from 5 to 3V, which also can provide enough current.

There are very cheap dcdc converters with an onboard potentiometer to adjust outout voltage. The only cheaper (and very dirty) solution could be to use a 5V usb charger and put 3 Si diodes in series. The diodes will drop the voltage to 5V-3×0.7V=2.9V. The diodes should be rated for 1W power dissipation, just to be save

use two AA cells in series ... use C or D cells for more capacity

@jsotola, Doesn't a motor driver have solid state circuitry that needs a regulated power source? Or is it just an H-bridge built with MOSFETs that can tolerate a wide range of input voltages?

@Duncan the  L9110 datasheet specifies a wide power supply voltage range

Motors draw a LOT of current compared to CMOS circuits.
The 3.3V output on most Arduinos can only provide a very small amount of current. The Arduino Uno, for example, says it only provides a max of 50mA from its 3.3V regulator. Your motor driver probably needs >10X more than that.
The overload protection on the Arduino's voltage regulator will probably kick in and cause it to shut off. It might take a while to cool down before 3.3V output comes back. I've heard that the protection on Arduino knockoffs doesn't always work, so you could also fry the voltage regulator if you try to draw too much from it.
Bottom line: Don't do that.
Get a high current supply for your motor driver.

I was powering the driver directly from the arduino. Thankfully the Arduino isn't Dead (yet) so I decided to Use a 9V battery with a Voltage divider to power the driver and the motor But now when the arduino Starts driving the stepper the driver's led starts flickering instead of staying constant. And now the motor doesn't turn (see my last edit for more details)

If you're talking about one of those little square 9V batteries, forget it. Those don't have enough juice to power an Arduino for long, never mind a motor. They have very low total energy storage (measured in mAh, 500 mAh is common) and very low peak current. (A little googling said "Estimate 350 mA peak for 10 minutes".) If your motor needs 800 mA, you have less than half the current you need to even run the thing. It might work for a few seconds when the battery is completely fresh, but it might not.

Do you have any recommendation for any Readily Available power source for that Motor?

Nope. Look at the current requirements, and find a switching supply that provides at least 20% more current (so you have some "wiggle room".)


text:
How to get a specific value from an unknown number of JSON representations?
I am using ArduinoJson and ESP8266HTTPClient.
Say I have a DynamicJsonDocument that has an unknown number of entries with information on different persons:
[
    {
        "ID": "12345",
        "name": "John Smith",
        "Address": "Street 1"
    },

    .
    .
    .

    {
        "ID": "00345",
        "name": "Paul Anderson",
        "Address": "Street 2"
    }
]

I would like to somehow store the values associated with the key "name" for all the different persons. For example, have something like:
String name1 = "";
...
String nameN = "";

.
.
.

Serial.println(name1);
...
Serial.println(nameN);

To print a list of all the names:
John Smith
Paul Anderson

The only information of the JSON I have beforehand is the keys each entry will have. I do not know how many entries there will be.
How can I go about this?
EDIT: Why I want to do this:
I am using the ESP as a client to get information from a server in the form of a JSON similar to what I wrote above. At the same time, I am serving a simple HTML website by doing server.send(200, "text/html", HTML_code); using the ESP as an AP. I was able to just cram the whole JSON into the HTML as text, but I would like to just have specific information from the JSON, as explained above.
I am aware what I am doing is far from elegant or the "correct way to do it", but I am learning all of this, so any criticism and help is more than welcome :)

You may want to make it clear why you want to do this.  Because, as is, it sounds like you're just duplicating data for no reason.  And if there is a good reason for doing this, it will likely give some shape to the answer.

You know the size from JsonArray::size() so just iterate over the array getting each object in turn. It's also recommended to use iterators instead of a for loop.

I added an edit explaining just that, maybe now it is more clear?

your explanation seems to suggest that you are thinking that the webpage HTML needs to exist in its entirety before the webpage can be served ... you can serve the webpage in pieces ... serve the ... then iterate the JSON
 put name here
, then serve

for simple extractions like that, in the past I've just plucked the values from the JSON as text, using something like strstr(json, "\"key\"") and then strchr(thatString, ',') to get the span from that key's starting point. You could use String methods too, but those tend to cause problems if over-used.

Directly from the ArduinoJson Assistant:
// Stream& input;

StaticJsonDocument<384> doc;
deserializeJson(doc, input);

for (JsonObject elem : doc.as<JsonArray>()) {
  const char* ID = elem["ID"]; // "12345", "13244", "00345"
  const char* name = elem["name"]; // "John Smith", "Jason Statham", "Paul Anderson"
  const char* Address = elem["Address"]; // "Street 1", "Street 2", "Street 3"
}

See also:

How to use ArduinoJson with HTTPClient?
How to deserialize a very large document?

Thank you, I will try this. How would I access for example "Jason Statham" inside the "name" char*?

Serial.println(name);  // prints "Jason Statham"

Wouldn't that print all the names and not a specific one?


text:
client.connect() problem
I'm using XAMPP(version-7.2.1) server in my PC to publish my arduino sensor data in a webpage. I have tried the code above and it shows an error like:

Ethernet configured via DHCP
Connecting...
-->connection failed

I have also followed the steps given in this https://forum.arduino.cc/index.php?topic=40448.0 but it doesn't work.
The code runs till client.connect() after that it doesn't get inside the if(client.connect(server,80)) loop.
The arduino's ethernet shield is assigned an IP by the PC via ICS.
I believe that the problem is in connecting the arduino to the localhost but I don't know how to resolve it. The XAMPP server seems to run properly. I have checked it logs.
I have also posted at https://forum.arduino.cc/index.php?topic=525947.0.
Hope someone can help me
Thanks in advance

#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
DHT dht;
const int sensor_pin = A1;
unsigned int ldr;
byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 33);
char server[] = "192.168.1.7"; // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie. "www.yourwebpage.com")
EthernetClient client;

void setup() {
  Serial.begin(9600); // Serial.begin starts the serial connection between
  computer and Arduino
  Ethernet.begin(mac, ip);
  Serial.println("Ethernet configured via DHCP");
  delay(1000);
  dht.setup(2);
}

void loop() {
  delay(dht.getMinimumSamplingPeriod());  /* Delay of amount equal to sampling period */
  float soilmoisture;
  int sensor_analog;
  sensor_analog = analogRead(sensor_pin);
  soilmoisture = ( 100 - ( (sensor_analog / 1023.00) * 100 ) );
  float temperature = dht.getTemperature();
  float humidity = dht.getHumidity();
  ldr = analogRead(A0);

  Serial.println("Connecting...");
  // Connect to the server (your computer or web page)
  if (client.connect(server, 80)) {
    Serial.println("--> Connected");
    client.print("GET /write_data.php?"); // This
    client.print("temperature="); // This
    client.print(temperature); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.print("&humidity="); // This
    client.print(humidity); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.print("&soilmoisture="); // This
    client.print(soilmoisture); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.1.7"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
    client.println( "Content-Type: application/x-www-form-urlencoded" );
    client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
    client.println(); // Empty line
    client.println(); // Empty line
  }
  else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }
  client.flush();
  client.stop();
  // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
  delay(10000);
}

My PHP code is as follows:
<?php
// Prepare variables for database connection
$dbusername = "x";  // enter database username, I used "arduino" in step 2.2
$dbpassword = "y";  // enter database password, I used "arduinotest" in step 2.2
$server = "localhost"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"
$dbname = "arduinotest1";
// Connect to your database
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword,$dbname);
if (!$dbconnect) {
    die("Database connection failed: " . mysqli_connect_error());
}
$dbselect = mysqli_select_db($dbconnect, "arduinotest1");
if (!$dbselect) {
    die("Database selection failed: " . mysqli_connect_error());
}
// Prepare the SQL statement
$sql = "INSERT INTO arduinotest1.tabletest2 (temperature,humidity,soilmoisture) VALUES ('".$_GET["temperature"]."','".$_GET["humidity"]."','".$_GET["soilmoisture"]."')";
// Execute SQL statement
mysqli_query($dbconnect,$sql);
?>

How do you know till where it runs? What output does it produce? What have you tried to debug? Why do you stop the client twice?

Also asked at: http://forum.arduino.cc/index.php?topic=525947 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

try to change ip to 127.0.0.1?
maybe try NAT at your router.

Have you prove disconnecting your firewall protection? It works for me.

As far as I can see, when you call client.connect(server, 80), you call it with char[] variable that holds char server[] = "192.168.1.7". And from library code it seems that it will call function with those parameters which will try to resolve dns but can't do it and returns 0.
It calls: int EthernetClient::connect(const char * host, uint16_t port)
,when it should call: int EthernetClient::connect(IPAddress ip, uint16_t port)
Source code: https://github.com/arduino-libraries/Ethernet/blob/master/src/EthernetClient.cpp
So you need to change char server[] = "192.168.1.7"; to IPAddress server(192,168,1,7);
That way it will call the right connection -function and wont get stuck with dns.
Edit: added details

Check the server ip is correct and server is running. Then check the return value of client.connect() function. If it's a 0 then most likely your server is behind a firewall. If so, unblock the apache server to pass through it. I had this similar issue with wamp.
Although 0 is not a valid return code for client.connect() according to http://www.arduino.cc/en/Reference/ClientConnect , it weirdly returns a 0. Oherwise it will give you a clue.
Also use IPAddress class for assigning the server address instead of using char [].


text:
PIR with Arduino - detects only first motion
The following is an Arduino sketch for 3 PIR sensors. Two PIRs can activate 1 buzzer and show status in an LCD. The third PIR activates a relay.
The problem is only the first motion gets detected and the "L" indicator stays on. After that there is no activity.
The same Arduino Uno board is working fine with other sketches. PIR sensors are also working. The sketch seems to be working on simulation as well.
Link to simulation
"L" LED is the LED close to the 13th pin. above the TX,RX LEDs. The PIRs are set for the lowest time, sensitivity medium. The issue exists even without connecting the PIRs/relay. There is one beep from the buzzer, it happens 4-5 seconds after turning the board on, with that the "L" led goes on - forever.
The LCD also has an issue, it shows filled blocks on the first row, nothing else.
I tried connecting only one PIR and 1 buzzer to the board.
What is wrong?
#include <LiquidCrystal.h>

unsigned long time;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
int pir1Pin =9;
int pir2Pin =10;
int pir3Pin =11;
int buzzerPin =8;
int relayPin = 12;
int backlightPin = 13;
long previousMillis = 0;
long interval = 1000;

void setup() {
  lcd.begin(16, 2);
  pinMode(pir1Pin, INPUT);
  pinMode(pir2Pin, INPUT);
  pinMode(pir3Pin, INPUT);
  pinMode(relayPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(backlightPin, OUTPUT);
  digitalWrite(relayPin,HIGH);
  delay(1000);
  digitalWrite(relayPin,LOW);
  Serial.begin(9600);
}

void loop() {
  if(digitalRead(pir1Pin)== HIGH) {
    digitalWrite(backlightPin,HIGH);
    lcd.setCursor(0, 0);
    lcd.print("Pir 1 Active");
    beep();
  } else {
    lcd.setCursor(0, 0);
    lcd.print("Pir 1 is off");
    digitalWrite(backlightPin,LOW);
  }
   if(digitalRead(pir2Pin)== HIGH) {
     digitalWrite(backlightPin,HIGH);
     lcd.setCursor(0, 1);
     lcd.print("Pir 2 Active ");
     beep();
   } else {
     lcd.setCursor(0, 1);
     lcd.print("Pir 2 is off");
     digitalWrite(backlightPin,LOW);
  }
  if(digitalRead(pir3Pin)== HIGH) {
     while(digitalRead(pir3Pin)==HIGH) {
       digitalWrite(relayPin,HIGH);
     }
   } else {
     digitalWrite(relayPin,LOW);
   }
 }

void beep() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    for (int i=0; i<500; i++) {
      digitalWrite(buzzerPin, HIGH);
      delayMicroseconds(500);
      digitalWrite(buzzerPin, LOW);
      delayMicroseconds(500);
    }
  }
}

You say “the "L" indicator stays on”.  What is the "L" indicator?  Also, what amount of time are the on-time pots on the PIR units set for?  If set for several seconds, could be causing the problem.

@ James Waldby - jwpat7, It is an LED marked as "L" on the board. the LED close to the 13th pin. above the TX,RX LEDs.
The PIRs are set for the lowest time, sensitivity medium.
The issue exists even without connecting the PIRs/relay.
There is one beep from the buzzer, it happens 4-5 seconds after turning the board on, with that the "L" led goes on - forever.

I don't really know what the problem is with your setup, but here are a few suggestions to try:

Several PIR guides (1,2,3,4) recommend using a pullup resistor on the open-collector signal pin of some models of PIR sensors.  You could also (or instead) say pinMode(pir1Pin, INPUT_PULLUP); (and so forth) rather than pinMode(pir1Pin, INPUT);.  Note, for each PIR, attach a voltmeter to its output (or, to its input on the Uno).  Trigger the PIR and verify that the signal acts as you expect it to.
Use a different pin number than 13 for your backlightPin.  The Uno's digital pin 13 corresponds to the on-board LED (presumably the LED your question calls 'L').  If you use separate pins for the backlight and the on-board LED, you can then use the on-board LED as a debugging aid.
Your code arrangement if(digitalRead(pir1Pin)== HIGH){ ...
lcd.print(...); ... beep(); }else { ...
lcd.print(...); ... } (and similarly for pir2Pin) will print stuff to the LCD on every pass through loop(), that is, every few milliseconds.  It might make sense to have variables that record previous readings on those pins, and only update the LCD when a pin reading changes.  (Without other changes, this change would lead to only one beep when the PIR triggers, rather than a train of beeps at one-second intervals.  In this case if you want a train of beeps, you would need a beep-status variable.)

This is not a complete answer because I couldn't figure out why the beep only happens once. But if I'm not mistaken, if your code would work as you intend the first motion gets detected and the code jumps to beep. There it will be stuck for 500x(500+500) ms. You would never get results for pir2 or pir3 if the setup is in a way that you can't trigger pir2 independently from the others.
Therefore:
Use pulldown resistors as mentioned by others.
Read all the pir states and save them, and afterwards run the LCD code and then the beep code.
Your system will be unresponsive for as long as the beep code runs.

To supplement, use an I2C backpack for the LCD and fmalpartida's newLiquidCrystal library. Set the jumper to autoreset the trigger.
Wire VCC to 5V
Wire S+ (outputs 3V3 when tripped) to D2 (INT0) - or whatever you use...
Wire GND to GND


text:
MAX30102 showing Heart rate: 0.00bpm / SpO2: 0%
I am using a MAX30102 to monitor SpO2 and heart rate using the https://github.com/oxullo/Arduino-MAX30100 library and the minimal example, but it is not showing any value change.
It only shows zero and in the library tester example it is also showing a timeout error for die temperature.
I removed all 3 pull up registers and given 5 v supply.

Please help to get correct result; I will be thankful.

Have you used pull-up resistor with 5V?

the tester example, checks connections on the startup. are they ok ?
you have to put your finger on the sensor, but not pressing againts it, and without shakes or movements for a few seconds before the results start to change. also, you can decrease the led current (uncomment it in the example) and try again.

To identify the issue, run I2C Scanner and check the address of this module on the Serial Monitor.
If the I2C Scanner program is not able to detect the module, then either the module is defective or connections are wrong.
If the I2C Scanner program is able to identify the sensor, then check with other libraries.


text:
Is there a 3.3V and 12V 18650 circuit?
Is there an all in one circuit which regulates charging, protects and steps up/down an 18650 battery to 12V and 3.3V at the same time, so I can power a sensor and my ESP32?

Are you asking for a ready to use module, or for a circuit, that you can build yourself?

@chrisl preferably a ready to use module

there probably is such a module ... asking where to get one is an off topic shopping question

in all ways but convenience, it would be better to use an LDO to take the battery voltage down to 3.3 and use a 12v-only controller.

@dandavis can I even use an LDO safely? Won't I need some protection against over discharge?

I would suggest using a 12V controller, and then adding a 3.3V switching regulator using the 12V supply. That would be 2 off-the shelf components and you're done.

You MIGHT be able to find a battery controller that has both 12V and 3.3V outputs, but if not, a 3.3V switching regulator that can convert 12V to 3.3V efficiently is very easy to come by.


text:
Arduino measuring high-voltage electric fence
I would like to know if someone has experience with measuring high voltages using an Arduino.
I know you can use resistors to lower the voltage, however.
I want to be able to measure the pulses of an electric fence used to prevent farm animals from escaping. These pulses are high-voltage and will not always be a similar voltage. I want to read these voltages, to scan for differences.
So, I wondered if someone has done something like that, and if the Arduino gets weird when it gets a voltage above 5 V at a low amperage on its analog port.
--here some possible solutions for those wanting to know the answer--
-mostly based on comments and answers below-

Using resistors as a voltage divider while keeping an eye on the maximum spark gap distance and capacitive coupling.
using a transformer/coils to reduce the voltage.
using a high voltage probe to measure it.
using neon bulbs or other light sources to measure it.
charging a capacitor and measuring discharge time with high resistance(only works for the total power)

-this list is meant as a summary of what is discussed further ideas and solutions are still welcome-

Duh, that's typically a couple thousand volts. I fear a simple resistor won't do, since the voltage is high enough to cause severe interference or jump trough the air. And that would destroy your equipment quite spectacularly.

Do you really want to measure it, like proportionally, or just see that it's still operating?

I don't think that the high voltage is the problem. I grew up on a farm in Germany and There were many occations to experiment with el. fences, when I was a child ;-). The voltage is not high enough to "jump" over more than a fraction of a millimeter, and that only with a perfect ground. I would say the only thing that jumps is the farmer if, he touches the fence. Yes, I've tried it. Yes, I jumped.

One of the problems is the variations in the voltages. You can be sure that all pulses are of the same amount. You could build a voltage divider, sometimes it is sufficient, sometimes not.  The next problem is the length of the pulse, How can you be sure you get the peak voltage, if you only take probes at discrete times? So I would say the arduino allone is not fast enough to give you reliable results.

If you are fit in electronics, build a voltage devider with two high watt, low value resistors. Add a peak detektor to it and meassure the voltage with your arduino. Use a 5V Zehner diode to protect the Arduino pin from high voltage. Zehner diodes are slow, so you might want to use N shottkey diodes that add to about 5V.

i think that you can buy a fence tester that contains a neon bulb ... use a photo sensor to detect the light from the lamp

@PeterPaulKiefer: at 10kV, the pulse can build a spark of at least 10mm, which is absolutely significant given the physical size of a breadboard or a resistor.

Typically you would use a long chain of resistors. The voltage across each one is then below the maximum rated voltage for that individual resistor (and any distances involved). However a transformer may be a better solution to give galvanic isolation.

@PMF A 10kV signal with a high frequency can do that (e.g. Tesla coils). A single pulse has not the power and not the time to to ionize the air. The pulse can create a high potential electric field, but the wires are too small to take much voltage from that. If you keep the arduino 10 cm away from the fence wire, the field has nearly no impact. A direct voltage coupling whith a voltage devider is the only way to build a cheap measurement solution, as long as you get it to measure fast enough to find the pulse peak or use a peak detector.

Using a trafo is diffficult, because you have no sine wave, so the trafo has impact of the shape of the signal. Then it gets difficult to reconstruct the peak. And as I understand, the different peak voltages of the pulses are the goal of this exercise.

Ahh, one thing I forgott to mention. Of cause the Arduino is not the only one who is in danger. 10kV (even  a short pulse) can kill you. E.G. if your the owner of a weak heart. So, be carefull.

@PeterPaulKiefer I just want to throw in another point: you don't need to measure pulses. The voltage on an electrical fence is static: when touching the wire, you get a shocked immediately - you don't need to wait for the next pulse. Pulses are only used to recharge the fence's capacity.

@SimSon As soon as you add the voltage devider to the wire it will be discharged. You will only get the peak voltage at the peak of the pulse. You need to meassure exactly at the peak of the pulse or you use a peak detector, if you want to measure the differences in the peak voltage, like IMHO the OP asked.

In my experience electric fences put out high voltage AC. That's the easiest, low-tech way to boost voltage, after all - a transformer many time more windings in the secondary than in the primary would boost an AC input to high voltage quite simply.

https://forum.arduino.cc/index.php?topic=18043.0

While my question describes an electric fence to make it more usable and understandable for everyone, the actual system uses a specific coreless coil for self-inductance. it runs from 12v and is meant to detect objects that respond to the magnetic or electromagnetic charge. since the coil itself has quite high resistance(+-50 ohm) the output current and voltage are quite safe and below an actual electric fence. I can make sparks with it to the battery terminal by slide-disconnecting it I get at most around 2mm sparks(see st. jacobs ladder). normal sparkgabs work up to around 0.1mm at most.

@timemage I need to actually measure it to detect the difference in self inductance. so I can use that to detect objects and their relative distance/location.

@PeterPaulKiefer perhaps I might be able to get it stable enough with some small capacitors then I can measure the total energy instead of the voltage which in this case should give good results as well that way I stabilize the highest peaks and it might better suit the arduino's peak.

You are talking about measuring 2 to 10 kV pulses, with about 1 to 5 J of energy per pulse.
The maximum current may be very low, but the voltages you want to measure are very high, and will very probably damage your Arduino without proper measures.
You will at least need a voltage divider to reduce the voltage the Arduino sees to 5 V (or 3.3 V for some Arduinos) to be able to make a measurement with the Arduino's ADC.
The voltages are high enough to bridge a fair distance with a spark; they could well bridge a physically small resistor or the distance between two connections on your breadboard or PCB.
To be honest, I think you shouldn't go anywhere near such voltages with an Arduino, unless you know exactly what you are doing when preparing the signal for an Arduino's ADC pin.

Consider purchasing a high voltage probe for a VOM. They are very high in resistance, if you go low you will drain all the energy out of the fence.  Nice part they are designed for this type of voltage, not a kludge device. This would go in series with a load resistor then measure the voltage across the load resistor which has one end grounded to the fence ground. International code limits the voltage to 10KV some countries it is lower.

I think perhaps I might make a transformer like some have told in the comments, and then use a divider with extra isolation. some peak detection would be great however in a way where it would only pass through the highest differences.
I was also when starting to think about this project thinking about designing my own computer for it or using analogue equipment, however, I thought that Arduino would be great to use because I can also easily perform all other kinds of instructions.

@Gil I will try that, I have some laying around anyway so testing it would be great. I might also try making a custom one since that would make it more readable and less tape and wire.

When you say 'scan for differences', do you mean differences along the fence, or something else?  Do you plan to use the Arduino as a portable voltmeter?  If so, buying a HV probe for a standard voltmeter sounds a lot more practical.
However, if you plan to install multiple sensor points along the fence so that you can continually monitor pulse amplitudes along the fence, then that is a different kettle of fish, especially if you are thinking about outdoor use over a long fence length.
Can you elaborate a bit, please?

I mean to use a system similar to an electric fence. but more compact and coil like to use the self-inductance to measure changes in nearby metallic or water like objects. since in versions where I manually feel for the differences in shock values it seems to respond really good to metals where a simple coil would give clearly feelable different shock intensity when I introduced small metal objects, at ranges my commercial metal detector can not even detect them.

Note that the coil I use at the voltage and the maximum allowed charge and discharge time cycle is tuned to be rather safe even when put in massive cast iron. I would of course not recommend anyone to use its hands at a high voltage circuit, especially when not sure it is tuned properly to around half of the intentionally dangerous values.


text:
Doubt in coding part in blink without delay
Code 1 (here unsigned long currentmillis = millis() is in loop area):
const int LED = 2;
unsigned long previousmillis = 0 ;
const long delaytime = 1500;
int ledstate = HIGH;

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

void loop() {
  unsigned long currentmillis = millis();
  if (currentmillis - previousmillis >= delaytime) {
    previousmillis = currentmillis;
    if (ledstate == HIGH) {
      ledstate = LOW;
    } else{
      ledstate = HIGH;
    }
    digitalWrite(LED,ledstate);
  }
}

Code 2 (here unsigned long currentmillis = millis() is above void setup()):
const int LED = 2;
unsigned long previousmillis = 0 ;
unsigned long currentmillis = millis();
const long delaytime = 1500;
int ledstate = HIGH;

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

void loop() {
  if (currentmillis - previousmillis >= delaytime) {
    previousmillis = currentmillis;
    if (ledstate == HIGH) {
      ledstate = LOW;
    } else {
      ledstate = HIGH;
    }
    digitalWrite(LED,ledstate);
  }
}

Code 1 is working and Code 2 is not working. What is the significance of the position of unsigned long currentmillis = millis() here and why?

This is a common misunderstanding for Arduino beginners.
In the second code you do
unsigned long currentmillis = millis();

outside of any function, meaning at global scope. These variables are declared at the very start of the program, even before the initial Arduino stuff is configured (like the configuration of Timer0 for getting millis() to work). The variable will have the value zero. And variables are not magically tied to a source. What you are doing there is a one-time assignment. currentmillis will not have future values of millis(). It will stay the same until you change it in your code. In your second code you do not ever change currentmillis, thus is will stay at the same value forever, preventing the code from working correctly.
In the first code the value is assigned at every loop() iteration, so you can be sure that it has a very up-to-date value of millis() when you use it afterwards.
This coding principle works exactly like you would bake a pizza, regularly looking at the clock to check the time while you are doing other things. With your first code you look very regularly at the clock to not miss the time to get the pizza out of the oven. With the second code you only look once at the clock, even before you have put the pizza in the oven, and then never again; so your pizza will burn.

Got it thanks @chrisl


text:
Leonardo clone being recognized by Windows as a broken Linino One - wtf?
I'm running a Velleman VMA103, which is advertised as a clone of the Leonardo. Both use the 32u4 chip, and the pinout is exactly the same. However, when I plug it in, the drivers do something weird.
For about 5 seconds after pressing reset, the Arduino IDE will recognize the Leonardo on COM9, and the Windows device manager will show "Arduino Leonardo bootloader" then, the COM9 device will disappear and a device will be shown in the Other Devices tab as a LININO ONE, with no drivers installed. How is this possible?
I've reinstalled the IDE, no help there.

How is this possible? The quick answer is "Windows". Obviously the plug-and-play manager is playing you a trick. If you really want to dig into this start by checking the USB signatures. The bootloader might be presenting an "illegal" signature which is owned by another company.

USB is a complex protocol.  There is a USB device and vendor ID used to tell the difference between a USB printer and USB camera.  Perhaps the clone is not setup correctly.  Connect the clone to a Linux computer and type "lsusb".  Or, you may have multiple drivers installed on your Windows machine all fighting to be used by the USB device.  You didn't say what Windows you are using - so search for how to deal with this on the internet.

Test it with another computer. If that is the same problem, then you should burn new firmware into it (the official Arduino Leonardo firmware). That should get rid of all the nonsense. Do you have a programmer or a Arduino Uno board that can be used as a programmer ? Once that is connected properly then you can use the Arduino IDE to burn new firmware.

USB associates a driver, and thus what it calls a device, with the VID and PID that the device announces. Arduino PIDs are in a horrible mess, and there are many different devices that use the same PID. On top of that you have other makers also using the same VID/PID pairs and providing their own re-named Arduino driver files for their devices.
And then of course you have the problem that it is down to the firmware ("sketch") installed on the Leonardo that determines what VID and PID is shown to the computer.
So you have a set of possible scenarios - the main two being:

You have a driver installed that identifies the VID/PID pair of the Leonardo as something else
You have firmware installed in the Leonardo that gives the wrong VID/PID pair for your drivers

Check 2 first by installing the Blink example into the Leonardo (you can still upload firmware since it goes to bootloader mode at first as you have seen). If it changes the shown driver then you had some broken firmware installed. If it doesn't then you may be running a patched installation of the Arduino AVR core that gives a different default VID/PID pair, or you may just have the wrong board selected in the menu.
If you still have trouble then uninstall whatever driver is associated with the detected device and reinstall the official Arduino drivers that come with the IDE.
You can also delete the IDE and its associated downloaded packages and reinstall the latest version to ensure that you don't have strange patches and settings in there corrupting things.

A Leonardo sketch can change the Leonardo's VIP/PID values?  I didn't know that.  Regardless, perhaps it would improve the answer if you made it clear that this is possible only on some Arduinos.  I'm thinking the old Arduino Uno's had an FTDI chip with fixed VIP/PID values.


text:
Arduno as bridge between two i2c masters
so I am gonna just jump right into the topic. Recently, I have been trying to build a project where I need to connect an ev3 to a raspberry pi. I have decided doing it by i2c after reading (and successfully replicating) an article about connecting an ev3 to arduino by i2c https://www.dexterindustries.com/howto/connecting-ev3-arduino/.  However, after setting it up with raspberry pi, I realized a huge problem that I am facing, both of these devices acted as masters and I could not get them to connect to each other. So I decided to use an arduino between those two which transports the data that it receives to the other device, which I couldn't get working. I have no idea how to get it working anyways, it was just a hopeless try. Now I am doubting myself If I can't do it. So my question is, is such a project possible or should I just give up. If I should, what type of communication do you suggest that I use.

Your question is confusing.  You successfully connected an Arduino to a device using I2C?  Then you added a Raspberry Pi putting 3 I2C devices on the same I2C bus and it does not work?  And instead of posting this to raspberrypi.stackexchange.com you are posting it here in arduino.stackexchange.com?  FYI, it is hard to imagine an I2C bus with more than one master.

An Arduino can be put into I2C slave mode, so I imagine a Raspberry Pi can be as well. I suggest asking on the Arduino Pi Stack Exchange how to do it. I can migrate this question there if you like.

https://raspberrypi.stackexchange.com/questions/5584/i2c-raspberri-pi-as-a-slave


text:
How to create a String with Temperature Value From An int Value
The following code is for a temperature controlled relay which turns a DC fan on and off when the temp threshold is breached. I'm using a DS1820 Temperature sensor and the code for this has several variables including WholeDegrees & FractDegrees Which are the whole number of degrees and the fractional number of degrees. I'm wanting to be able to set the threshold to lets say 23.25 Degrees so that when the temp rises above that then the fan comes on.
I'm trying to do this by using a two condition if statement howeveer, the FractDegrees are causing me a problem because if condition 1 is true and and the WholeDegrees is greater than 22 but the second condition the FractDegrees is lower than 25 then the relay turns the fan off again. So I get the fan turning on for a split second and then off, then on & off again which isn't a problem when the temperature sensor is at roughly the temp I want to set the threshold at but when it's at say 40 Degrees The fan cuts in and out whilst cooling until the sensor is roughly at the threshold value again.
I have kinda had a go already but failed which you might see in the //'d out code but is there a way that I can put these two values WholeDegrees & FractDegrees into a string so that I could have a string with the temp value and then use a single condition if statement to turn the fan on and off by checking the strings value instead?? I'd want the string to be "WholeDegrees.FractDegrees" So that I could just use the if statement to ask if the temp was greater than 23.25 degrees.
The code I tried returned a value of "0.0" which obviously wasn't the temperature value but I couldn't understand why......
#include <OneWire.h>
int inPin = 10; // define D10 as input pin connecting to DS18S20 S pin
OneWire ds(inPin);
int relay1 = 8; // define relay Signal Pin to Digital Output 8
//String stringOne, stringTwo, stringThree;

void setup(void) {
  Serial.begin(115200);
  pinMode(relay1, OUTPUT);

}

void loop(void) {
  int HighByte, LowByte, TReading, SignBit, Tc_100, WholeDegrees, FractDegrees;
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];
  //stringOne = String(WholeDegrees);
  //stringTwo = String(".");
  //stringThree = String(FractDegrees);

  if ( !ds.search(addr)) {
    ds.reset_search();
    return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);

  delay(250);

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);

  for ( i = 0; i < 9; i++) {
    data[i] = ds.read();
  }
  Serial.print("Temperature: ");
  LowByte = data[0];
  HighByte = data[1];
  TReading = (HighByte << 8) + LowByte;
  SignBit = TReading & 0x8000;
  if (SignBit)
  {
    TReading = (TReading ^ 0xffff) + 1;
  }
  Tc_100 = (6 * TReading) + TReading / 4;
  WholeDegrees = Tc_100 / 100;
  FractDegrees = Tc_100 % 100;
  if (SignBit)
  {
    Serial.print("-");
  }
  Serial.print(WholeDegrees);
  Serial.print(".");
  if (FractDegrees < 10)
  {
    Serial.print("0");
  }
  Serial.print(FractDegrees);
  Serial.print(" C\n");
  //int tempthresh;
  //tempthresh = (stringOne&&stringTwo&&stringThree);
  //stringOne += stringTwo;
  //stringOne += stringThree;
  //Serial.println(stringOne); // RETURNS VALUE OF 0.0 When I want Temperature Value to be returned
  //Change The Figure "22" To Adjust The Temperature Threshold To Turn Fan On.
  //Currently Set to Keep Temperature At Or Below 23.25 Degrees
  if ((WholeDegrees > 22)&&(FractDegrees >= 25)) digitalWrite(relay1, HIGH);
  else digitalWrite (relay1, LOW);
  delay(250);

}

As has been pointed out looking for a temperature to that level of accuracy on a sensor that is only accurate to 1 degrees in an application which only needs accuracies of a few degrees is just adding extra complications for no real world benefit. In this situation just looking at the whole number part is good enough.
But ignoring the final application this is still a programming question which should be answered.
Using strings to compare numerical values is a very very bad idea. Even ignoring the wasted memory and CPU time involved converting things to a string performing a string to string comparison to evaluate the value is often problematic at best. Normally you'd do it by converting the string to a float.
Which brings us to the easiest solution, as Jot indicated, use a float:
float temp = WholeDegrees + FractDegrees/100.0;
if (temp >= 23.25) { ... }

That's by far the clearest and easiest way to perform the calculation but floats are CPU intensive. There are other, faster ways to do it.
You could do everything in 100ths of a degree, this is a better because ints are a lot quicker to work with and take up less memory than floats. But unless you add comments it's not quite as clear as the float version.
int temp = WholeDegrees*100 + FractDegrees;
if (temp >= 2325) { ... }

Or finally you could do something like your original attempt but fixing the logic. This would probably be the fastest and lowest memory of the lot since it only involved 8 bit calculations which on an 8 bit processor is a big benefit. But of the 3 it's also the least obvious what is happening.
if ( (WholeDegrees > 23) || ( (WholeDegrees == 23) && (FractDegrees >= 25)) ) { ... }

In the Arduino IDE, in the Library Manager, are the OneWire library (by a lot of people including Paul Stoffregen) and the DallasTemperature library (by Miles Burton and others). You need both.
The DallasTemperature makes using the DS18B20 easier. Especially when there is more than one DS18B20 sensor connected. It can get the temperature by index or with the unique ID number that each DS18B20 has.
Start with the examples of the DallasTemperature that appear in the Arduino IDE menu, for example the "simple" example.
Then you have the temperature as a float, and you can compare it with 23.25.
Even the OneWire library comes with the DS18x20_Temperature example that shows how to calculate the temperature as a float.

Thank you I'll have a look at that. I never thought to check the examples in the libraries themselves.

This code goes to some lengths to separate the temperature into whole- and fractional-degrees, and to do it in floating point. Unless there is more to the job that isn't shown in this code and requires either of those representations, you can do the whole job with integers, much more simply.
The DS18x20 series return temperatures as fixed-point integers. The "DS1820" that you referred to has only 1/2 degC resolution so testing to 0.25 degrees won't be useful. It delivers the result with 1 fraction-bit (binary point to the left of bit-0). This is equivalent to the number of 1/2-degreesC:
DS1820
+---------------+---------------+---------------+---------------+
|   |   |   |   |   |   |   |   |   |etc|16 | 8 | 4 | 2 | 1 |.5 |
+---------------+---------------+---------------+-----------^---+

                                                 binary point

If you're using the DS18b20 or DS18s20, the result is delivered with 4 fraction bits, binary point to the left of bit-3, or the number of 1/16-degreesC:
DS18x20
+---------------+---------------+---------------+---------------+
|   |   |   |   |   |   |etc|16 | 8 | 4 | 2 | 1 |.5 |.25|   |   |
+---------------+---------------+---------------^---------------+
                                     binary point       .125 .0625

To detect a temperature threshold you only need to compare that single 16 bit number to the equivalent 16-bit representation of the threshold value.
Using your threshold of 22.25 degC, you'd compare to "44" for a DS1820: (2 * 22.25). The remaining fraction, .5, gets truncated off. Or compare to "356" for one of the DS18x20 types: (22.25 * 16).
This function to converts a 4-place fixed point number to an ASCII decimal string for printing:
/*
 * Name:          q12p4toa
 *
 * Function:      Converts a q12p4 binary number to ASCII decimal
 *
 * Description:   Convert a 4 binary-places signed fixed point number (Q12.4) to
 *                an ASCII string as: sdddd.dddd
 *                Up to 3 left zeroes are replaced with spaces; 4 decimal places
 *        are always generated.
 *
 * Parameters:    pbuf            - -> array of at least 10+1 bytes
 *            q12p4         - A fixed-point number to 4 binary places
 *
 * Returns:       pbuf
 *
 */

char *q12p4toa(char *pbuf, int16_t fixp)
{
   // If neg, write the sign and negate the number
   *pbuf++ = ' ';      // don't use this leading space if sending to Blynk
   if( fixp < 0 ){
      *pbuf++ = '-';
      fixp = -fixp;
   }
   // Handle the rest as an unsigned int
   (void)snprintf(pbuf, 9+1, "%d.%04d",
          fixp >> 4, (uint16_t)(10000L/16 * (fixp & 0xF)));
   return(pbuf);
}


text:
Can I run Arduino code on a 6502?
I've been doing projects with the arduino boards for a long time and accordingly also with the libs from adafruit etc. But that was too boring for me and I wanted to get more into the matter, so I used youtube and acquired knowledge about the microcontrollers eeproms etc. itself . But now my question is whether I, if I have the necessary interface adapters, etc., can compile the libs from adafruit, etc. and flash the hex file directly onto an eeprom and then use it with e.g. connect and use a 6502. but I need the corresponding settings in the IDE so that the code can be executed correctly, right? and what is the best way to do this? and general tips would also be nice thanks in advance

Perhaps the results of a search for "6502 vs avr" would be enlightening.

your question is same as can I speak Swahili to an Englishman and be clearly understood?

Maybe yes on a C++ level but you have to write the tool chain and all the needed files. That would including all the libraries you use. In about 20 years you may have enough done to start testing.  As far as flasining, if my memory is correct it has no RAM or FLASH so you will also have to design the chip.

No, you can't.
You would fail at the first hurdle: you would need to find a 6502 C++ compiler, and AFAICT there is no such thing.
Without a C++ compiler for the 6502 you would never be able to compile C++ code for the 6502.
The closest you would come is to program in pure C for the 6502, which means you won't be able to use 99% of the Arduino libraries (not counting the fact that many use architecture-specific register access) since they are written in C++ not in C.


text:
Transmitting voice via VLC
The project I'm working on: Short-Range Coded Visible Light Communication System.
Visible Light Communication (VLC) systems use light to transfer data between transmitter and receiver over short-range links. This project intends to build a wireless VLC system capable of transmitting voice between two microcontrollers such as an Arduino or a Raspberry Pi using visible light.
An LED or laser diode is deployed at the transmitter side, and a Light Dependent Resistor (LDR) or photodiode is deployed at the receiving side.
Digital data is transmitted using on-off keying where the LED functions as on-off light. Strings of ones (1) and zeros (0) are transmitted with high frequency such that the LED flicking is undetectable to the human eye.
I'm using an Arduino Uno and this is the code that I used. I'm hearing noise from the speaker, not my voice.
Transmitter code:
// Define microphone pin
const int micPin = A0;

// Define LED pin
const int ledPin = 9;

// Define sampling frequency (in Hz)
const int samplingFrequency = 8000;

void setup() {
  // Set microphone pin as input
  pinMode(micPin, INPUT);

  // Set LED pin as output
  pinMode(ledPin, OUTPUT);

  // Begin serial communication at 9600 baud rate
  Serial.begin(9600);
}

void loop() {
  // Read analog voltage from microphone
  int analogValue = analogRead(micPin);

  // Map analog voltage to PWM duty cycle (0-255)
  int dutyCycle = map(analogValue, 0, 1023, 0, 255);

  // Set LED brightness based on duty cycle
  analogWrite(ledPin, dutyCycle);

  // Print duty cycle value to serial monitor
  Serial.println(dutyCycle);

  // Delay to maintain sampling frequency
  delay(1000 / samplingFrequency);
}

Receiver code:
const int ldrPin = 9;
const int speakerPin = 11;
int voiceSample;

void setup() {
  Serial.begin(9600);
  pinMode(ldrPin, OUTPUT);
  pinMode(speakerPin, OUTPUT);
}

void loop() {
  analogWrite(ldrPin, voiceSample);
  delay(10);
  voiceSample++;
  if (voiceSample > 255) {
    voiceSample = 0;
  }
  int voiceInput = analogRead(A0);
  voiceInput = map(voiceInput, 0, 1023, 0, 255);
  analogWrite(speakerPin, voiceInput);
}

The Serial.println(dutyCycle) in your transmitter is going to seriously slow down communications. It takes 1.04 ms to send a single byte over serial at 9600 baud, and assuming you have 3 digits, plus carriage return and linefeed that will take over 5 ms for each serial print.
However you are trying to sample at 8000 times a second (once per 125 µs) so you simply won't keep up. I suggest removing the serial print.

delay(1000 / samplingFrequency);

The delay function takes a long argument, not a float. 1000 / 8000 will evaluate to zero so the sample rate will not in fact be 8000 times a second.
You may want to consider the delayMicroseconds function.

Did you write this code or ChatGPT? ChatGPT questions are currently banned on Stack Overflow.  I'm not sure about their policy in regards to Arduino Stack Exchange.