text:
Selection of presence sensor
For one of my university projects I need to detect the presence of a person in the shower. In order to do that what I have in mind is use a proximity sensor. If the target is in a distance range (let's say 20 to 50 cm) It will assume that the person is in the shower when the distance measure is no longer in this range then it will mean that the person left the shower. I need to detect all the time of the person in the shower (meaning when he/she gets in and then out). I have read a lot of info and forums to properly choose the type of sensor. However I still don't have a clear answer. About the Ultrasonic proximity sensors I know that they are cheap and more accurate by it can be affected by Temperature, humidity and some ambient noise, all of them which happen in a shower. The other option an Infrared one gets affected by lightning conditions and the surface of the target. The last option I checked is a PIR sensor I know it senses Temperature of the target, but I don't know if it will be affected by the running hot water and also is more expensive. In general, I don't know how the running hot water will affect the detection of the person in shower. Also,so again I don't know how this will work. Sorry for the huge amount of  questions, I am a little bit confuse with all the factors to have in mind. I am hoping someone out there can help a lost newbie like me and give me a suggestion. Thanks a lot :)

There is no one sensor that is perfect, but some are more reliable than others.
Yes, the temperature and humidity can play an important role in your sensing, and has to be taken into account. That's not to say that things like Ultrasound don't have a place in the scheme of things.
There's one word you need to think about here: Correlation.
If one single sensor isn't completely reliable then add a second that works in a different way. If both of them agree that there is someone in the shower (i.e., the sensors correlate) then the probability that there is actually someone in the shower is considerably higher.
The great thing about a shower is you are working in a defined enclosed space. That makes it much easier and there are plenty of sensors which, when combined with others, would be quite good at reliably sensing the presence of someone in that enclosed space.
Some ideas:
Ultrasound above the person's head

Pros:

Simple to arrange.
Safe.

Cons:

Can be fooled by the water from the shower head.
Steam isn't good for them.

Infra-red distance

Pros:

Accurate
Can be sealed

Cons:

Expensive
Harder to work with
Can be blocked by steam

Horizontal infra-red beam

Pros:

Can be positioned outside the shower glass with a reflector inside
Safe

Cons:

Small sensing area
Can be blocked by steam

Pressure sensor

Pros:

People weigh more than water so is very reliable
Simple to interface

Cons:

Hard to install safely
Needs to be completely waterproof and sealed.
Could be a shock hazard if not waterproof

You notice I haven't mentioned PIR. I'm not a fan of PIR for sensing the presence of humans. They work by detecting moving heat sources. If the person is moving (entering an area, walking round a room, etc) then they get detected. If the person stands still (as is often the case in a shower) it "forgets" they are there.
Of the choices above (and I am sure someone would come up with others) I would probably opt for the infra-red beam. Maybe split it into a V shape to cover more area - that is, the beam enters the side of the shower at an angle, strikes a reflector on the shower wall, and is reflected back at another angle. The detector is then placed away from the emitter. You could also have a second set to give better coverage.
Infra-red distance measuring in/on the ceiling could be used to improve correlation and thus the probability that there is actually someone there.
I'd stay away from pressure sensing unless you can get hold of a proper waterproof pressure sensing mat designed for in-shower use. Don't try and make one yourself, waterproofing isn't an easy task, especially when people stand on it all the time.

There is always pressure sensitive mats that are used outside in front of doors etc.


text:
Power arduino from 5v rail of pc molex
I'm building a small device using arduino that should be connected to my pc via a usb header to exchange data with the PC.
What I'd like to achieve is that arduino turns on when the pc is on, whereas it shuts down when the pc is turned off. If I rely on the usb port to provide power to the arduino that might not happen, since some motherboards still provide power to the usb connections even when the pc is off.
Therefore I'd like to power the arduino using the 5v rail directly from a Molex. I know that theoretically I can connect that rail straight to the 5v pin, but what about power spikes? How can I be sure that the 5v input voltage is properly filtered and stabilized? Would it be better to use a LM317 and transform the 12v rail into 7.5v to feed arduino from the vin?

The Arduino will be fine with the 5V rail as long as you don't have a garbage-of-the-garbage PSU. After all, the rest of the computer is much more sensitive than the Arduino.

Yes, I think that as well, but just to be sure what kind of filter could I build to prevent possible (even if unlikely to happen) spikes?

The 5V on the USB port, is coming from the same power supply as the 5V from the molex. You could also switch to e.g. an Arduino Leonardo, which would be able to detect whether the PC is actually on.

So you're saying that if the USB is powered when the pc is off then so is the molex 5v rail? What about the 12v then? I might be able to regulate it down to like 7.5v with a lm317 and then feed it to the vin pin... Changing the board is not a viable option for me in this case.

FYI only the DC Power port (12v) and USB (5v) are regulated, vin is not. 3v and 5v pins are only for output.

The 5v of an ATX power supply will be perfectly adequate for powering an Arduino.
It will already be very heavily filtered and stabilised.

Now @Gerben made me think that maybe the 5v rail is still powered on when the pc is off. If so, then will a regulated 12v rail work? What do you think?
ps. I need 15 rep here to upvote you, so if you upvote the question that might help :)

An ATX supply has a 5v standby rail that is always on which is used to control the computer's power circuitry. The main 5v rail will be off. The only time I have seen a computer's USB providing power when turned off has been when an external powered hub is back feeding power into the port.

Some motherboards do have the option of providing standby power to USB for wake-up purposes, but that usually has to be explicitly enabled by the user.

source: Stack Exchange

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

sort: votes


text:
Cannot read NTAG203 with MFRC522
I tried regular RFID tags and It works but when I tried NTAG203 it won't detect.
P.S. I used the code "dump_data" example of MFRC library.

what are regular RFID tags? MFRC522 reads NFC tags - "RFID" tags include non NFC tags

@JaromandaX Mifare 1k Card is what i referred to. I could easily read that card but not a NTAG203 sticker

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


text:
Inputting list of data
Sorry if this question has been asked but I can't seem to find an answer because I don't really know if I'm phrasing the question correctly.
I'm trying to control a grid of LED to light up in a specific sequence that is based on a long list of data (and loops over time). Is there any way to bring in the data automatically? (vs individually coding the digitalWrites and delays) I think I found a reference project a few days ago but I lost it.
Thanks!

Your question is too vague to answer in detail, but in broad terms, probably yes.

Google for loops and arrays - that should get you started.

Your question is vague so I have made some assumptions, I hope they are right.
The first is I have assumed you are relatively in experienced at programming, I hope that's right otherwise the rest of this may seem patronising.
You have a number of LEDs arranged in a grid (lets say 3x3 to make life easy).
You are asking is there an alternative to doing this:
// Step 1
digitalWrite (LED1, HIGH);
digitalWrite (LED4, HIGH);
digitalWrite (LED8, HIGH);
delay (100);
digitalWrite (LED1, LOW);
digitalWrite (LED4, LOW);
digitalWrite (LED8, LOW);
// Step 2
// And so on...

Yes there are, and there are many, I think this is probably going to be the easiest to start with.
Coding the data in a 2D array.
An array is a fixed length list of values of the same type.  One obvious use for an array is to hold the pin numbers for you LEDS, rather than having LED0 through to LED8.
#define LED0 2
#define LED1 3
// and so on

Alternative array version
//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = {2, 3, 4, 5, 6, 7, 8, 9, 10};

I have declared the array as const because the values in it aren't going to change.  The array is going to hold integers (because that's what digitalWrite() takes as a pin number) and there are 9 of them.  Rather than use the literal 9 I have defined a constant because I know that value is going to be used elsewhere in the code and this means it is easier to change the number of LEDs.
So how does this help you?  Well you can define an array of 'steps' and each step has a list of which LEDs are switched on.  As your code loops through the steps it turns the specified LEDs, waits and then turns them off.  The simplest way to encode the data would be for each 'step' element to be an array of Boolean values (each true value indicates a light that should be on during this step).  I have chosen Booleans because it will use the least amount of space, which is always an issue on an Arduino.  Depending on the number of steps and LEDs you may need to look at alternative storage methods, like just the LEDs that are on, but it will do for now.
const bool theSteps[MaxSteps][MaxLEDs] =
{
    {false, false, false, false, false, false, false, false, false}
  , {false, true , false, false, true , false, true , false, false}
  , {false, false, true , true , false, false, false, true , false}
  , {true , false, false, false, false, true , true , false, false}
};

You still have to code the data within the program, but its much smaller
//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };

const bool theSteps[MaxSteps][MaxLEDs] =
{
    { false, false, false, false, false, false, false, false, false }
    ,{ false, true , false, false, true , false, true , false, false }
    ,{ false, false, true , true , false, false, false, true , false }
    ,{ true , false, false, false, false, true , true , false, false }
};

#define StepDelay 100

void setup()
{
}

void loop()
{
    for (int onOff = 0; onOff < 2; ++onOff) // Turns the LED on and off
    {
        for (int step = 0; step < MaxSteps; ++step)
        {
            for (int led = 0; led < MaxLEDs; ++led)
            {
                if (theSteps[step][led])  // If the LED should be on
                {
                    digitalWrite(LEDPins[led], (onOff < 1) ? HIGH : LOW);
                }
            }
        }
        if (onOff < 1)
            {
                  delay(StepDelay);
            }
    }
}

I'm afraid I haven't tested any of this code (it might not even compile) but the theory is right and it should give you a shove in the right direction.

Thanks! I forgot about arrays because I haven't coded in a while... I'm still fiddling with the code because I'm actually trying to do 3 separate arrays of data that shifts/scrolls across one direction (step++ at the end of each loop and shifting the array for each set of data) but I think I've almost got it.


text:
Getting coordinates from a touch panel with I2C
Hello world (this is my first message in this forum).
I am quite a just-married-to-Arduino guy, I am very passionate about this platform that I kew since long time but never had the time to dedicate.
Now I have done several home projects that made me both feel happy and feel sooooo rookie... But hey, here I am trying more and more complex things.
I am trying to do something I haven't found information about: I have a 10" touch panel (I am not talking about a screen, just the touch surface) which is a capacitive 10 pin panel that communicates with I2C protocol (there are SCL and SDK pins). I have managed to scan the address and turns out it is in the #40.
However, other than that I do not have the knowledge to get the coordinates out of that panel. My question is: is there any library that can help me with that or will I need to code everything?
I am attaching some pictures of the panel and the pinout to have a clearer picture of what I am talking about.
I thank you all for your time reading my post, I hope some day I will be able to provide some answers rather than questioning!
Joan.

Have you googled for a datasheet of that chip?

Where did you get that panel? Don't they provide any identification or information? A datasheet is necessary to do anything with the panel (at least, when you cannot sniff on a working communication with it, when it is connected to a working master device)

Hi Chris, thanks for your comment. I have googled it and found nothing really interesting. The user hcheung found an interesting library, but I have hit a rock with a part of the code I can't deal with (look below). The panel came to me by somebody that purchased it on ebay, so not really easy to get the source... I have found the manufacturer of the chip though: FocalTech

There is a simple library that works for FT5xx6 display panel.
Other information available:
Application node - https://cdn-shop.adafruit.com/datasheets/FT6x06_AN_public_ver0.1.3.pdf
Datasheet - https://www.newhavendisplay.com/appnotes/datasheets/touchpanel/FT5x26.pdf
In case those links might be no longer available in the future, a quick search on FocalTech FT5xx6 should give you the relevant information.

Hi! Thank you so much for your help! I have started with the library and have come out with an issue when trying to compile. I am afraid I am very novice if I don't know where the problem is, but the error is in this line: FT5xx6 cmt = FT5xx6(CTP_INT);

It seems that you are trying to create an instance of FT5xx6 class, the line FT5xx6 cmt = FT500x(CTP_INT); is simply incorrect. If you want to create an instance called cmd, it should be FT5xx6 cmd(CTP_INT);.

Hi, thanks again for your comment. I tried your suggestion and it shows the exact same error. Maybe there is something wrong in the libraries? I had to make the library file myself copying the text from the Github repository, maybe I did something wrong...

Ah, I just realised that the github is not structured as a proper Arduino library that you could download and use it. You need to do it manually. 1) Go to your Libraries directory where your Arduino IDE located, create a directory called FT5xx6; 2) copy FT5006.cpp from the github and save it inside the directory you just created, do the same for FT5xx6.h; 3) create a new project from Arduino IDE, and copy the example code from capacitive_7in_panel.ino on github. It should works now. I just tried (compilation only, didn't run as I don't have a FT5xx6 module). Good luck.

Hi again. I believe that is what I did, however I couldn't copy the file, but copy the text and generate a plain text file as it is not downloadable. I did this from a MAC computer, I will try to do it with a PC... Is this how you did it? Or there should be a way I could download the files?

Yahoo! It works. MAC or something was making these files go wrong for some reason. I made all the process on a PC and turns out that I get data. Now the difficult thing will be to understand it. I would like to make it just give me a set of coordinates of a single touch, it looks like this script delivers a lot more information than that. I am only interested in a single point touch, now I need to understand all the data in the serial monitor and figure out which is good for me. I will post an image of what I get. Thanks for your help! It is much appreciated.

Hi hcheung, I have been struggling with the code and the panel, but something is wrong... the monitor shows weird data, like I am touching 15 points or even touching in the same spot gives different data every time. Until it looks like something "saturates" and starts giving coordinates of 4095x 4095y. I really am lost now. Do you have any idea why this happens? I think I will start a new thread with the exact issue. Thanks for your help!

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


text:
Issues controlling a 10,1 capacitive panel with Arduino
Some days ago I had the inestimable help of hcheung in this forum to help me find some libraries on github to control a capacitive panel with a HT5xx6 controller. The libraries and code are here.
I have copied and created the libraries into a.h and .cpp files and placed where arduino IDE can find them and run the sketch. The startup works fine, meaning the panel is initialized.
However it doesn't give reliable data. Any time you touch the panel in a specific location it does not give a single set of coordinates, it sometimes give 2 or 3 set of coordinates and most of the time 15. This is as if the panel would detect 15 touches!
Even more issues: the coordinates are never the same in one fixed location. So the data is not reliable and I don't know what I am doing wrong.
Has anybody gone through this experience before?
Thanks for your help in advance!
Take care.
Joan.

is your panel the capacitive type for certain?

Hi jsotola, yes it is. I have the TDS and it is clear. https://focuslcds.com/content/FT5X26.pdf. Thanks.

The ISR might be fired up multiple times during the touch. Can you try to switch to another library https://github.com/sumotoy/FT5206? This one allows you to set your own interrupt pin and disable the interrupt when the touch is detected, read the coordinates and check against old coordinates. Read the example codes provided.  For random coordinates issue, make sure your power supply can provide sufficient power (1A-2A), and you might want to add a 10uF capacity between Vcc and GND.

Hello, thanks for the comment. I have tried all the above indications and still have the same issue. I have uploaded 3 videos on youtube so you can see what is happening, maybe this helps:

Part 1 Video [https://youtu.be/UwGcfkD-O-Q] - Part 2 Video [https://youtu.be/80RHSga8HTM] - Part 3 Video [https://youtu.be/yidqZx6y918]

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


text:
Sending values from Matlab to arduino using serial communication
I want to send numeric value from matlab to arduino but code is not working.
Matlab code is as:
doi = 3 ;
arduino=serial('COM5','BaudRate',9600); % create serial communication object
fopen(arduino); % initiate arduino communication
fprintf(arduino, '%s', char(doi)); % send answer variable content to arduino
fclose(arduino);

Arduino code is as:
  int solenoidPin = 13; //This is the output pin on the Arduino
int doi;

void setup()
{
  Serial.begin(9600);
  //pinMode(13, OUTPUT);
  pinMode(solenoidPin, OUTPUT); //Sets that pin as an output
}
void loop()
{

  if(Serial.available()>0)
  {

    doi = Serial.read();
    //Serial.println(doi);
    //Serial.println("\n");
    //doi = doi - 48;
   if (doi == 1)
   {
    //Serial.println(1);
    digitalWrite(solenoidPin, HIGH); //Switch Solenoid ON
    delay(1000); //Wait .15 Second
     digitalWrite(solenoidPin, LOW);
    }
  else if (doi == 2)
    {
     //Serial.println(2);
    digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
    delay(2000); //Wait .165 Second
    digitalWrite(solenoidPin, LOW);
    }
  else
    {
      //Serial.println(3);
      digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
      delay(3000); //Wait .180 Second
      digitalWrite(solenoidPin, LOW);
    }

  }
}

I used str2num(doi) also instead of fprintf(arduino, '%s', char(doi)) but no output.
Please give suggestion to correct this.
Thanks.

You need to learn how serial communication works. https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

fopen(arduino); takes some time to initialize the serial connection so you should use pause(2); after fopen(arduino); and in fprintf() send doi as interger i.e. fprintf(arduino, '%i', doi);. Suppose the doi is 1 then code would be as
doi = 1;
arduino=serial('COM5','BaudRate',9600); % create serial communication object
fopen(arduino); % initiate arduino communication
pause(2);
fprintf(arduino, '%i', doi); % send answer variable content to arduino
fclose(arduino);

Another modification required in arduino program as
doi = doi - 48;

Uncomment this line inside if(Serial.available()>0) block.

I presumed that you are retrieving the value of doi from some other function then using pause(2) will make your program significantly slow. to avoid this problem you can split your program into three part first part will contain upto fopen() which will be executed when the main program initialized, fprintf() will be executed during runtime and at the end fclose() will be executed to terminate the serial communication.

You send a string of ASCII characters representing a number in human readable format.
You then read one of those characters that represents a single digit and then try and use it as if it were a number.
Instead you need to read the whole string of numbers (which means having some way of knowing where the end of the numbers are in the stream of characters that arrive) and then interpret it back into a number again.

Hello Thanks for your reply but as I am beginner so I can not understand the solution what you suggest completely. Can you please suggest me modification in my above code so that I can solve this problem. Thanks.


text:
I2C MCP4725 DAC connection speed
I'm trying to use the MCP4725 DAC from Adafruit (https://www.adafruit.com/product/935) to output some waveforms over a frequency range up to about 50kHz. At the moment, I'm simply sending values to the DAC via the Wire library and through the DAC's onboard library. It appears that the values are only being sent at 7kHz. Is this due to the added weight of the libraries I'm using? Is there some way I can increase the transmission speed?

Consider using a Teensy 3 or a Due, with 2 built-in 12-bit DACs each

You cannot get 50kYz from a DAC running on I2C on an Arduino.
The maximum rate for I2C (if you select fast mode) is 400kbps. Setting the DAC takes three bytes plus start/stop/ack bits (total 29 bits).
At 400kbps that equates to (400000/29) 13793 settings per second.
Add to that the time taken to actually create and process the data, running the instructions to do everything, you can expect about half that - which is the 7kHz you're getting.
To get 50kHz from a DAC you really need a CODEC and run something like I2S, which you are never going to do on an Arduino.


text:
Output frequency from an SPI DAC (MCP4922) is lower than expected
I'm using a 2-channel, 12-bit DAC (MCP4922, datasheet) with an Arduino Uno, using the library written for it here. With the clock divider set to 2, I should have the SPI clock frequency at 8MHz. If each value sent to the DAC takes about 12 of these clock cycles, that leaves me with about 650kHz as my output frequency (when I'm sending a simple on-off signal like below), but the fastest I see is about 25kHz.

void loop() {   dac.output2(4095, 0);   dac.output2(0, 4095);  }

Am I misunderstanding how the transfer protocol works? How can I make this faster? I'd like to both understand why this is so slow, and also to get an output frequency of at least 50kHz.

Did you set the clock divider to 2, or to SPI_CLOCK_DIV2? 2) Did you setPortWrite(true)?

@EdgarBonet Yes to both, unfortunately.

Let's do some maths...

16MHz master clock / 2 = 8MHz SPI clock
2 transactions = 16 bits (not 12!)
8,000,000 / 16 = 500,000
2 transitions per cycle
2 channels
2 + 2 = 4
500,000 / 4 = 125,000Hz

So in a perfect world you could expect 125kHz from the DAC. However the world is far from perfect.
Let's look at what it's actually doing when you use output2():
void DAC_MCP49xx::output2(unsigned short data_A, unsigned short data_B) {
  this->_output(data_A, CHANNEL_A);
  this->_output(data_B, CHANNEL_B);

  // Update the output, if desired.
  // The reason this is only in the dual-output version is simple: it's mostly useless
  // for the single-output version, as it would make more sense to tie the \LDAC pin
  // to ground, or do it manually. However, there should be a single-call method
  // to update *both* channels in sync, which wouldn't be possible with multiple
  // separate DACs (for which there is latch()).
  if (automaticallyLatchDual) {
    this->latch();
  }
}

Assuming automaticallyLatchDual is false we can pretty much ignore that section. So it's calling _output() twice - once for each channel. And what does that do?
void DAC_MCP49xx::_output(unsigned short data, Channel chan) {
  // Truncate the unused bits to fit the 8/10/12 bits the DAC accepts
  if (this->bitwidth == 12)
    data &= 0xfff;
  else if (this->bitwidth == 10)
    data &= 0x3ff;
  else if (this->bitwidth == 8)
    data &= 0xff;

  // Drive chip select low
  if (this->port_write)
    PORTB &= 0xfb; // Clear PORTB pin 2 = arduino pin 10
  else
    digitalWrite(ss_pin, LOW);

  // bit 15: 0 for DAC A, 1 for DAC B. (Always 0 for MCP49x1.)
  // bit 14: buffer VREF?
  // bit 13: gain bit; 0 for 1x gain, 1 for 2x (thus we NOT the variable)
  // bit 12: shutdown bit. 1 for active operation
  // bits 11 through 0: data
  uint16_t out = (chan << 15) | (this->bufferVref << 14) | ((!this->gain2x) << 13) | (1 << 12) | (data << (12 - this->bitwidth));

  // Send the command and data bits
  SPI.transfer((out & 0xff00) >> 8);
  SPI.transfer(out & 0xff);

  // Return chip select to high
  if (this->port_write)
    PORTB |= (1 << 2); // set PORTB pin 2 = arduino pin 10
  else
    digitalWrite(ss_pin, HIGH);
}

That's quite a lot. All those boolean mathematics operations and decision making slows things down a lot. So does hopping from function to function (yes, the compiler will possibly try and inline some things).
Even the SPI.transfer() isn't that efficient with checks and while loops, etc.
To get anywhere near the kind of speed you are looking for you would need to use non-blocking SPI code so you can be transferring a byte out of the SPI port at the same time as getting the next byte ready to send. You don't need to wait for the current SPI transfer to finish (as the SPI library does), you just need to be sure that the previous one has finished before you start the next one.


text:
Make device based on CH340G working as keyboard
There is small board with gyroscope. Controller - Atmega 8a, com-usb chip is CH340G. Board is handmade but not by me so I don't sure is it Arduino clone or not. It works with "ch341ser" driver on the computer and is used in small video game writed on java. This game is ran by .bat file where I specify COM port number, game listen this port in code.
I need to do anything to make computer understand gyro tilt as arrow keyboard buttons commands. In other words I need to write a driver or smth else to make computer understand device as USB HID keyboard. Is it possible to do it programmatically and how to do that?

You could try using V-USB, instead of using the CH340G that only does serial.

It will be a lot easier to buy a Arduino Micro or Pro Micro with a ATmega32U4. That chip can be set as a keyboard with standard Arduino libraries.

No, it's not possible. The device enumerates as a USB serial device, and the only way to change that is to change the internal silicon of the device.
The closest you could do is (though I have no clue how on Windows) write (or if you are lucky, find) a program that reads serial data through the COM port and somehow injects keyboard commands into the input subsystem of the operating system.

@DiA I found this that may help: https://www.232key.com/


text:
ToF Laser Sensor (VL53L0X) not working
I have this time of flight laser distance sensor: http://www.dx.com/de/p/cjmcu-vl53l0x-tof-laser-distance-measuring-sensor-module-purple-449081#.WSbn52jyi70
The example code of the VL53L0X-arduino library is not working; I always get the serial message

65535 TIMEOUT

However, I guess that the problem is at the sensor. The communication is via I2C, so that the i2c scanner should find it's address, right?
This finder doesnot find any address - am I right, that then the problem is at the sensor?
I connected VCC to (nearly) 5V, GND to GND, SCL to A5 and SDA to A4 (Arduino Uno)

It look like that board doesn't have pull-up resistors on the SDA & SCL pins. Try adding them. Something around 2 kilo-ohm (not that critical).

@Gerben I tried it. I added for SDA & SCL 2.2 kOhm resistors to pull it to 5V. However, I still get 65535 TIMEOUT. But do you agree, that I should get an address using the I2C scanner?

Yes. It should appear on the scanner. Looking at the listing, it specifies that it is a 3.3V device. But looking at the pictures it seems like there is a voltage regulator and something like a buffer-ic on the bottom.

Why have you connected it to 5V?

have you solved the problem? I have the same.

@Mcrane unfortunately not. Please leave a reply if you do

I had the same problem using this sensor. The solution was to connect

VCC -> 5V
GND -> GND
SCL -> A5 (SCL)
SDA -> A4 (SDA)
DNC -x Not connected
GN2 -> GND
XSH -> 5V
INT -x Not connected

And then to use the code mentioned here by Ted Meyers. I used Nano with ATmega328P and Arduino IDE 1.8.5.

CODE:
#include <Wire.h>

#define VL53L0X_REG_IDENTIFICATION_MODEL_ID         0xc0
#define VL53L0X_REG_IDENTIFICATION_REVISION_ID      0xc2
#define VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD   0x50
#define VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD 0x70
#define VL53L0X_REG_SYSRANGE_START                  0x00
#define VL53L0X_REG_RESULT_INTERRUPT_STATUS         0x13
#define VL53L0X_REG_RESULT_RANGE_STATUS             0x14
#define address 0x29

byte gbuf[16];

void setup() {
  // put your setup code here, to run once:
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
  Serial.println("VLX53LOX test started.");
}

void loop() {
  Serial.println("----- START TEST ----");
  test();
  Serial.println("----- END TEST ----");
  Serial.println("");
  delay(4000);
}

void test() {
  byte val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_REVISION_ID);
  Serial.print("Revision ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_MODEL_ID);
  Serial.print("Device ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("PRE_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  val1 = read_byte_data_at(VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("FINAL_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  write_byte_data_at(VL53L0X_REG_SYSRANGE_START, 0x01);

  byte val = 0;
  int cnt = 0;
  while (cnt < 100) { // 1 second waiting time max
    delay(10);
    val = read_byte_data_at(VL53L0X_REG_RESULT_RANGE_STATUS);
    if (val & 0x01) break;
    cnt++;
  }
  if (val & 0x01) Serial.println("ready"); else Serial.println("not ready");

  read_block_data_at(0x14, 12);
  uint16_t acnt = makeuint16(gbuf[7], gbuf[6]);
  uint16_t scnt = makeuint16(gbuf[9], gbuf[8]);
  uint16_t dist = makeuint16(gbuf[11], gbuf[10]);
  byte DeviceRangeStatusInternal = ((gbuf[0] & 0x78) >> 3);

  Serial.print("ambient count: "); Serial.println(acnt);
  Serial.print("signal count: ");  Serial.println(scnt);
  Serial.print("distance ");       Serial.println(dist);
  Serial.print("status: ");        Serial.println(DeviceRangeStatusInternal);
}

uint16_t bswap(byte b[]) {
  // Big Endian unsigned short to little endian unsigned short
  uint16_t val = ((b[0] << 8) & b[1]);
  return val;
}

uint16_t makeuint16(int lsb, int msb) {
    return ((msb & 0xFF) << 8) | (lsb & 0xFF);
}

void write_byte_data(byte data) {
  Wire.beginTransmission(address);
  Wire.write(data);
  Wire.endTransmission();
}

void write_byte_data_at(byte reg, byte data) {
  // write data word at address and register
  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(data);
  Wire.endTransmission();
}

void write_word_data_at(byte reg, uint16_t data) {
  // write data word at address and register
  byte b0 = (data &0xFF);
  byte b1 = ((data >> 8) && 0xFF);

  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(b0);
  Wire.write(b1);
  Wire.endTransmission();
}

byte read_byte_data() {
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

byte read_byte_data_at(byte reg) {
  //write_byte_data((byte)0x00);
  write_byte_data(reg);
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

uint16_t read_word_data_at(byte reg) {
  write_byte_data(reg);
  Wire.requestFrom(address, 2);
  while (Wire.available() < 2) delay(1);
  gbuf[0] = Wire.read();
  gbuf[1] = Wire.read();
  return bswap(gbuf);
}

void read_block_data_at(byte reg, int sz) {
  int i = 0;
  write_byte_data(reg);
  Wire.requestFrom(address, sz);
  for (i=0; i<sz; i++) {
    while (Wire.available() < 1) delay(1);
    gbuf[i] = Wire.read();
  }
}

uint16_t VL53L0X_decode_vcsel_period(short vcsel_period_reg) {
  // Converts the encoded VCSEL period register value into the real
  // period in PLL clocks
  uint16_t vcsel_period_pclks = (vcsel_period_reg + 1) << 1;
  return vcsel_period_pclks;
}

You have to pull XSH high (3.3V) in order to turn the device on (either via an I/O port or via a pullup resistor to 3.3V).
Also, the device is rated for a maximum of 3.3V, you might damage it if you connect it to 5V.
Regards

One other thing to check as I had this error myself and it was simply because I hadn't soldered the header pins of the nano or the TOF device which I had just stuck into my breadboard. I am using a iHaospace VL53l0x from Amazon. I only thought of it once I ran the i2C scanner check, which didn't recognise (see) the device, so that go me thinking - (https://gammon.com.au/i2c). The I2C scanner Sketch code to use in Arduino's IDE is two thirds down that page. I also should point out that you need to run the serial monitor at the 115200 baud rate not lower or you might get gobbledygook. Now it all works just as it should with the standard Arduino Adafruit example, no #include wire.h required.

I had this problem. After connecting VL53L0X, the script hung at the start. Scanning of i2c devices also hung up. Washing the soldering points of contacts helped. Apparently the device is very sensitive to dirt on the contacts.


text:
Galileo Positioning System signal receiving
I want to determine my arduino's position. However, I want to use the European Galileo system instead of the US-American GPS.
Therefore, I searched for any possibilities receiving the Galileo signals. I figured out, that u-blox has some receivers: NEO 8 or the LEA 6 (firmware update required). However I did not find any arduino breakout board (, etc.) that uses these u-blox sensors or other Galileo-compatible hardware.
Does anyone know, how I could use the Galileo Position System?

First check that there is coverage in the area you want to use it. Currently coverage is mainly Europe. They are still in the process of putting more satellites into orbit.

but why using a system starting in 2020?

You need the hardware and a library. Most GPS modules use a serial communication, and I think that also the Galileo compatible boards use serial communication. That makes them compatible with most microcontrollers and also with Arduino boards.
I could find a few shields that can be attached to an Arduino board.
This one is in development at the moment: Kickstarter shield with Galileo
This one is compatible via the serial pins: GA-001 Multi GNSS Ublox
There is a "NEO-M8N" shield and maybe one or two others.
All those boards are very new, and I don't know if they come with a library for an Arduino. Perhaps you have to wait a few months and then it should be a lot easier to buy a complete functioning module with a library.
Before buying a module, confirm that there is a library for Arduino or good documentation to write your own library.

NeoGPS is the only Arduino library that will work with the newest GPS devices, like the NEO-M8.


text:
How to create a USB CDC device. (I'm using stm32f103c8 black pill board) and I want to read the data through USB in my raspberry pi as a serial port
How to create a USB CDC device. (I'm using stm32f103c8 black pill board) and I want to read the data through USB in my raspberry pi as a serial port.
I am using a black pill to read RFID-rf522 to read a tag (SPI) and send it to raspberry pi through a USB (using DM and DP pins).
Quick responses are welcomed.

It depends on what the core provides. If it's like others, then Serial.begin(115200); or maybe USBSerial.begin(115200); will do it. Read the manual for the STM32F1 core on the website for that core.

Could it be that you might be better off just to use the STMicro code for what you are doing?

if you use the core by STM select USB support in Tools menu

You can use the one provided by generating it with STMCubeMx. This is going beyond arduino though. But it is highly feasible.


text:
Arduino Analog to Digital Conversion from 56V DC Batteries
I have a problem, I am using 56V DC combined batteries system. I get ADC values comes to Arduino like 211, 217 etc... I have to find out when the DC volt drop to 42V. How do i know the digital value for the ADC from Aruino.

Your code and circuit please, or we are just not able to help you. Ypu cannot measure voltages greater than 5V with the Uno, so you need circuitry to divide the voltage down to that range

I'll assume you're using Li-Ion batteries in 14s configuration. You'll want to measure voltages up to around 60 V while charging. With a bit of safety margin, I'd set it up to measure up to 72V without damaging the Arduino - which can measure voltages up to 5 V, but the input on that pin should never exceed 5.5 V.
To bring your battery voltage down to something the Arduino can use, you'll need to use a voltage divider, as chrisl suggested.

With R1 = 10 kOhm and R2 = 680 Ohm, you'd get readings up to an input voltage of 78 Volts.
With analogRead() returning values between 0 and 1023, your 42 V cutoff would be around 546.

Warning: this is going to get math-heavy
Ok. So you have a battery with a voltage divider on it, and you are using the Aruino ADC to read the output of that voltage divider. And you want to "back-calculate" the battery voltage from the ADC reading.
First let's look at exactly what happens with a voltage divider and just how it works. For that we'll turn to good ol' Ohm's Law.
Rule number one is that two resistors in series sum their resistances. So if you have a 10kΩ and 680Ω resistor in series (as suggested in @towe's answer) the total resistance is 10680Ω.  We'll use this arrangement as our example.
Now Ohm's Law states that the current flowing through a resistive load is directly proportional to the voltage across it. So for a fixed resistance and a given voltage we can calculate the current that will be flowing through the resistors.  That formula is:
I=V/R
So for a voltage of 56V and a resistance of 10680Ω we can say that the current is 56/10680 amps - or about 5.24mA.
Great. But so what? Well, now we can reverse the formula and find the voltage across a given resistance for that specific current. Which we can do for, for example, the 680Ω resistor.  We know that the same current is flowing through both resistors (since they are in series), so flipping the formula around we get:
V=I×R
So at 0.00524 amps and 680Ω that's 0.00524×680 = 3.57V.  We can do the same for the 10kΩ resistor: 0.00524×10000 = 52.43V.  And oh look - if we add those two voltages together, what do we get? We get 56V. The resistors have divided the voltage into two portions.
You can combine those two formulae together to give you:
VOUT = VIN × (R2 / (R1 + R2))
And if we move the VIN to the left hand side we get:
VOUT / VIN = (R2 / (R1 + R2))
And that is known as the transfer function, or the ratio of the input to output voltage of the voltage divider.
For a 10kΩ (R1) and 680Ω (R2) resistor pair we get 680/10680 = 0.0637.
And that is the "magic number" we want to calculate back from the ADC to the battery voltage.  Whatever the voltage we read at the ADC the battery voltage is the reciprocal of that number times bigger (reciprocal is "one over the value").  The reciprocal of 0.0637 is 15.7.  So if you read the value from the ADC then convert that into a voltage relative to the internal reference voltage (approximately 5V for a normal Arduino) then multiply that voltage by 15.7 you will get your battery voltage.
So next is to get the ADC voltage. And again, it's all ratios.  The ADC gives you a number that is a ratio of the incoming voltage to the reference (5V) voltage.  At 1023 you get "5V minus 1 LSB", so about 4.995V. We don't need that kind of accuracy for this, really, so we'll just call it 5V.
Say you read 482 from the ADC, if you convert that into a voltage you take the ratio 482/1024 and multiply it by the reference voltage (1024 is the range of a 10-bit ADC - you would change that for other types of ADC):
VIN = 482 / 1024 × 5 = 2.35V
Multiply that by our "magic number" 15.7 and you get 36.95V - and that's the battery voltage.


text:
Several ESP8266 in wifi network should share information
I am currently working on a project for my home where several ESP8266 (each with a relay) control lights. I have developed an android for this where I find the ESP8266s via mdns but the problem is that sometimes one or two won't be found ever (depends on the position where I am trying it). So my idea was to make them talk to each other so everyone knows like an list of ip addresses from the others. This would give me the possibility to find every ESP as soon as i have found one.

I guess you are asking if it is feasible: if this is the case, I would say yes, without too many troubles. Each ESP can launch MDNS discovery, so they can discover each other.

Waht you may be looking for is a mesh network, you can use the standerd lib ESP8266WiFiMesh. Mesh reduces the loading of smart devices on the router by
 forming a mesh between the smart devices.There are unluckely no examples ready to use but you can look at the provided example and modify it to your needs,
You find the lib in your core dir
C:\Users\Your_Username\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFiMesh

but be aware there are a lot of open issues and PRs (which means lot of trouble in a stable production)
EDIT
There is also the Arduino library painlessMesh. Its well documented and has lot of examples and can be combined with MQTT.For MQTT there is one condition where you might consider this option, if you have deep sleeping nodes on battery (than mesh might be contra productive)

And here's the source code online as well: https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFiMesh


text:
Do we need ARM build for arduino while interfacing R-pi and arduino
I wonder whats ARM build for Linux? Do we really need ARM build when we work with arduino? I need to integrate arduino and raspberry pi over wi-fi, I don't know whether I need ARM in this case. Also any quick learning tutorial for interfacing two of these hardware is appreciable
A newbie to Arduino. I hope fun learning with it

The arm build contains arm binaries for the compiler. Are you running the IDE on the pi?

To interface the two grasp the usb cable firmly by the plug and insert into the usb socket.

please tell me why we need ARM while working with arduino. I have to get the logs of arduino based sensor nodes on raspberry pi. in this case, do i need ARM ?

I need to interface over the wireless medium

And I asked a question. ARE YOU RUNNING THE IDE ON THE PI?

Nope. Not running on pi

The ARM build of the IDE is for running the IDE on ARM systems. If you want to run the IDE on the pi then you need the arm build. However if you want to run the IDE on your PC then you need the IDE build that matches the architecture of your pc.
There are a million and one ways of communicating wirelessly between an Arduino and a pi.

Thanks for the clarification. Now i am at ease. R pi is ARM system and we need ARM build for that. right>

Only if you want to compile Arduino sketches using the pi.


text:
Using I2C to keep track of position of slaves
I am trying to flesh out my ideas for an electronics project and this question seems to be the main hangup. Is it possible, in the I2C protocol, to figure out the order in which the slaves are chained to the host? For example if I have 5 arduinos strung together by their serial and clock lines I want the master to be able to see that Arduino 1 is in position 1, Arduino 2 is in position 2... And so on. But if I switch Arduino 1 and 2 I want the master to know that Arduino 1 is in position 2 and Arduino 2 is in position 1.
I assume this isn't possible because all of the arduinos are connected to the same data and clock. So does anyone have any other protocols or algorithms in mind where I could do this. I was thinking I could have one Arduino talk to it's neighbors somehow and waterfall data down the line until it gets to it's destination. But I'm curious to see what y'all come up with.

Please tell what your project is. Why do you want to know the order ? How long is the maximum total length of the wires for the I2C bus ? What kind of cable will you use ? Perhaps it is possible with jumpers for the I2C address or with the Serial bus in a daisy chain configuration. Perhaps the I2C bus can be daisy chained by using the hardware I2C for the Arduino as a slave and a software I2C for the next I2C bus. That will probably be too complex and unreliable. I can think of more possibilities with extra hardware, but they all will get you into trouble.

I'm trying to make something like little bits or Legos where the user is able to stack the pices in whatever order and it runs sequentially from device to device.

That is typically a daisy chain with the Serial bus.

@jot please explain... As far as I understand it serial really only works for two devices

Suppose you want to send data down and up the chain, then each Arduino should have two serial busses. It can be a software serial bus, but not the standard Arduino SoftwareSerial. One bus connects up and the other bus connects downward the chain. The Arduino boards mainly passes on the information between the serial busses (changing one byte to indicate that it has become one level further down the chain), and the Arduino only takes the command that is for the current Arduino. Each Arduino will know how far it is down the chain. You need a well described and preferably fault-tolerant protocol.

With a single serial bus, each TX is connected to the RX of the next one. The last TX can be connected to the RX of the first one. That creates a round daisy-chain. Maybe what I describe is a cascade ?

Ok, so that allows data in one direction but unless I have a wire connecting the transmit of the bottom of the chain to the receive of the top of the chain there is no way to transmit data back up the chain.

If you don't have a closed round loop of communication and you need data to go up and down the linked chain, then you need two serial ports.

This is indeed not possible.  I2C was meant for short on-the-same-board communications and though it's sometimes also extended to near-board communications, it still has no facility for position sensing.  Each slave  simply listens for an address and then responds to commands sent for that address.
Slaves can "stretch the clock" to slow down things, but cannot otherwise make themselves known so long as they are not mastering the bus.  In any case, even if bus mastering is assigned round-robin, only presence can be determined, not the position in any chain.


text:
Trouble with SIM808 shield
I've been trying to work with Waveshare SIM 808 shield on arduino, quite similar to this one:
https://www.waveshare.com/wiki/GSM/GPRS/GPS_Shield_(B)#How_to_use_with_Arduino_UNO_R3
I tried using multiple examples, such as this:
#include <DFRobot_sim808.h>

#include <SoftwareSerial.h>

DFRobot_SIM808 sim808(&Serial);

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

  //******** Initialize sim808 module *************
  while(!sim808.init()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
  Serial.println("Open the GPS power failure");

}

void loop() {
    //************** Get GPS data *******************
    if (sim808.getGPS()) {
    Serial.print(sim808.GPSdata.year);
Serial.print("/");
Serial.print(sim808.GPSdata.month);
Serial.print("/");
Serial.print(sim808.GPSdata.day);
Serial.print(" ");
Serial.print(sim808.GPSdata.hour);
Serial.print(":");
Serial.print(sim808.GPSdata.minute);
Serial.print(":");
Serial.print(sim808.GPSdata.second);
Serial.print(":");
Serial.println(sim808.GPSdata.centisecond);

Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat,6);

sim808.latitudeConverToDMS();
Serial.print("latitude :");
Serial.print(sim808.latDMS.degrees);
Serial.print("\^");
Serial.print(sim808.latDMS.minutes);
Serial.print("\'");
Serial.print(sim808.latDMS.seconeds,6);
Serial.println("\"");
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon,6);
sim808.LongitudeConverToDMS();
Serial.print("longitude :");
Serial.print(sim808.longDMS.degrees);
Serial.print("\^");
Serial.print(sim808.longDMS.minutes);
Serial.print("\'");
Serial.print(sim808.longDMS.seconeds,6);
Serial.println("\"");

Serial.print("speed_kph :");
Serial.println(sim808.GPSdata.speed_kph);
Serial.print("heading :");
Serial.println(sim808.GPSdata.heading);

//************* Turn off the GPS power ************
sim808.detachGPS();
  }

}

or this
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX
String comdata = "";
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

 while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  delay(200);
}

void loop() // run over and over
{
  delay(2000);
   mySerial.println("AT");
   delay(200);
   //Send message
   mySerial.println("AT+CGNSPWR=1");
   delay(200);
   //reset GPS in autonomy mode
   mySerial.println("AT+CGNSTST=1");
   delay(200);
   mySerial.listen();
   while(1)
  {
    while(mySerial.available()>0)
        Serial.write(mySerial.read());
    while(Serial.available())
    mySerial.write(Serial.read());
  }
}

In first case, I obviously don't declare RX, TX pins and use the Arduino's general purpose RX, TX pins (0, 1).
In second case I used wires to connect Arduino pins 2 and 3, to shield's D0 and D1 pins.
In both cases, neither RX or TX leds on shield's module light up, which means that it doesn't receive the sent data.
I made sure to set UART/ARDUINO switch on ARDUINO position and I did reset the module several times.
I am using Arduino Uno. What goes wrong here?

try this ... https://www.arduino.cc/en/Tutorial/SerialPassthrough

I'm sorry but I don't quite understand, Serial1 is not declared on Arduino Uno board. Am I supposed to declare it myself? @jsotola

sorry, i was not paying attention to the content of the link ... use that sketch, but change Serial1 to be software serial ... that way you can use the serial monitor in the Arduino IDE to talk to the SIM808 ... then type the AT commands in the serial monitor window, or use a serial terminal program, such as Putty

I have no trouble using the shield, while connected directly to it via micro USB and sending AT commands using Putty. Howevery, once I connect to Arduino board and connect shield to Arduino it just won't work. I tried replacing Serial1 with Serial and typing AT commands in Arduino Serial Monitor, but I doesn't send any reply

make Serial1 software serial that is connected to the SIM808

I think I figured it out. Thank you so much

the sketch is similar to your second sketch except that it uses if statements ... the while statements in your sketch block execution until all data is received on one of the serial ports ... the if statements allow the code to service the serial ports in an alternating fashion


text:
Passing a method pointer
I created a small library, which takes a callback function:
MyClass::add_callback(bool (*callback_function)(), byte behaviour) {
  // ...
  bool result = callback_function();
  // ...
}

So far, I'm using it for periodic polling (for which I don't want to use ISR interrupts). However, I like to use it for other periodic calls that require a state. A simple example is a blinking light, which has an on-off state, as well as knowledge when the next state change needs to occur.
I like to change this method or add another method that takes a method, instead of a function. How should I do this? I'm struggling with the C basics, but answers on StackOverflow seem foccused to more modern C variants. For example, this great answer on Stackoverflow recommends to use boost::bind, but I rather not include such a large dependency.
What I'm looking for is something akin to:
MyClass::add_callback(void *obj, bool (*callback_method)(), byte behaviour) {
  // ...
  bool result = Object::callback_method(&obj);
  // ...
}

where Object::callback_method(&obj); should be equivalent to Object obj; bool result = obj.callback_method();.
For bonus points, is it possible to make this independent on the Object class?
I'm happy for pointers to other sites (like StackOverflow), provided it is applicable to a bare Arduino program.

In case you wonder why I'm not using ISR, I'm a bit of a novice with the Arduino and C. My hardware is a ftDuino, and the Ftduino library uses timers and interrupts on the ATmega32u4, and I want to avoid conflicts for now.

The easiest method I know to do this would be to use a "C"-style wrapper for the member function call. This is in fact done to interface C callbacks with C++ objects.
You could do it like this:
struct Blinky {
  //state etc.
  bool isOn() { return /* something useful */ true; }
};

// The "C" wrapper for the callback
bool Blinky_callback(void *vblinky)
{
  return static_cast<Blinky*>(vblinky)->isOn();
}

struct MyClass {
  void add_callback(void *obj, bool (*callback_method)(void *), byte behaviour) {
    // ...
    bool result = callback_method(obj);
    // ...
  }
};

// Globals
MyClass c;
Blinky b;

void setup() {
  c.add_callback(&b, Blinky_callback, 0);
}

A slightly tidier way with a static member (functionally identical):
struct Blinky {
  //state etc.
  bool isOn() { return /* something useful */ true; }

  static bool callback(void *vblinky) {
    return static_cast<Blinky*>(vblinky)->isOn();
  }
};

// ...
c.add_callback(&b, Blinky::callback, 0);

Other variants would be using inheritance and virtual functions.
// Abstract base class
struct Sensor {
  virtual bool do_check() = 0;
};

struct Blinky : public Sensor {
  bool do_check() override { return true; }
}

Then you can have your add_callback look like:
void MyClass::add_sensor(Sensor *sensor) {
  // ...
  bool result = sensor->do_check();
  // ...
}

This is relatively nice to code with, and the compiler has a fighting chance at keeping your code typesafe, if all the "things" you want to control can conform to the same interface. The virtual dispatch won't cost much more (if anything) than the static wrapper in the previous example. You "pay" a few bytes per class and one pointer per instance for the virtual table though.
More modern techniques would involve templates and/or lambdas, or perhaps std::function, but all that seems overkill if your need is as described (and might generate a lot more code than you're expecting, or do dynamic allocations for std::function which is best avoided in context).

Remark: if you want to do it with (non-static) member function pointers, it is possible but the syntax is hairy:
void add_callback(Blinky *obj, bool (Blinky::*callback_method)(), byte behaviour) {
  // ...
  bool result = (obj->*callback_method)();
  // ...
}

And you're tied to that class. Unless you make add_callback a template, but beware extra codegen.

Thanks for such an extensive answer so quickly. I'll have a look and mark as read once I fully grasp it. At least it give me some good pointers. I seem to be struggling a bit which level of abstraction to use for microcontrollers. Turning back to C after a rather long time of Python and friends, it's interesting to see how poor C's memory management is, and how poor Python's instance protection are. Your answer helps me understand what sort of introspection I can expect from C, especially on an Arduino platform with few high-level libraries.

@MacFreek: none of the code I posted (or that you posted) is C. It is all C++. (And C++ is not modern C, they are two different languages). Look up "RAII" for how you should deal with memory management/object lifetime management. A lot of what you'll find won't be a great fit for small embedded projects, but the core idea is important. (The acronym sucks though.)

You are right. I used "C" because my Arduino code mostly uses plain functions and globals, rather than classes (which is fine for this purpose).

I'm not sure if this is a C vs. C++ syntax, or historic/modern constructs, but I noted that the Arduino IDE allows archaic constructs. For example, you can leave out the this-> in methods, or leave out the std:: prefix for type definitions. I found the hard way when delay() in my method did not call the Arduino function, but this->delay(). Would there be a way to make the IDE more strict, and only allow recommended constructs, so I only learn things the right way?

Thanks for your code examples. I now understand that I need a wrapper function, preferably in the stateful class with the called method. I was trying to solve it in the calling instance, without wrapper.

I don't know if you can change the compiler options used by the IDE (uses -std=gnu++11 -fpermissive which is not super strict), there might be questions on this site about this already. Leaving out this whenever you can is standard practice, you rarely need it. A missing std:: prefix should be a compile error, but there are several ways for a name to be brought into scope.

Your answer uses structs instead of classes. Is that recommended, or personal preference?

The only difference between the two is that struct give public access by default whereas class gives private. So struct is simpler for simple examples. The rest is a matter of style/preference.


text:
DigitalRead() floating pin problem
I am having a problem implementing a the digitalRead() function in arduino uno.I want digitalRead to return 0 when nothing is connected and return 1 when it is connected to +5 volt.But seems like digitalRead returns random values when it is not connected to anything.
I have kind of solved the problem by a small piece of code to stabilize the value i'll attach the code here but if any other solution is avalable..Please help.
The function is as follows:-
bool getValue()

{

String k="";

if(digitalRead(3)==HIGH)

k="HIGH";

else

k="LOW";

bool f=true;

for(int i=0;i<1000;i++)

{
String z;

  if(digitalRead(3)==HIGH)

  z="HIGH";

  else

  z="LOW";

  if(k!=z)

  {

    f=false;

    break;

  }

}

if(f==true)

return true;

else

return false;

}

The solution is called a pull down resistor and it's exactly the same as when you are using a button - the button is what connects the pin to +5V. The pull down resistor (usually around 10kΩ) connected to ground is what makes the pin read LOW at other times.

Do you (original poster) really need it to read 0 when disconnected?  The Arduinos have a built-in pull-up resistor which you can easily enable (https://www.arduino.cc/en/Tutorial/DigitalPins), meaning it will read 1 when disconnected.  Your external device then has to pull the line to 0v to signal something.  This is a very common way of doing things.

Thanks Mark... I'll implement it in that manner..Thanks again


text:
Which one is IR led?
I've ever been so confused in my life. I'm new to Arduino and electronics but I just can't figure it out which diode is IR transmitter/receiver or even if it is IR. I know that IR is not visible to human eye but I'm really clueless and I need help distinguishing them. I think the black one is a receiver but when I connect the white/transparent one it lights up so I guess It's not IR diode, right? How do I test them to see it anyways?

The black one is probably receiver. If the other one lights up then it's a normal LED. You don't have an IR led...

If you connect one of these and you can see it light up with your naked eye then it is not an IR LED, it's a visible-light LED. It's also not an IR sensor.
If you want to see IR, point a digital camera (like in your phone) at it and apply power. The sensors in digital cameras almost always detect some IR, so you can see a faint light on the screen. To test this, point your phone at a TV remote and press the button. If you see a flashing light in your phone's screen, you know it can "see" IR (Most digital cameras have an IR filter to get rid of most of the IR going into the camera, but they generally allow enough IR through that if you point them directly at an IR LED you can usually see it, at least faintly.)
Note that you should be able to use a visible light LED as a light source for an IR photoresistor/photodiode/phototransistor, since visible light LEDs will also give off some IR. However, an IR LED will put out a WHOLE LOT more IR than a visible light LED at of the same power.
The black one is probably an IR receiver. The color of the lens probably blocks visible light but not IR.
All the IR LEDs I've seen have looked clear, but I could not see any visible light when I powered them up.

The dark coloured one is an IR photodiode.
Osram SFH203-FA
Hope that hemps.
:)


text:
Long range wireless RC airplane control
I pretty new to Arduino and I need help to clarify some things.
 First, I want to make an Arduino controlled RC airplane but I don't know what communication module to use. I did some research and found three options.
1. Hc 12 Bluetooth: It has a decent range of about
    1.8km, buy suffers from delay(it can't be used on
     fast rc cars or airplanes)
2. Nrf24I01: About 850m in open space, uses
     2.4ghz which perfect for RC planes but doesn't
     really work through walls.
3. Lora: has a range of up to 10km but I didn't read on it that much.
So my question is: which one is better to use in a mini uav. I have no problem with mounting an antenna on top of my building. Will any of these work or is it better to use a wifi module connected to a modem which gives it internet access so that I can control the plane over the internet.

Any standard RC. For long range TBS CrossFire. For standard range (up to 2 km) - any other 2.4 control. Let say Jump[er T16 with any RX. As you new in Arduino I guess you also new in flight controllers SW. So better to start with something already manufactured. Let say legacy (old) ArduPilot was based on Arduino Mega. Sources can be found on APM site.

Can you pls elaborate more. By the way, I'm on a tight budget.

i think that HC12 is not a bluetooth module

you could use a module that uses the cellular phone network

@Brandy, what do you mean: APM is here: https://github.com/ArduPilot/ardupilot TBS is here: https://www.team-blacksheep.com/shop/cat:cat_crossfire#product_listing Any RC things are expensive except toys

@jsotola, no. It will not work because of latency. Nothing that has more than 20-40ms delay will never work with UAV (may be with car but on very slow speed).

i like ESP-NOW; cheap, fast, semi-simple, longer range than raw wifi.

I guess I’ll have to use the ESP for the project. Thanks


text:
How to use a non-adafruit BMP280 sensor for continuous data outflow
please I need help with the arduino BMP280 breakout board I got from  AliExpress. I’m pretty new to the arduino world, I need it for my rocket datalogger, I downloaded the adafruit BMP280 library but I don’t know how or where to change the data rate and what does the “default standby time” mean in the library sensor code? I want to get at least 10-20points of data per second as the rocket will be traveling very fast. Can someone please help me with a solution, or if there’s another library that solves my problem. I’m really stuck. Also, I don’t want my code to stop while waiting for temp, pressure and altitude values and also get the altitude before launch so that I can now the approximate height of the rocket above see level. Any help would be appreciated.
Details
Connection type: 12c
Application : Water rocket altimeter/datalogger and flightcomputer.
Brand: Unknown
Microcontroller: Arduino Nano

you said nothing about what you have ... you only described what you want to use it for ... please provide a link to the datasheet for the device

Show what you've done so far in getting the altitude from the pressure reading, and what stop you from reading it multiple times?

Take a look at the source code of Adafruit library

With a single instantaneous pressure reading you can't get sea-level and elevation. You need to know sea-level to get elevation. You need to know elevation to get sea-level. You can get a "flight level" by setting the sea-level pressure to 1013.25hPa but that's only a true elevation on a very small number of days in the year (if any). So you need to work out how you're going to set the MSL value for your altimeter before flight. You really need to post the code that you've tried so far.


text:
How to code an arduino to execute a particular code using a slide switch
I’m pretty new to arduino. I need help concerning a project I’m making. I’m using a SPDT slide switch to switch between what code(method) should be executed.i.e when I shift the switch to the left, XXX method should be executed and when I move the switch to the right, YYYY method should be executed. The center pin of the switch is connected to arduino +5v while the     left and right leg of the switch are connected like how a tactile switch is interfaces with the arduino. Please can anyone help me with the code, or at least how to program the arduino? Thank you

Your switch wiring for D12 is wrong. You connect your inputs directly to ground and that can never change, regardless of the position of the switch.
You effectively have:

simulate this circuit – Schematic created using CircuitLab
However you are over complicating things.  A SPDT switch is nothing more than two buttons, only one of which can be pressed at one time.  If one is pressed the other must be released.
You can completely ignore half the switch and treat the other half as a button: if the "button" is pressed then the switch is in one position. If the "button" is released then it's in the other position.
Unless it's a "center off" switch, in which case it has 3 positions, not 2, and the middle one has nothing connected.
If it is a simple 2-position SPDT switch then just disconnect the D12 wire and remove the right-and resistor in your drawing. Then read D13 to determine the position: HIGH is one position and LOW is the other.
If it's a 3-position "center off" switch then move the D12 wire 4 holes to the left so that it connects to the switch-resistor junction, not ground. Then you will need to read both D12 and D13 - which ever one is HIGH is the one that is activated, and the switch is in that position.
Then it's a simple "if / else" (2 position) or "if / elseif / else" (3 position center-off) structure to decide which code to run.

“Your switch wiring for D12 is wrong. You connect your inputs directly to ground and that can never change, regardless of the position of the switch.”  I don’t understand how it is wrong, each side of the switch is basically like a push button, and that’s the exact same wiring as a push button.  I do agree with “However you are over complicating things. A SPDT switch is nothing more than two buttons, only one of which can be pressed at one time. If one is pressed the other must be released”. It’s a 2 position switch.

The method I first used did work but once I move the switch to one position, it won’t go back to its former position(as in not physically). I think maybe there’s a problem with the code.


text:
Previous and updated releases of Arduino IDE are not be able to start on Win 8.1 x64
I have tried to install many versions of IDE, but non of them has started successfully. There is just the logo of the program shows up and then nothing happens.
My laptop: Toshiba Satellite C50-A630
The releases I have installed: 1.6.12 , 1.6.13, 1.0.6

Which Java Version you got installed?

Delete your preferences.txt file.

I had the same problem with various IDE versions. Deleting the preferences.txt solved the problem for me.


text:
Can I send data from one MKR1000 to another MKR1000
I want to simply send data from one MKR1000 to the other over wifi, both are connected to the same network, but sending the data is where I get stuck, I've looked through tuts everywhere but can't seem to find an answer.. can someone point me to a solution?
I've set up my devices using the tut https://www.arduino.cc/en/Tutorial/Wifi101WiFiChatServer
but the devices don't communicate to each other they only take telnet from the host server(my laptops wifi hotspot)

You want one device as the server. The other needs to be a client that connects to the server.

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.
If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.
client socket
if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side
WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}

You led me to a good tut, sometimes the right google search helps, thanks for your response

I found a tutorial that explains exactly what Majenko and Juraj explained,
https://www.instructables.com/id/MKR1000-IoT-Clientserver-Communications/
the library code that the tutorial references is useful, the tutorial is useful to us learning communication


text:
Coding issue with for loop
I have an issue with this piece of code concerning the use of 3 capcitance sensors each outputting a midi note chosen from one of three scales selected with a pot. Regarding the sensors triggering notes and the pot selecting scales, everything is perfect.
However, each sensor will play each of the scale's notes by itself with each finger press. This of course is not what I am intending as each sensor should only trigger its corresponding note. Thanks for any clues and tips!!
    #include <SPI.h>
#include <CapacitiveSensor.h>
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();
// midi notes
int c3 = 36;
int d3 = 38;
int e3 = 40;
int g3 = 43;
int a3 = 45;
int c4 = 48;
int d4 = 50;
int e4 = 52;
int g4 = 55;
int a4 = 57;
int c5 = 60;
int d5 = 62;
int e5 = 64;
int g5 = 67;
int a5 = 69;
int c6 = 72;

/////// code & 2d array for scale selection
const int columns = 3;
const int scales = 3;
int potVal = 0;
const int  notes[scales][columns] = {
  {c3, d3, e3},
  {c4, d4, e4},
  {c5, d5, e5}
};

const int numberOfSensors = 3;
int sensorPin[numberOfSensors] = {38, 39, 40};
/////////

static const unsigned ledPin1 = 22;      // LED pin on Arduino Mega
static const unsigned ledPin2 = 23;
static const unsigned ledPin3 = 24;

int val = 10; // this value is best around "10". works with "multiply"
// and "Threshold" to enable Polyphony!
int Threshold = (0); //Threshold of triggered mp3
int Multiply = (0);  //increases or decreases the overal sensitivity

CapacitiveSensor   cs_2_38 = CapacitiveSensor(2, 38); //Mega sensor pins
CapacitiveSensor   cs_2_39 = CapacitiveSensor(2, 39);
CapacitiveSensor   cs_2_40 = CapacitiveSensor(2, 40);

void setup()
{
  for (int i = 0; i < numberOfSensors; i++) {
    pinMode(sensorPin[i], INPUT);
    Serial.begin(9600); //midi(31250)

    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);

  }
}
void loop()
{
  int potVal = map(analogRead(A2), 0, 1024, 0, 3);
  for (int i = 0; i < numberOfSensors; i++) {
    checkSensor(potVal, i);
  }
}
void checkSensor(int scaleIndex, int columnIndex)
{
  static boolean lastSensorHit1 = false;
  static boolean lastSensorHit2 = false;
  static boolean lastSensorHit3 = false;

  bool sensorHit3 = cs_2_40.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit2 = cs_2_39.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit1 = cs_2_38.capacitiveSensor(Multiply) / val > (Threshold);

  Multiply = map(analogRead(A0), 0, 1023, 150, 5);
  Threshold = map(analogRead(A1), 0, 1023, 150, 5);

  long total1 =  cs_2_38.capacitiveSensor(Multiply);
  long total2 =  cs_2_39.capacitiveSensor(Multiply);
  long total3 =  cs_2_40.capacitiveSensor(Multiply);

  int Art1 = total1 / val;
  int Art2 = total2 / val;
  int Art3 = total3 / val;

  if (sensorHit1 != lastSensorHit1)

    if (sensorHit1 && !lastSensorHit1)
    {
      digitalWrite(ledPin1, HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 80, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin1, LOW);
      MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }

  if (sensorHit2 != lastSensorHit2)

    if (sensorHit2 && !lastSensorHit2)
    {
      digitalWrite(ledPin2, HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 79, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin2, LOW);
      MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }

  if (sensorHit3 != lastSensorHit3)

    if (sensorHit3 && !lastSensorHit3)
    {
      digitalWrite(ledPin3, HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 78, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin3, LOW);
      MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }

  lastSensorHit1 = sensorHit1;
  lastSensorHit2 = sensorHit2;
  lastSensorHit3 = sensorHit3;

}

You should have another function to do that sensor checking so there isn't all that cut'n'paste code (which some folks consider bad programming). In your checkSensor() function check which sensor is active and call the new function to process it. I'd probably use a switch/case construct for that https://beginnersbook.com/2017/08/cpp-switch-case/

what does this mean? ... it does not make any sense to me ... each sensor will play each of the scale's notes by itself with each finger press

Thanks for your help. @jsotola...it means that if I keep tapping the first sensor only, i will hear each of the scale's notes, one after the other so I know the problem is to do with the for loop as it keeps cycling around. In fact, all the sensors will do this. I guess I'm not sure how to do that with a seperate function but I will look into it Dougie, thanks

you say keep tapping ... does that mean that you tap the sensor and you hear one note, then you tap again and hear the next note, and so on?

Yes, that is correct. Of course, if I keep my finger on the sensor then I hear the sustain of that note until I take my finger off again

and, that is not what you want? ... you do not want to hear the next note, you want to hear the same note on each tap?

You are correct jsotola. I only want to hear the same note on each tap of the same sensor

Well after more tinkering I found that the one change that fixed everything was simply this (in the if/else statements).....changing MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1); to MIDI.sendNoteOn(notes[scaleIndex][0], 127, 1); [columnIndex] needs to be a [0], [1] or [2] representing one of three scales in the assigned array. This is fine as I'm writing out the code for a few sensors. However, for 16 sensors I'm going to have to use a for loop ....Thanks for all your help! Here's the full code for anyone who needs it...including some alterations to the leds...
#include <CapacitiveSensor.h>
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();

 int c3 = 36;
 int d3 = 38;
 int e3 = 40;
 int g3 = 43;
 int a3 = 45;
 int c4 = 48;
 int d4 = 50;
 int e4 = 52;
 int g4 = 55;
 int a4 = 57;
 int c5 = 60;
 int d5 = 62;
 int e5 = 64;
 int g5 = 67;
 int a5 = 69;
 int c6 = 72;

const int columns = 3;
const int scales = 3;
int potVal = 0;
const int  notes[scales][columns] = {
  {c3, d3, e3},
  {c4, d4, e4},
  {c5, d5, e5}
};
const int numberOfSensors = 3;
const int sensorPin[numberOfSensors] = {38, 39, 40};

const int ledPin[numberOfSensors] = {22, 23, 24};

const int val = 10; // this value is best around "10". works with "multiply"
// and "Threshold" to enable Polyphony!
int Threshold = (0); //Threshold of triggered mp3
int Multiply = (0);  //increases or decreases the overal sensitivity

CapacitiveSensor   cs_2_38 = CapacitiveSensor(2, 38);
CapacitiveSensor   cs_2_39 = CapacitiveSensor(2, 39);
CapacitiveSensor   cs_2_40 = CapacitiveSensor(2, 40);

void setup()
{
  Serial.begin(9600);//midi(31250)
  for (int i = 0; i < numberOfSensors; i++) {
    pinMode(ledPin[i], OUTPUT);
}
}
void loop()
{
    int potVal = map(analogRead(A2), 0, 1024, 0, 3);
for (int i = 0; i < numberOfSensors; i++) {
    checkSensor(potVal,i);
  }
}
void checkSensor(int scaleIndex, int columnIndex)
{
  static boolean lastSensorHit1 = false;
  static boolean lastSensorHit2 = false;
  static boolean lastSensorHit3 = false;

  bool sensorHit1 = cs_2_38.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit2 = cs_2_39.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit3 = cs_2_40.capacitiveSensor(Multiply) / val > (Threshold);

  Multiply = map(analogRead(A0), 0, 1023, 150, 5);
  Threshold = map(analogRead(A1), 0, 1023, 150, 5);

  if (sensorHit1 != lastSensorHit1)

    if (sensorHit1 && !lastSensorHit1)
    {
      digitalWrite(ledPin[0], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][0], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[0], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][0], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }
    if (sensorHit2 != lastSensorHit2)

    if (sensorHit2 && !lastSensorHit2)
    {
      digitalWrite(ledPin[1], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][1], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[1], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][1], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }
    if (sensorHit3 != lastSensorHit3)

    if (sensorHit3 && !lastSensorHit3)
    {
      digitalWrite(ledPin[2], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][2], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[2], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][2], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }

  lastSensorHit1 = sensorHit1;
  lastSensorHit2 = sensorHit2;
  lastSensorHit3 = sensorHit3;

}````````

I am just learning this program so I could be way off on this and I apologize if I am.
Instead of the loop inside of void setup() initialize each pin individually. Also you are telling the system to start the MIDI and set the pinMode 3 times.
Inside the Void checkSensor function you set all the sensorHits every time the function runs, you might save a little bit you do lastSensorHit(i).
I just noticed you have the if command running this function as (int i = 0; i < numberOfSensors; i++).  You don't have a sensor 0, so you might want to change that to (int i = 1; i < numberOfSensors+1; i++)// or just change it to 4.
Inside the function checkSensor, it doesn't look your variable val has a value.
if (sensorHit1 != lastSensorHit1) this is still under the same function as before and it is going to run once per channel that you specified in the controlling if function.
Maybe move this into the void loop() or create its own function?

Thanks Jeff A...you've made some interesting points. I'll have a chance to work again with this later tonight and will report back with my progress!

Thanks for your help everyone but this is way above my head I'm sorry to say. I need to go and learn about all the processes taking place within this code so that I can approach it better .

I hope you can get it figured out.  Good luck and Merry Christmas

Absolutely!! Merry Xmas to you too Jeff A

AWESOME, good job.  To make it easier to read can you put ```` at the beginning and end of your code, it will make it easier to read.  Its the key to the left of 1

Yes, I can never get to grips with posting on this forum. I'll edit that now!


text:
How to connect accelerometer, GPS, microphone and a GSM module to a Arduino?
I am a noob in the Arduino world and have only started reading about it. I have zero experience with Arduino some suggestions to increase my level will also be highly appreciated. But I have a lot of ideas, I want to work on.
I want to measure the velocity and noise levels with the GPS coordinates of a moving vehicle and send it to my phone using gsm or wifi.
Should I include a small LCD also? again suggestions will be highly appreciated.

https://arduino.stackexchange.com/tour

It depends.
If you are a beginner, do it in steps:

Get an Arduino Uno
Get a feeling for MCUs connecting a LED and resistor.
Connect the buzzer and get it working.
Disconnect it, connect the display and get it working.
Same for one sensor.
Than try multiple sensors.
Than play with the WIFI module.
Than combine everything.

The key is to split up your (for a beginner) big project into smaller easier to handle projects.
If you want to add an LCD, depends fully on YOUR requirements; we don't know exactly what you want. If you send all data via WIFI in principle the receiver can display it, but maybe you have a good reason to display it on a display.


text:
GSM module not working after power off
I am making a project on gsm module(sim 900a unofficial shield), when I will send a SMS led will turn ON. after uploading code, module works fine, and led turned ON after sending message. But when I power off sim900a and Arduino, and power on back, it's not working, led not power up after sending message, when I reupload sketches it is working fine, means every time after power off I need to upload code again, I am learning c and don't have much knowledge? Is my code right? Or some other fault?
#include <SoftwareSerial.h> //software serial library for serial communication b/w arduino & GSM

    SoftwareSerial mySerial(8, 9);//connect Tx pin of GSM to pin 8 of arduino && Rx pin of GSM to pin no 9 of arduino

    int led = 7;
    String message;

    void setup()
    {
      mySerial.begin(9600);   // Setting the baud rate of GSM Module
      Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
      delay(100);

      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
      pinMode(led,OUTPUT);
      digitalWrite(led,LOW);
    }

    void loop()
    {
      if (mySerial.available()>0){
      message = mySerial.readString();
      }

      if(message.indexOf("ON") > -1){
          Serial.println("LED ON");
         digitalWrite(led,HIGH);
         }
        else if(message.indexOf("OFF") > -1){

          Serial.println("LED OFF");
          digitalWrite(led,LOW);

      }

      delay(10);
    }

Circuit diagram

The GSM takes time to start up.  Your program needs to be far more complex than the simple "Throw commands at it and hope" method you are using.
First you need to query the modem repeatedly until it responds.  This is usually done with the AT command.  A sequence would look like:
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Recv: OK

Once the modem has booted and is ready to receive commands you can start sending commands.  You shouldn't just "print and delay" though like you are at the moment. Instead you should send the command and then examine the response to see if the command worked ("OK") or failed ("ERR").

Is there any librery for it on GitHub, or do you have any prewritten code that work fine, I have not much knowledge of 'C', I am a farmer and my farm is 3 k.m. from my home, so I want to make water motor automatic that I want to control from my home,

@Devid The Arduino IDE comes with a GSM library bundled with it. I have never used it though, so I don't know if it works with the SIM900A.


text:
How to set a not plugged in pin to ground or Low
I have digital pin 7 when set to High it does and when set to low it does not.
The only way I can get consistent High or Low is to use a 2 position 3 pin switch with my pin 7 in the middle and ground on one side and 5v on the other.
Is there a way I can use an simple Open/Close switch and still get the same function?
As of not if I dont "pull" pin 7 to ground I get both open and close randomly.

Have you configured the pin as input? Please provide the code and your wiring diagram. A not connected pin, that is set as input, catches random noise, thus changes state rapidly.

Yes the pin is set to input, is there a way I can remake the circuit were it does not catch noise when it is open?

output+dwrite(low) doesn't ground it?

Seems like you already found the solution. Without a pull-down of pull-up resistor, the voltage at pin 7 will float to some random voltage, when the switch is open.
Either add an (external) pull-down resistor. Or flip things around and use the internal pull-up resistor inside the ATMega328p. Then connect the other side of the switch to GND. Whenever the switch is pressed, your digitalWrite gives you a LOW.
To use the internal pull-up use pinMode(7, INPUT_PULLUP);

This worked perfectly thanks for the advice it was super helpful.


text:
Send large files to API via HTTP
I am making a stream-based radio clock that needs to send snippets of the stream to an external API for music recognition using an ESP-WROOM-32 DevKit.
The snippets that I record are 15 seconds long, which results in a file ~2MB in size (assuming the stream is 128Kbps, MP3). If I try to buffer this in the ESP32's RAM, it will fill it up in no time.
How can I send that snippet via HTTP without overflowing the ESP's RAM?

Use one of the ESP32s with the 8MB PSRAM?

Can't you stream the snippets? If you can, then you don't need to store them.

i don't like shying away from a challenge, but this is more apt for an SBC than an MCU.


text:
Java NetBeans sending value and receiving value from Arduino
This is my Java code to send a value to Arduino and a receiving value from Arduino. Can anyone tell where I made a mistake? I am able to send the value but can't receive a value from Arduino.
package hell;

import com.panamahitek.ArduinoException;
import com.panamahitek.PanamaHitek_Arduino;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class led extends javax.swing.JFrame
{
    PanamaHitek_Arduino Arduino  = new PanamaHitek_Arduino();
    private BufferedReader input;
    SerialPort serialPort;

    public led(){
        initComponents();
        try {
            Arduino.arduinoTX("com3", 115200);
        }
        catch (ArduinoException ex) {
            Logger.getLogger(led.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    public synchronized void serialEvent(SerialPortEvent oEvent)
    {
        System.out.println("lol 31");
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                System.out.println("lol 1.1");
                Scanner s = new Scanner(serialPort.getInputStream());
                int mes =Integer.parseInt( s.nextLine());
                System.out.println(mes);
                System.out.println("lol 1");
            } catch (Exception e) {
                System.err.println(e.toString());
                System.out.println("Syncronice ");
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(0);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is off");
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(1);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is on");
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new led().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;

    try{
        Arduino.sendByte(1);
    }
    catch(Exception ex){
        Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
    }

    System.out.println("led is on");

    private javax.swing.JButton jButton2;
}

Here is my Arduino code, which receives a value from Java and prints it accordingly:
int val = 0;
int led = 8;

void setup() {
  Serial.begin(112500);
  pinMode(led, OUTPUT);
}

void loop() {
  if (Serial.available()>0) {
    val = Serial.parseInt();
    if(val == 1) {
      //Switch on the LED, if the received value is 1.
      digitalWrite(led, HIGH);
      Serial.println("Succesfully received.");
    } else if(val == 0) {
      //Switch off the LED, if the received value is 1.
      digitalWrite(led, LOW);
    }
  }
}

EDIT:
There is no problem to controlling arduino via Java code, the problem is that I can't received message from Arduino to display in a Java.

I don't see any initialization of serialPort or serialEvent being called anywhere. And I doubt you will be able to open the port again, if it's already opened by Arduino object. Also you are reading a line from the Arduino and parse it as an integer, but the only thing you are sending from the Arduino is the string "Succesfully received.".

You are writing a number as a single byte and expect it as a string on the other end.
Replace
val = Serial.parseInt();

with
val = Serial.read();

sorry i forget to mention that there is no problem to controlling arduino via java code, the problem is i cant received message from arduino to display in a java..

i have added java jbutton code to control arduino


text:
Intermittent LOW reading from input pin set to INPUT_PULLUP
i have an output pin connected to a magnetic reed switch. The pin mode is INPUT_PULLUP. When the switch is closed, it connects the pin to GND and drags the pin to a LOW reading. I check the state of the pin in the loop function. Occasionally the pin reads LOW when it shouldn't (the switch is not closed) - e.g. around once per second. What could cause this? The wire from the pin to the switch is about 1m long - could this be long enough to intermittently drag it down to a LOW? Also, it seems to happen much more when the air temperature is hotter.
Circuit summary: Pin (INPUT_PULLUP) -> Magnetic reed switch -> GND

My guess would be that you're getting noise interference on the line and it's too much for the Arduino's little internal pullup.  Try adding an external pullup resistor - say 5k-10k (exact value is not critical).

Thanks, you are correct. I managed it through code. E.g i'm now taking 10 samples a second, and to change state it needs 10 consecutive samples to be the same reading. This has been working without fail now for days. I suspect noise can only pull the pin down briefly (nanoseconds?)

Yes it will be brief, but how frequent will depend upon where the interference is coming from - it could conceivably happen a lot.  If that's working for you then it sounds like a reasonable workaround.


text:
HEF4094 with 12v Vcc
Using old NXP HEF4094BP shift register chips, for the reason of fixing some old hardware. These chips were popular in the 90's because they could accept 3-15V VCC and directly drive series+parallel LED chains. Think: gas station price signs, etc.
I'm green. Using this post and the 4094 datasheet, I've successfully modeled your typical shift register count-to-100 binary, with an LED on each SR out. Powered by 5V, works great. This was phase 1 for me.
For phase 2, I powered the Arduino via 12V (via p30, Vin). Still supplying 5V to the 4094 (Nano pin 27 output), works great.
Phase 3, I need help. I remove the 5V jumper that was from Nano pin 27 going into 4094's VCC pin. In it's place, I run 12V directly from the (regulated) PS and I get NO LED output.  I know I haven't burned anything out because at 12V I get brief "flashes" when I'm "plugging" in the 12V power supply. I can revert to 5V VCC input and it works fine as before.
I've read the datasheet 3X and it's not clear how the chip's output pin voltage is managed when you alter the VCC to be higher (is it limiting current or voltage on the outputs?)

The part of the datasheet you need to understand is this bit:

That's the input logic levels, and as you can see they vary depending on the supply voltage.
At 10V you need to supply at least 7V to get a HIGH registered. At 15V you need 11V or more. So at 12V you can expect that level to be around 9V and upwards.
The Arduino outputs 5V. That's nowhere near 9V, so the chip completely ignores it.
These chips are not designed to be level translators. They are designed to work with other chips that also run at the same voltage. To use it at a higher voltage that the chip that's driving it you will need to employ some form of 5V to 12V level translation.

THANK YOU for the perfect answer. I get it -- signal requirements "scale" relative to the VCC so I need to boost the signal lines after leaving the Arduino. I haven't done this type of thing yet, but I've read all the SparkFun transistor tutorials more than once, and just need to "do" it. Cheers.

Not that I would change my design (I actually need to follow this approach to salvage something cool), but out of curiosity does anybody make a chip that functions how I was assuming things worked (5V high input expected regardless of VCC into the SR)? I'm surprised by the variety of SRs one can choose from, and from a novice user POC they're a pretty fun way to learn!

@Crossfit_and_Beer I'm not sure if there's a single chip solution off hand, but normally people use a low voltage shift register coupled with a higher voltage IO driver chip, such as the ULN2803. There are LED driving shift registers with constant current sinks available which run off 5V or 3.3V and can sink 12V happily, as well as I2C equivalents, both constant current and open-drain (TLC59116).  I am not aware of a single chip solution though, but I will have a google around for you.

Ah, a ULN2803. I'll look at that next, TY.    Yeah I suppose if one were creating a fresh design, I2C (or the ws2812s) would be the way to go - solving the problem neatly for nearly any type of signage.