text:
Use an LDR to run a sketch
This may sound like a simple question but I have tried to find the right solution but all I find is the usual make an led blink and even I can code that nugget
I am quite new to programming arduino but am a dab hand with a soldering iron.
What I would like to do is combine the attributes of an LDR to allow a lighting sketch to run if it is dark and go off in daylight, but all I seem to find is turn a pin high or low, this is no good as I already have a sketch I would like to run
I am using WS2811 led nodes housed in pinspot style housings so the sketch would need to check the light level and if it is below a set value run the rest of the sketch then check every hour to see if the light level has changed to be above a set level  if it is go into a check loop until the light level falls again to below the set value can anyone point me in the right direction I would be grateful for any assistance
Thanks
Dave

Can you show us the "lighting" sketch you written?

It sounds like you need to put your light code in an if statement that checks the light level.  I know I’ve seen this project done over and over so I don’t believe you can’t find an example.  If you find one that just sets a pin high or low in response to the ldr then you’re almost there.  Just take out the line that turns the pin high or low and replace with code that turns your led strip on or off.  It’s really just that simple.

the function that reads the value of an LDR and the function that turns on the lights are two completely separate functions ... the LDR function raises a flag that says light on ... it does nothing else .... the light function turns on the light if it sees the flag .... it does nothing else .... the light on flag could also be raised by a pushbutton being pressed or by a timer or by sound detector hearing noise, etc.

You're unlikely to find exactly what you want as existing code example. Break it into parts and solve it in parts.
You can't "Run a sketch" based on reading a value of an LDR. You can write a new sketch that reads an LDR, and calls a function if it's dark, or a different function if it is light. You will need to refactor your code from your other sketch into functions that you can integrate into your new combined sketch that uses the LDR. That means doing some original programming, not "finding the right solution" ready-made on the internet.
First, how do you use an LDR to determine if it's light or dark? Answer, use an analog input. Build a voltage divider with the LDR and a similar sized resistor, and feed the output into an analog pin. Say the LDR is between +5V and the pin, so more light results in higher voltage, hence a larger value.
Log the output of the LDR to the console in a loop, and decide on your threshold values for light and dark. Make the threshold value a constant. Let's call it DARK.
Now write a loop function. It might look something like this:
int lightValue;
#define ldr_pin xxx //your pin number
#define threshold xxx //your threshold value

void setup() {
   //set the ldr pin as an analog input
}

void loop() {
   lightValue = analogRead(ldr_pin);
   if (lightValue <= threshold) {
      doNightStuff();
   } else {
      stopDoingStuff();
   }
}

Edit:
As mentioned by Edgar, the code above will be subject to "jitter", where it will rapidly switch back and forth between the dark and light states.
The solution is to add a buffer range where once it's in one state, it doesn't change states until it leaves the buffer range.
The if statement might look like this:
#define buffer 5

if ((lightValue +buffer) <= threshold)
    doNightStuff();
else if ((lightValue -buffer) >= threshold)
    stopDoingStuff();

It would be still better with two thresholds that provide some hysteresis.

Fair point, but I think that might be beyond the OP's current level of understanding.

You are probably right. OTOH, without hysteresis, the OP is likely to be coming back here pretty soon. :-)

if you power the LDR with an INPUT_PULLUP pin instead of VIN, you don't need a fixed resistor to form your divider, just plug the other LDR lead into the analog input. This won't give you full range, but it's more than enough resolution to distinguish dark from light.

simple adding of hysteresis, replace all loop code but first line: if ((lightValue +5) <= threshold) doNightStuff(); if ((lightValue -5) >= threshold) stopDoingStuff(); Adjust as needed.

@ Duncan C
think i have a solution not sure if it's your way but it does work so not bad for a newbie lol
//
//  "Pacifica"
//  Gentle, blue-green ocean waves.
//  December 2019, Mark Kriegsman and Mary Corey March.
//  For Dan.
//  Thanks for the sketch i have added a daylight sensor so they now go off in daylight Dave Cowell June 2020

int lightValue;  //new code dc

#define FASTLED_ALLOW_INTERRUPTS 0
#include <FastLED.h>
FASTLED_USING_NAMESPACE

#define ldr_pin             A0   //new dc
#define Threshold_dark      100  //new dc
#define Threshold_light     1000  //new dc
#define DATA_PIN            7
#define NUM_LEDS            28
#define MAX_POWER_MILLIAMPS 500
#define LED_TYPE            WS2811
#define COLOR_ORDER         RGB

//////////////////////////////////////////////////////////////////////////

CRGB leds[NUM_LEDS];

void setup() {

  analogRead (A0);  //new dc

  delay( 3000); // 3 second delay for boot recovery, and a moment of silence
  FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
        .setCorrection( TypicalLEDStrip );
  FastLED.setMaxPowerInVoltsAndMilliamps( 5, MAX_POWER_MILLIAMPS);
}

void loop(){

 lightValue = analogRead (ldr_pin);  //new dc

 if (lightValue <= Threshold_dark){    // new dc

    EVERY_N_MILLISECONDS(20)
    pacifica_loop();
    FastLED.show();

 }else { (lightValue = Threshold_light);  // New dc

 {                                         // New dc

 for (int i = 0; i <NUM_LEDS;i++){         // New dc

      memset (leds,0,NUM_LEDS*3);          // New dc

                FastLED.show();             // New dc

                FastLED.delay (100);         // New dc

 }         // New dc
  }        // New dc
   }       // New dc
    }      // New dc

//////////////////////////////////////////////////////////////////////////
//
// The code for this animation is more complicated than other examples, and
// while it is "ready to run", and documented in general, it is probably not
// the best starting point for learning.  Nevertheless, it does illustrate some
// useful techniques.
//
//////////////////////////////////////////////////////////////////////////
//
// In this animation, there are four "layers" of waves of light.
//
// Each layer moves independently, and each is scaled separately.
//
// All four wave layers are added together on top of each other, and then
// another filter is applied that adds "whitecaps" of brightness where the
// waves line up with each other more.  Finally, another pass is taken
// over the led array to 'deepen' (dim) the blues and greens.
//
// The speed and scale and motion each layer varies slowly within independent
// hand-chosen ranges, which is why the code has a lot of low-speed 'beatsin8' functions
// with a lot of oddly specific numeric ranges.
//
// These three custom blue-green color palettes were inspired by the colors found in
// the waters off the southern coast of California, https://goo.gl/maps/QQgd97jjHesHZVxQ7
//
CRGBPalette16 pacifica_palette_1 =
    { 0x000507, 0x000409, 0x00030B, 0x00030D, 0x000210, 0x000212, 0x000114, 0x000117,
      0x000019, 0x00001C, 0x000026, 0x000031, 0x00003B, 0x000046, 0x14554B, 0x28AA50 };
CRGBPalette16 pacifica_palette_2 =
    { 0x000507, 0x000409, 0x00030B, 0x00030D, 0x000210, 0x000212, 0x000114, 0x000117,
      0x000019, 0x00001C, 0x000026, 0x000031, 0x00003B, 0x000046, 0x0C5F52, 0x19BE5F };
CRGBPalette16 pacifica_palette_3 =
    { 0x000208, 0x00030E, 0x000514, 0x00061A, 0x000820, 0x000927, 0x000B2D, 0x000C33,
      0x000E39, 0x001040, 0x001450, 0x001860, 0x001C70, 0x002080, 0x1040BF, 0x2060FF };

void pacifica_loop()
{
  // Increment the four "color index start" counters, one for each wave layer.
  // Each is incremented at a different speed, and the speeds vary over time.
  static uint16_t sCIStart1, sCIStart2, sCIStart3, sCIStart4;
  static uint32_t sLastms = 0;
  uint32_t ms = GET_MILLIS();
  uint32_t deltams = ms - sLastms;
  sLastms = ms;
  uint16_t speedfactor1 = beatsin16(3, 179, 269);
  uint16_t speedfactor2 = beatsin16(4, 179, 269);
  uint32_t deltams1 = (deltams * speedfactor1) / 256;
  uint32_t deltams2 = (deltams * speedfactor2) / 256;
  uint32_t deltams21 = (deltams1 + deltams2) / 2;
  sCIStart1 += (deltams1 * beatsin88(1011,10,13));
  sCIStart2 -= (deltams21 * beatsin88(777,8,11));
  sCIStart3 -= (deltams1 * beatsin88(501,5,7));
  sCIStart4 -= (deltams2 * beatsin88(257,4,6));

  // Clear out the LED array to a dim background blue-green
  fill_solid( leds, NUM_LEDS, CRGB( 2, 6, 10));

  // Render each of four layers, with different scales and speeds, that vary over time
  pacifica_one_layer( pacifica_palette_1, sCIStart1, beatsin16( 3, 11 * 256, 14 * 256), beatsin8( 10, 70, 130), 0-beat16( 301) );
  pacifica_one_layer( pacifica_palette_2, sCIStart2, beatsin16( 4,  6 * 256,  9 * 256), beatsin8( 17, 40,  80), beat16( 401) );
  pacifica_one_layer( pacifica_palette_3, sCIStart3, 6 * 256, beatsin8( 9, 10,38), 0-beat16(503));
  pacifica_one_layer( pacifica_palette_3, sCIStart4, 5 * 256, beatsin8( 8, 10,28), beat16(601));

  // Add brighter 'whitecaps' where the waves lines up more
  pacifica_add_whitecaps();

  // Deepen the blues and greens a bit
  pacifica_deepen_colors();
}

// Add one layer of waves into the led array
void pacifica_one_layer( CRGBPalette16 & p, uint16_t cistart, uint16_t wavescale, uint8_t bri, uint16_t ioff)
{
  uint16_t ci = cistart;
  uint16_t waveangle = ioff;
  uint16_t wavescale_half = (wavescale / 2) + 20;
  for( uint16_t i = 0; i < NUM_LEDS; i++) {
    waveangle += 250;
    uint16_t s16 = sin16( waveangle ) + 32768;
    uint16_t cs = scale16( s16 , wavescale_half ) + wavescale_half;
    ci += cs;
    uint16_t sindex16 = sin16( ci) + 32768;
    uint8_t sindex8 = scale16( sindex16, 240);
    CRGB c = ColorFromPalette( p, sindex8, bri, LINEARBLEND);
    leds[i] += c;
  }
}

// Add extra 'white' to areas where the four layers of light have lined up brightly
void pacifica_add_whitecaps()
{
  uint8_t basethreshold = beatsin8( 9, 55, 65);
  uint8_t wave = beat8( 7 );

  for( uint16_t i = 0; i < NUM_LEDS; i++) {
    uint8_t threshold = scale8( sin8( wave), 20) + basethreshold;
    wave += 7;
    uint8_t l = leds[i].getAverageLight();
    if( l > threshold) {
      uint8_t overage = l - threshold;
      uint8_t overage2 = qadd8( overage, overage);
      leds[i] += CRGB( overage, overage2, qadd8( overage2, overage2));
    }
  }
}

// Deepen the blues and greens
void pacifica_deepen_colors()
{
  for( uint16_t i = 0; i < NUM_LEDS; i++) {
    leds[i].blue = scale8( leds[i].blue,  145);
    leds[i].green= scale8( leds[i].green, 200);
    leds[i] |= CRGB( 2, 5, 7);
  }
  {

  }
}


text:
Is it possible to exit a loop on the change of an input state?
I would like to exit a particular loop if the state of an input changes from LOW to HIGH. This is the current loop:
void brakeFade() {
pixels.clear();
pixels.setBrightness(255);
pixels.fill(16711680, 0, 0);

for(int i=255; i>=10; i-=1) {
  pixels.setBrightness(i);
  pixels.show();
  delay(5);
  }
for(int j=10; j<=255; j+=1) {
  pixels.setBrightness(j);
  pixels.show();
  delay(5);

}
}
I need that loop to exit if
(digitalRead(brakeFeed) == LOW)

Changes to HIGH during the loop.

there is no reason to use two different named index variables, i and j, in the two for loops ... they can both be i .... increment can be done using i++ instead of i+=1 ... same with decrement

figured it out:
void brakeFade2() {
pixels.clear();
pixels.setBrightness(255);
pixels.fill(16711680, 0, 0);

for(int i=255; i>=10; i-=1) {
  if (digitalRead(brakeFeed) == LOW){
  pixels.setBrightness(i);
  pixels.show();
  delay(5);
  }
  else {
    break;
  }
}
for(int j=10; j<=255; j+=1) {
  if (digitalRead(brakeFeed) == LOW){
  pixels.setBrightness(j);
  pixels.show();
  delay(5);
  }
  else {
    break;
  }
  }

}

simpler way would be to add it to the completion test of the for loop ...  for(int i=255; (i>=10) or (digitalRead(brakeFeed) == LOW);  i--) {

Wouldn't that be for(int i=255; (i>=10) && (digitalRead(brakeFeed) == LOW)? The OP wants the loop to continue as long as is >= 10, and the brakeFeed pin still reads as low. It should break if either of those stops being the case.

source: Stack Exchange

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

sort: votes


text:
Fast random booleans
I am looking for a way of generating booleans rapidly. For booleans, one usually uses random(0,2); but in my case I need about 250 booleans and calling random every time is slow.
So I thought about using all bits of a random number on the whole range as such:
randomSeed(100); // A seed to always keep the same sequence
long rdm = random(MIN,MAX);  // Generate a number in range MIN,MAX of type long
long mask = 1;
for(int i=0; i<32; i++){
    if((rdm>>i)&mask){
        //do something
    } else {
        //do something else
    }
}

But with this I have three questions:

What are MIN and MAX so that the LONG random uses all bits, with value ranging from -2,147,483,648 to 2,147,483,647 (arduino long type). I tried several MIN and MAX, also simply random(); but without success.
Is it a valid approach? Do I expect each bit to be uniformly distributed? Should I use fewer bits, e.g. random(0, 2^16); for a "better" distribution?
Is there some seed known to be good or bad at this?

My project
I am working on a device made of Neopixel LED strips. It is for a visual neuroscience experiment where each "pixel" is either ON or OFF. I need the speed to be able to reach high refresh rate (60-100Hz), with normal statistical distribution to avoid bias in neuron response analysis. With this approach, I can reach the desired speed but I'm concerned about the statistics. So I need a better understanding of random()'s behaviour to do it right!

are you sure it will be faster?

Good pseudorandom number generators are few and far between. I would not trust one from a microcontroller's library, which is optimized for speed rather than optimal statistic properties. On AVR, I would prefer the underlying no-parameter random(), which has 31 usable bits, over the one from the Arduino core, which only adds bugs. And I strongly recommend you test for the statistical properties you care about before committing to any PRNG.

@Juraj yes it's faster. Including the communication with Neopixel, when I was drawing one boolean per LED, I was displaying at around 30-40Hz. With this method I need only 8 random numbers to get the 250 bits, that allow me to display at 100Hz.
Quick benchmark (Arduino Uno) to assign value to each LED (237 total):
This method: 1.6ms  --
One rand per LED: 22ms --
(Neopixel communication: 2.05ms)

@EdgarBonet Thanks for the advice, I'll use just random() then to have the 31 bits. I'm using fixed seeds so I'm also checking how they distribute.

@Juraj I think this blog post is a relevant benchmark

I didn't try myself, but in the documentation it shows the MAX value is  2,147,483,647, which is 2^31-1. The MIN value I expect is -2^31, thus -2,148.483.648. Wondering what you mean by 'without success'.
Yes this is a valid approach. A 'perfect' random generator should be able to generate all values with an equal distribution. Since the values are within [-2^31, 2^31-1] this means all values within a 32 bit value is used, which automatically means all bits are also evenly distributed. So you can pick individual bits (as long as you use the entire MIN/MAX range).
In principle all seeds are good, as long as they are random. In the documentation it is advised to take an unconnected analog pin value. If you don't have one unconnected, you can use e.g. the millis function.

Arduino's two-parameter random() won't work as expected if max-min is larger than LONG_MAX.

@EdgarBonet Seems to me like a bug in the original Arduino (library). Using t hat library you refer to, or using 31 bits instead of 32 is than a solution. 8 instead of 7 calls needed, to get 250 booleans.

I wanted to show the weird output I got for MIN-MAX [-2^31, 2^31-1], but the source code say enough already. Thanks @Edgar

@Michel On the second point, I was more wondering specifically about the implementation in Arduino. Is it good enough to assume that all 31 bits are uniformly distributed? If not, taking for example only the first 24 bits should give better results, right? The previously assumed uniformity for these 24 bits is now an average of 2^7 values.

If the values returned are evenly distributed, it would not matter if you check bits one by one or the total value. Assume you use [0... max] and get a uniformly distributed 31-bit values, using 24 bits or 31 bits will not make the accuracy or results better.

After going around Wikipedia on pseudo-random generators, what I understand now is that the generator used in Arduino is a full-period generator. original paper. I thought differently. And please correct me if I'm wrong.

The random() function returns a number between 0 and RANDOM_MAX (0x7FFFFFFF). The random(min, max) function takes the value from random() and manipulates it to fit into the specified range (calculate the offset difference, modulus the random value by that difference, then add the lower offset).
That means that the widest range you can get is from random() directly, whilch is the same as random(0, RANDOM_MAX). However that is only ever going to be 31 bits, so your most significant bit will always be zero.
That's not what you want.
The best you can do to get 32 bits of random data is to take two random 31 bit values and combine them. Maybe left shifting one value by one bit and the XORing them together would be enough:
uint32_t rand1 = random();
uint32_t rand2 = random();
uint32_t fullrand = (rand1 << 1) ^ rand2;

Alternatively just working with 31 bits instead of 32 may be enough for your needs and would be faster than generating two numbers and combining them just to fill that one extra bit.

Thanks also for your answer, it adds to the comments of @Edgar. I was trying to understand why I was limited to 31 bits and now it's clear. 31 bits will do perfectly fine.

random(0, RANDOM_MAX) returns a random number between 0 and RANDOM_MAX-1 (inclusive), with 0 twice as likely as the other outputs.

Naaaasty. A good enough reason not to use Arduino's horrible overloaded versions of a standard library function.

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


text:
nRF24L01 only getting 10 meters range!
I am making a project where I need to communicate between two devices that are about 300-500 meters apart and might experience a lot of RF interference and obstacles. So I thought for initial testing the nRF24L01 modules will be good knowing that they are advertised at 500m. When I did a range test, I got only 10 meters and that too with no obstacles in between! This module seems to be the only choice I have so any suggestions on how to increase range will help immensely.
Stats:
nRF24L01+ module with PCB antennae and a socket adapter board.
I am using the nRFLite library and am transmitting at 2MBPS and have tried multiple channels!

a quick internet search reveals that you need an external antenna to achieve the communication range you require

Not directly related to nRF24L01, but I tested ESP-01 with PCB antenna running ESP-Now protocol, with small payload of about 40 bytes. I got about 250-300m without obstacles. But if there is obstacles (even just some trees), the distance reduced significantly and external antenna would be required.

The nRF24L01+ is only rated to about 10m. You can get modules with an additional power amplifier and antenna that boosts the range, but the standard range of a bare nRF14L01+ is only about 10m. For example, my K780 keyboard, which uses the SOC equivalent of the nRF24L01+ has in the specs "Powerful wireless connection with 10m/33ft range"


text:
Raspberry Pi 3B+ BLE communication to Arduino Nano 33 IOT
I have an Arduino Nano 33 IOT and it uses BLE. I want it to talk to my Pi 3B+ and send all of its sensor data. I cannot figure out a way to do it using Python for the Pi and ArduinoBLE library for my Nano IoT. Is it possible?

this describes the Arduino side ... you will have to figure out the RPi side since it is off topic here .. https://www.arduino.cc/en/Reference/ArduinoBLE

Okay thank you.

For completeness, it appears an appropriate Python library can be installed with:
pip3 install adafruit-circuitpython-ble

The test code, used with the Arduino code 'Echo' from the ArduinoHardwareBLE library is below.  This was updated to let you choose the name of the device (here, MY_BLE)  rather than any random device that has UART capability.  It also allows you to send a small file from a few lines, with a "#" denoting a comment (first character in the line).  ESC and a return quits the program.
# Connect to an "eval()" service over BLE UART.

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()

uart_connection = None

def send_stuff(s):
    uart_service.write(s.encode("utf-8"))
    uart_service.write(b'\n')
    readline=uart_service.readline().decode("utf-8")
    while(len(readline)>0):
        print(readline)
        readline=uart_service.readline().decode("utf-8")

while True:

    if not uart_connection:
        print("Trying to connect...")
        print("ESC then RETURN to exit.")
        for adv in ble.start_scan(ProvideServicesAdvertisement):
            if UARTService in adv.services:
                regular_name = adv.complete_name
                if(regular_name=='MY_BLE'):
                    uart_connection = ble.connect(adv)
                    print("Connected")
                    # for some reason, we have to read a line...
                    uart_service = uart_connection[UARTService]
                    print(uart_service.readline().decode("utf-8"))
                    break
        ble.stop_scan()

    if uart_connection and uart_connection.connected:
        uart_service = uart_connection[UARTService]
        while uart_connection.connected:
            s = input("Prompt: ")
            if(len(s)>0):
                if(ord(s[0])==27):
                    print("done.")
                    exit()
                else:

                    # Check if "!" character is used; if so, send contents of a file
                    if(s[0]=="!"):
                        print("sending commands")
                        count=0
                        file1=open('commands.txt','r')
                        Lines=file1.readlines()
                        for line in Lines:
                            count=count+1
                            tmp=line.strip()
                            if(len(tmp)>0):
                                if(tmp[0]=='#'):
                                    print("comment:" + tmp)
                                else:
                                    print("Line{}: {}".format(count, tmp))
                                    send_stuff(tmp)

                    else:
                        send_stuff(s)

Will this work on the Pi 3B+ because I don't know if it has BLE.

If you add a BT adapter, you should be able to.

The specs on the 3B+ say it has BLE, so this might work.  I have not tested it however; only with an Ubuntu 20.04 LTS system with (Anaconda) Python 3.7.7.


text:
Use normal TFT Shield with SD as a Nextion Display
I have a normal Elegoo TFT 2.8" display shield that also had an SD reader. I am trying to use it as a Nextion display. I want to do this because the Nextion tool allows you to make very nice looking sophisticated graphics and I wanted to do the same. Is there any possibility? Maybe some interpreter library?

why not? .... find a library that can display full screen graphics ... also a library that can overlay png images ... png overlay would need to be aware of transparency in the images

Can you suggest me some? I can't seem to find any.

search for Elegoo TFT 2.8" display ... find out what contoller is used ... then search for the controller

what do you mean by controller

the lcd module has a control chip that the arduino communicates with ... it understands high level commands ... there is no direct connection between the arduino and the lcd

No, you can't.
Nextion displays contain their own microcontroller with their own closed-source firmware on them.  You need that firmware to have a clue what is in Nextion files, and only Nextion have that firmware.
While it may be possible to reverse engineer Nextion display data and write your own software to interpret it, it would be a huge job with little to no real-world benefit.

You cannot use a 2.8" TFT as a Nextion Display. Two are seperate things
Nextion Display is an HMI. You can configure prebuilt menus and graphics without coding.
The 2.8" TFT is a generic display module. It prints data according to the commands it receives. The user has to prepare the data to be printed. It can read data from an sd card, but the user program has to issue the commands for it.
Nextion displays use a generic display like the 2.8" TFT, an onboard controller with custom firmware running on it.


text:
Power supply for DIY Arduino CNC Router
I am making a CNC router from a dremel and 3-5 NEMA 17 steppers. I am really confused on how I can power all those motors. I am using a RAMPS 1.4 with Arduino Mega. I have a 2.4A USB power supply. Is that enough? If not, what is the minimum specs I need to ensure that I don't burn, blow, or under power anything? I am trying to get my hands on a ATX power supply.

atx power supply may be useless ... it could shut down in response to a motor current spike

I have a 2.4A USB power supply. Is that enough?

Not by a long way, no.
NEMA 17 motors are typically 12V, not 5V, so a USB power supply is not even close.
You will need a decent 12V power supply with a lot of current.
My 3D printer has 3 NEMA 17 motors and uses a 200W 12V power supply. Most of that goes to the motors with only a comparatively small proportion to the hot end.
You need to know the current draw of the motors you are using (note: NEMA 17 defines the physical size, not the electrical characteristics).  Sum all those up for all your motors, and that's the absolute minimum you'll need from your power supply. Add some more on top for losses in the motor drivers and to power the Ardiuno.
And I'm not even considering the dremel in any of this...
So yes, an ATX power supply is probably a good choice.

The answer is great but do you know the minimum power requirement in amps?


text:
Unable to connect PN532 Board to Arduino Uno
I'm attempting to connect this PN532 NFC Board to an Arduino UNO using SPI. Currently my arduino is unable to recognize the board and I'm not sure whats the root of my issue. I'm using the Adafruit PN532 library and my program fails at trying to get the Firmwarm Version of the attached chip. I've attached the code and pictures of the soldering and connections. One interesting note is the LED on the chip will turn on before I connect VCC. The LED will turn on as soon as plug in MOSI (Not sure if that is intended behavior). Any ideas on where my issue might be?
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>

// If using the breakout with SPI, define the pins for SPI communication.
#define PN532_SCK  (13)
#define PN532_MISO (12)
#define PN532_MOSI (11)
#define PN532_SS   (10)

// Use this line for a breakout with a SPI connection:
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

void setup(void) {
  Serial.begin(115200);
  nfc.begin();
  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Could not find board");
    while (1); // halt
  }

  Serial.print("Found Board");
  nfc.SAMConfig();
}

void loop(void) {
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;

  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  if (success) {
    Serial.println("Found a card");
    }
    delay(2000);
}

MOSI pin and IRQ pin looks badly soldered ... could also be a reflection in a very good solder connection

you use the constructor for software SPI. use Adafruit_PN532 nfc(PN532_SS);. the SPI library knows the other pins


text:
Port manipulation: Coding for two chips
I am using Arduino Nano to test a code that will be ported on an ATTiny chip, which will need to perform operations at a frequency near clock maximum, calling for a very succinct coding.
My goal: to streamline coding for two different chips in one file with the least repetitions and operations possible.
Specifically, I have a pin
#ifdef TIMSK0 //Nano vs atTiny
const byte  wavePin  = 5,
            waveBit  = B100000;
      byte *wavePort = &PORTD;
#define NANO
#else
const byte  wavePin  = 0,
            waveBit  = PB1;
      byte *wavePort = &PORTB;
#endif

Notice the pointer? It works, but I have the impression this may not be the most efficient option, as it adds an operation (by looking up the reference). I have also planned to do constantly check which chip we are loading it in this fashion
#ifdef NANO
  PORTD
#else
  PORTB
#endif
  |=   waveBit *  waveOn);
#ifdef NANO
  PORTD
#else
  PORTB
#endif
  &= ~(waveBit * !waveOn));

But again, while this may be perfectly fine in operations, it hurts the eyes and is rather repetitive.
Is there a way to create a direct access to a port?

Are you familiar with C++ Macros?

Not yet? Tell me more :D

Do you mean to do something like #define WAVEPORT PORTD?

StarCat you opened me a can of worms and I love it :D Thanks it actually works!

Great! That is actually more or less what I meant.


text:
Wake up from a pin, Sleep when work is done
I have a project which needs to sleep most of the time, and when a button gets pressed, it does its thing which is producing a fading sound wave (using interrupts) until it's time to sleep again.
The goal is to reduce work load on the battery so the item can last as long as possible.
#include <avr/sleep.h>
void setup(){
  /*givePin! This is the pin that will spark the waking up!*/
  pinMode(givePin,INPUT);
  noInterrupts();
  set_sleep_mode(SLEEP_MODE_IDLE);
  /*changes to timers registers*/
  interrupts();
}
void loop(){
  ampCurrentlyOn = digitalRead(givePin);
  ampPulse =  (ampCurrentlyOn && !ampPreviouslyOn) * 255     //Reset
           + !(ampCurrentlyOn && !ampPreviouslyOn) * ampPulse//Same
           -   bool(ampPulse);  //Decay
  ampPreviouslyOn = ampCurrentlyOn;

  if(!ampPulse){//Once that value reaches 0 time to GOTO bed;
    /*This! Is this what I need to do?*/
    cli();
    sleep_mode();
    sei();
  }
}

Am I doing in the right direction? Could any pin work? How do I get the chip to understand a pin set to digital HIGH to wake up from nap time?
Thank you!

you search for something like attachInterrupt(digitalPinToInterrupt(givePin), [](){}, FALLING);? givePin must be pin capable of external interrupt.(pin 2 or 3 on Uno/Nano) ([](){} is empty anonymous function)

You shouldn't call cli before sleep, or it will never wake up. I also think you need to call sleep_enable();.

@Gerben: sleep_mode() takes care of calling sleep_enable().


text:
Fast PWM: Resolution in hertz
I am trying to get a nice sounding varying PWM to DAC, and intend to use a Sallen Key as part of an active low pass filter.
I set the Fast PWM at a max of 255 (WGM1[0-3] = 5) and set/clear OC1A upon comparing with OCR1A (1<< COM1A1)
I also update the value of OCR1A in 64 distinct steps, changing those steps around 15'000 times a second to create a specific sinusoidal shape.
As the chip works at 16 Mega Hertz, does this mean that one cycle of PWM is 16'000'000/256= 62.5 Kilo Hertz? If not, what is its resolution
Thank you!

As you are directly poking into the hardware I/O registers, you have to read the datasheet. Look for the prescaler, and the bits CS1[0-2].

Assuming you have no prescaler, you'd indeed get around 62.5kHz. The 15kHz update rate for the sinusoidal is a bit odd, as it's 1/4.167 of the PWM update frequency. I'd probably use the timers interrupt to call a function that updates OC1A every 4th call.

Thank you both for your answers! I read the datasheet but I guess without prescalers it's indeed 62.5kHz. The update will vary considerably as I'm trying to do the 12 tones of the scale. If I were to update OC1A every 4th PWM I'm not sure I'd be able to do a perfect period.

With the help of the comments, I decided to use variable PWM max values to match absolutely with the frequency. This resulted in a crispier sound that actually doesn't need the Sallen Key anymore.
For example, a low C natural, or 261.6Hz, updated 32 times for 8 full cycles of PWM give us, for a 16MHz chip, an period and amplitude of 238.
This means that having a prescaler of 8 (CS01), a period (OCR0A) AND a max potential duty cycle (ICR1) of 238, and going through 32 iterations of the sound sought for, I got the sound that I wanted and none of the wave groove that comes with a pulse duty cycle cut short.
Sure, it means less granularity when it comes to a Bb with a max duty cycle of 133, however it worked for me.


text:
Chips & High voltage: Connected in Series?
I have 3 micro-controllers that will be connected to a battery, and I need to provide each of them between 3 and 5 volts maximum.
I have 3V batteries but they do not seem to provide enough power, while putting to of them in series would fry the chips as it busts the 6 volts max.
My question is, if I provide 9 volts to 3 chips connected in series, would current drop be distributed evenly to 3V across all chips, or would for example fry the first one?

simulate this circuit – Schematic created using CircuitLab

If you connect micro-controllers in series like that, it's unlikely you'll fry them, but they won't work reliably. They need a constant voltage to operate correctly, and if you put them in series, the load on one will change the voltage on the others.

Additionally, if one chip doesn't work with 3V, 3 chips won't work with 9V. You'll probably need slightly more than 3V per chip.

So your batteries are the right voltage, but they don't provide enough current? How about putting multiple batteries in parallel? That would keep the same voltage, but would raise the maximum current

would current drop be distributed evenly ... you have a misunderstanding ... there is no such thing as current drop ... it is voltage drop that would be distributed ... the current would be the same through each of the chips ... the voltage drop would be evenly distributed only if the chips were completely identical and they executed the same program in sync ... so no, in real life, the voltage would not be distributed evenly

If  you put three resistors of the same value in series, then you would get equal voltage division between them.
But chips are not like resistors. Their current usage is not constant and typically vary by orders of magnitude even within each clock cycle. See why this would be a problem?
If you have good 3V batteries that supply 3V up to the maximum current that the chips can draw, and the chips are rated to run reliably at 3V then there is another problem. Maybe you need decoupling capacitors across the chips?

Thank you! What would the decoupling capacitors do specifically?

Does one chip work at 3V?

Chips can use different amounts of current at different times, and that amount can change abruptly.sometimes the power source can not supply these bumps fast enough, so the caps help smooth it out.

Does one chip work at 3V? - depends on the chip! What chip are you using?


text:
How to specify a timer's name depending on the chip it will be compiled to?
I need to enable a timer interrupt for a chip, and in the mean time, I am testing the code on Arduino Nano rather than (feed the chip, test the chip)++.
So as part of the code I have to TIMSK0 |= (1 << OCIE0A); which works great on the Arduino Nano, but has to be changed to TIMSK (without the 0) for the ATtiny45.
I was planning to go for something along the line of
#define NANO//Put // in front for the AtTiny45
#ifdef NANO
  const char in  = A0;
  const char out = 3;
  const char pwr = 10;
  char *timer = &TIMSK0;
#else
  const char in  = 3;
  const char out = 0;
  const char pwr = 1;
  char *timer = &TIMSK;
#endif
//...
*timer  |= (1 << OCIE0A);

So here are my three questions:

Do #these commands take space on a chip?
Is a pointer the way to go for this kind of things?
Am, am I doing it right?

Just as a complement to Delta_G's answer:

The names TIMSK0, OCIE0A, etc. are already preprocessor macros
so, for consistency, it makes sense to define your own preprocessor
macros for them. I tend to be lazy and use one of the already defined
names, like
#ifdef TIMSK0  // support both ATtiny{25,45,85} and ATmega328P
# define TIMSK TIMSK0
#endif

A const pointer for &TIMSK0 is fine though.

The macros identifying the MCU are defined to the value 1. Thus you
have the choice between these three idioms:
#ifdef __AVR_ATtiny45__
...
#endif

#if defined(__AVR_ATtiny45__)
...
#endif

#if __AVR_ATtiny45__
...
#endif

The third one is convenient when you want to address several MCU
models with the same code:
#if __AVR_ATtiny25__ || __AVR_ATtiny45__ || __AVR_ATtiny85__
...
#endif


text:
Arduino to AtTiny change of pin interrupt behaviour?
I have a project which, to save on battery, is put to sleep until an interrupt pin is rising from LOW to HIGH.
This works well on Arduino Nano, however the translation doesn't on the ATTiny.
#include <avr/sleep.h>
void setup(){
    pinMode(2,INPUT);
    noInterrupts();
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    attachInterrupt(INT0,wakeUp,RISING);
    //Yadada
    Interrupts();
}
void wakeUp(){
   //Something Something
   sleep_mode();
}

Both on the Arduino Nano and the AtTiny, the interrupt Pin 0 is equivalent to Pin 2.

The Arduino is set to ISP
I have run the Bootloader (with internal clock as 8MHz if that makes a difference)
The program loads on the AtTiny45.

Yet, the interrupt pin does not interrupt.
Does the INT0 act differently on a ATTiny than on the Arduino, and if so, how can I wake up my AtTiny?

attachInterrupt(digitalPinToInterrupt(pin), ...

The INT0 value is 0 for Atmega328 and it's 6 for the Attiny45... It was working just by accident on the other Arduino. It's not even supposed to be used with attachInterrupt (it's used by attachInterrupt to setup registers correctly)

Aaaaah so that's why it's not recommended. I will give it a try and come back with corrections! Thank you both!

@Juraj, For some reason my version of Arduino IDE does not recognize the digitalPinToInterrupt? Looks like a usual thing so will see how else I can do this. Currently diving in the GIMSK etc. :S

it is possible that the Arduino core in this boards support package doesn't have the function

After going through a lot of documentation, it seemed best and more efficient to attach the interrupt without functions.
EIMSK  |=  (1<< INT0);//Attaches the interrupt
MCUCR  |=  (1<< SM1)  //Power-down mode
         | (1<<ISC01) //The rising edge of INT0
         | (1<<ISC00);// generates an interrupt request

I think it's great that you came back and answered your own question.  But, this answer seems weirdly mismatched with the question "Does the INT0 act differently on a ATTiny than on the Arduino, and if so, how can I wake up my AtTiny?"


text:
Bootload from a Nano to an ATMega328 without a crystal
I have a program to load from a Aduino Nano as ISP to a ATMega328p chip that will have an internal clock at 16M, but I don't have a crystal handy.
Is there a way I can not have to buy a crystal? What should be the circuit's look like?
Here's how I have it hooked:

Ground to Ground (Pin 8)
5V to VCC (Pin 7)
D10 to Reset (Pin 1)
D11 to MOSI (Pin 17)
D12 to MISO (Pin 18)
D13 to AVCC (Pin 20) (There are no resistors or capacitors, that all was part of a tutorial I cannot find anymore)

So I'm testing now with the basic Blink sketch and here is the resulting terminal comments.
/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/b77/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/b77/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/b77/Documents/Arduino/libraries -fqbn=megax8:avr:atmegax8:cpu=328_16 -vid-pid=0403_6001 -ide-version=10816 -build-path /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627 -warnings=none -build-cache /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_cache_67558 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avrdude.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -verbose /Applications/Arduino.app/Contents/Java/examples/01.Basics/Blink/Blink.ino
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/b77/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/b77/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/b77/Documents/Arduino/libraries -fqbn=megax8:avr:atmegax8:cpu=328_16 -vid-pid=0403_6001 -ide-version=10816 -build-path /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627 -warnings=none -build-cache /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_cache_67558 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avrdude.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -verbose /Applications/Arduino.app/Contents/Java/examples/01.Basics/Blink/Blink.ino
Using board 'atmegax8' from platform in folder: /Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3
Using core 'megax8' from platform in folder: /Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3
Detecting libraries used...
/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10816 -DARDUINO_ATmegaxX8 -DARDUINO_ARCH_AVR -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/cores/megax8 -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/variants/megax8 /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp -o /dev/null
Generating function prototypes...
/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10816 -DARDUINO_ATmegaxX8 -DARDUINO_ARCH_AVR -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/cores/megax8 -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/variants/megax8 /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp -o /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/preproc/ctags_target_for_gcc_minus_e.cpp
/Applications/Arduino.app/Contents/Java/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/preproc/ctags_target_for_gcc_minus_e.cpp
Compiling sketch...
/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10816 -DARDUINO_ATmegaxX8 -DARDUINO_ARCH_AVR -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/cores/megax8 -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/variants/megax8 /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp -o /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp.o
Compiling libraries...
Compiling core...
Using precompiled core: /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_cache_67558/core/core_megax8_avr_atmegax8_cpu_328_16_27f180324ce8b44e5ad3e6dc83e4e5ee.a
Linking everything together...
/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-gcc -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.elf /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp.o /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/../arduino_cache_67558/core/core_megax8_avr_atmegax8_cpu_328_16_27f180324ce8b44e5ad3e6dc83e4e5ee.a -L/var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627 -lm
/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.elf /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.eep
/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-objcopy -O ihex -R .eeprom /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.elf /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.hex
/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-size -A /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.elf
Sketch uses 924 bytes (2%) of program storage space. Maximum is 32768 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -P/dev/cu.usbserial-AC012GAB -b19200 -Uflash:w:/var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf"
         User configuration file is "/Users/b77/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbserial-AC012GAB
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.04s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.04s

avrdude: Device signature = 0x000000 (retrying)

An error occurred while uploading the sketch
Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

From what I've seen online, the device signature being 0x000000 could potentially mean that the lack of crystal may make it impossible for me to do the bootloading. The chip is also brand new and I've tested with more than one as I have 3.
My thought is that I probably read the tutorial wrong especially with the AVCC pin?
In any case, how should I connect a Nano to an ATMega328p without a crystal?
Thanks for your help!

The internal oscilator is 8Mhz on the ATMega328P. You could use the 3.3V 8Mhz Arduino Pro Minis bootloader. But make sure you set the fuses correctly, so it's doesn't use the crystal as a clock source. The only downside is that the RC oscillator isn't as accurate as a crystal, so Serial/UART may not work correctly.

Alright. After reading some and some more, I was able to notice that SCK, just one pin down from AVCC, was the missing link.
Yet another reminder to properly read the fabulous manual.
It looks so easy now.


text:
Is there a variable type of half byte? Is there a workaround?
I have this long array of 64 values going from 0 to 15, values which only cost 8 bits, for a pulse width modulation.
So I made a test to see its cost in space, commenting one of the two arrays.
const byte wave[64] = {8,9,9,10,11,11,12,12,13,13,14,14,14,15,15,15,15,15,15,15,14,14,14,13,13,12,12,11,11,10,9,9,8,7,7,6,5,5,4,4,3,3,2,2,2,1,1,1,1,1,1,1,2,2,2,3,3,4,4,5,5,6,7,7};
//const byte wave[2] = {8,9};
byte i = 0;
void setup() {pinMode(1,OUTPUT);}
void loop() {            //(Don't worry about the code in here,
  analogWrite(1,wave[i]);//it's just to get the program
  i++;delay(1);          //to hold on to the data)
}

The compiler said Sketch uses 1112 and 1050 bytes (3%) of program storage space. or a difference of 62 bytes.
This tells me that one could save a lot of memory by keeping them in a 4-bit or what I'd like to call half byte, going from 0 to f rather than from 00 to ff.
How could I do so without turning the code to unreadable bit mush?

You can always use Nibbles. Just store on number in the first half of a byte and the other in the second half. to read it back, just shift and AND it with an appropriate mask.

I understand this can help, just wondering if the masking won't use also a lot of dynamic memory?

You could definitely stuff 64 of your 4-bit integers into a byte array with 32 slots, but if your plan is to specify the contents of that byte array as you have in your sample code, then it might not help much. If, on the other hand, you were reading your array of 4-bit integers from somewhere else (e.g., from flash memory or from a UART input) then you might be in luck. In declaring const byte wave[64] you've told your program to allocate 64 bytes and the ship has sailed.

If the compiler get's it right, it is just ONE additional instruction (AND) to read the right Nibble and TWO instructions (SWAP + AND) to read the left Nibble. So it takes 6 bytes more for your code, but on the other hand you save 32 bytes on your data.

That makes a lot of sense! So I should find a way to store these nibbles prior to having it in the program? Any way you can recommend?

Are you sure you don't have enough memory? How likely is it? Are you going to manufacture tens of thousands of it, or could you just buy a chip with more memory? Otherwise I'd say that's premature optimization.

I've actually came to something quite interesting by turning this array into a int variable. It's really long but with 64*4 bit it still fits! and I saved a whopping 186 bytes o_O

the data looks like a sine wave lookup table ... you only need to store a 1/4 wave

@jsotola True! But the actual data I'm working with is a bunch of multiple sine waves together hence the need for the full cycle.

I think you can use union which is part of C. The compiler will then do all the bit manipulations for you. But I not really that well versed in C. Maybe @Majenko can chime in.

Keeping your 4-bit values in half-bytes is doable using structs and bitfields. You'll want an access function to separate the "array index" into a byte-index and a nibble selector (the LSb of the "array index") and return or store the appropriate nibble.
This related question on StackOverflow has some answers showing ways to do this. There will be obviously be some overhead to unpacking 4-bit nibbles since they can't be addressed directly, but it will be minor and is the trade-off for saving memory when memory is scarce.

If the point is to save program storage space, you're probably going to have to live with some unreadable bit mush or do bit-swapping in your head. Here's a code example that encodes your same array as a 32-byte array, but you have to combine pairs of your original numbers into bytes. It's not especially difficult because each hex digit represents one of your original numbers.
I.e., 8,9 becomes 0x89. Likewise, A is 10, B is 11, etc. Then you can iterate 1 thru 64 and do some division and bit-shifting to pull out the original value you wanted. This will iterate through your 32-byte array and pull out 64 half-byte values.
    const byte wave[32] = {0x89,0x9A,0xBB,0xCC,0xDD,0xEE,0xEF,0xFF,0xFF,0xFF,0xEE,0xED,0xDC,0xCB,0xBA,0x99,0x87,0x76,0x55,0x44,0x33,0x22,0x21,0x11,0x11,0x11,0x22,0x23,0x34,0x45,0x56,0x77};
    for(int i=0; i<64; i++) {
        byte val;
        if (i % 2) {
            // the little byte is first (LITTLE ENDIAN)
            val = wave[i/2] & 0x0F;
        } else {
            // the BIG byte is second
            val = (wave[i/2] >> 4) & 0x0F;
        }
        Serial.printf("%i=%i\n", i, val);
    }

NOTE: that the Endianness if your system may be different than mine. Most systems are little-endian these days, but you never know.


text:
Any limitation on array size in Arduino Mega 2560?
I am writing an Arduino code with 3 arrays.
Two of those are double and other one is int. Further first two arrays have nearly 420 elements for each.
Now I noticed that with more that 89 elements on 3rd array the program stall, and stuck executing. But with 89 or less number of element it runs with out an issue.
What would be the issue?

That's hard to tell without seeing your code.

The limit is 32767 elements. Anything else is a problem with your code.

Also be sure to not be too close to the max memory. If there is not enough space left to put variables on the stack, the program will crash some way

Are these arrays declared by size at compile time? what does the IDE report as far as your memory use is concerted when it compiles the program. As stated before, kinda hard to help without seeing your code.

A Mega has 8 KB of memory.
You are using:

double (same as float on an Arduino, see double) , 4 bytes * 420 elements * 2 arrays = 3,360 bytes
int (2 bytes) * 89 = 178 bytes

In total this is 3,538 bytes
This is about 50%, so I'm unsure what the 'rest' is.
You can take a look at the other related question that may show some answers (like using dynamic memory, memory gaps, or local/stack variables): What are the traditional ways to optimize program memory usage?


text:
Using sim900a GSM module, sending data to xampp Database
I am using a soil moisture sensor, dht11, and a relay module. To send data to xampp (database) sever I used the sim900a GPRS module and wrote a PHP code as well. But it doesn't connect and pass data to the database.
what is the problem?
Ardunio code:
#include <SoftwareSerial.h>                           //GSM module Library
SoftwareSerial gprsSerial(7, 8);                      //GSm module pin configration
#include <String.h>                                   //Header file
#include <DHT.h>                                      //Moisture sensor library
#define DHTPIN A1                                     //Define humidity sensor as Analog pin 1
#define soilHumPIN A0                                 //Define Soil moisture sensor as Analog pin 0

DHT dht(DHTPIN, DHT11);                               //Specify the DHT sensor
int relayEnable = 4;                                  //Define the digital pin to which dc water pump is to be connected
int soilHum = 0;                                      //Integer to store soil moisture value.
int output_value ;                                    //Integer to store the output value of soil moiture sensor
int current_value;                                    //Integer to store current value of soil moisture sensor reading
int threshold = 320;                                  //set the threshold value = 320
const int analogOutPin = 8;                           //Set analog output pin to pin 1

void setup()
{
  gprsSerial.begin(9600);                             // the GPRS baud rate
  Serial.begin(9600);                                 // the baud rate
  pinMode(relayEnable, OUTPUT);                       //set relayEnable pin as OUPUT
  dht.begin();

  delay(1000);
}

void loop()
{
  float humid = dht.readHumidity();
  float t = dht.readTemperature();
  output_value = analogRead(soilHum);                 //read the value of soil moisture sensor and store it in output_value
  current_value = output_value;                       //set current_value equal to output_value
  output_value = constrain(output_value, 10, 1023);   //set the contrain on output_value. Minimum = 10 Maximum = 1023
  output_value = map(output_value, 10, 1023, 100, 0); //map the output_value
  analogWrite(analogOutPin, output_value);            //send the output_value to transmitter pin
  delay(100);

  Serial.print("Temperature = ");                     //Print Temperature
  Serial.print(t);                                    //Serial print
  Serial.println(" °C");                              //Print temperature in Celcius
  Serial.print("Humidity = ");                        //Print Humidity
  Serial.print(humid);                                    //Serial print
  Serial.println(" %");                               //Print Humidity as a precentage value
  Serial.print("Soil Moisture = ");                   //print Moisture=
  Serial.print(output_value);                         //print the output_value
  Serial.println("%");                                //print %

if(current_value >=threshold)                                        //check if current_value >= 800

   {
    //if yes then
    Serial.println("\nWater Level Low... Turning Solenoid on..");       //print water level low.. turning water pump on..
    digitalWrite(relayEnable,LOW);                                     //turn on the dc water pump

   }
   else
   {
    //if no then
    Serial.println("\nWater Level High... Turning Solenoid off");       //print water level high.. turning water pump off..
    digitalWrite(relayEnable,HIGH);                                      //turn off the dc water pump

   }
   delay(10000);                                                        //create a delay of 10 second

  if (gprsSerial.available())
    Serial.write(gprsSerial.read());

  gprsSerial.println("AT");                           //Checking the status
  delay(1000);

  gprsSerial.println("AT+CPIN?");                    //Pin code of the sim is accepted or not
  delay(1000);

  gprsSerial.println("AT+CREG?");                   //Gives information about access technology
  delay(1000);

  gprsSerial.println("AT+CGATT?");                 //Attach or deattach pacakge domain service
  delay(1000);

  gprsSerial.println("AT+CIPSHUT");               //GPRS tcp contact
  delay(1000);

  gprsSerial.println("AT+CIPSTATUS");             //Reteun the connection status
  delay(2000);

  gprsSerial.println("AT+CIPMUX=0");              //Device single or multi ip address
  delay(2000);

  ShowSerialData();

  gprsSerial.println("AT+CSTT=\" \"");   //start task and setting the APN, for dialog APN is blank
  delay(1000);

  ShowSerialData();

  gprsSerial.println("AT+CIICR");             //bring up wireless connection
  delay(3000);

  ShowSerialData();

  gprsSerial.println("AT+CIFSR");           //get local IP adress
  delay(2000);

  ShowSerialData();

  gprsSerial.println("AT+CIPSPRT=0");   //echo is prompt or not
  delay(3000);

  ShowSerialData();

  gprsSerial.println("AT+CIPSTART=\"TCP\",\"IP/fruitinfo/insertDB.php\",\"3306\"");//start up the connection
  delay(6000);

  ShowSerialData();

  gprsSerial.println("AT+CIPSEND");         //begin send data to remote server
  delay(4000);
  ShowSerialData();

  //Sending data to server
  String str = "GET fruitinfo/insertDB.php";
  Serial.println(str);
  gprsSerial.println(str);            //begin send data to remote server

  delay(4000);
  ShowSerialData();

  gprsSerial.println((char)26);               //sending
  delay(5000);                                //waitting for reply, important! the time is base on the condition of internet
  gprsSerial.println();

  ShowSerialData();

  gprsSerial.println("AT+CIPSHUT");           //close the connection
  delay(100);
  ShowSerialData();
}
void ShowSerialData()
{
  while (gprsSerial.available() != 0)
    Serial.write(gprsSerial.read());
  delay(5000);

}

PHP code insertDB:
<?php

    require 'database_connection.php';

    if ( !empty($_POST)) {
        // keep track post values
        $soil_moisture = $_POST['soil_moisture'];
        $solenoid = $_POST['solenoid'];
        $humid = $_POST['humid'];

        // insert data
        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "INSERT INTO fruit_details (soil_moisture,solenoid,humid) values(?, ?, ?)";
        $q = $pdo->prepare($sql);
        $q->execute(array($soil_moisture,$solenoid,$humid,));
        Database::disconnect();
        header("Location: user data.php");
    }
?>

database_connection php code
<?php
    class Database
    {
        private static $dbName = 'fruitdb' ;
        private static $dbHost = 'localhost' ;
        private static $dbUsername = 'root';
        private static $dbUserPassword = 'hesn2412tutoo2';

        private static $cont  = null;

        public function __construct() {
            die('Init function is not allowed');
        }

        public static function connect()
        {
           // One connection through whole application
           if ( null == self::$cont )
           {
            try
            {
              self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
            }
            catch(PDOException $e)
            {
              die($e->getMessage());
            }
           }
           return self::$cont;
        }

        public static function disconnect()
        {
            self::$cont = null;
        }
    }
?>

write a test sketch and test php script for testing the connection between the arduino and php server ... proceed with code for connecting to database only after connection to php server is established

@jsotola I have written a php code and modified arduino code using this command AT+HTTPPARA="URL","(http://axxxxxxxxxx.com/conn.php?&humid=87&temp=27.5&soil_moisture=76"r"). This will save in xampp database as  87, 27.5 and 76. To send another data I need to modifed above parameters manually. How to get the sensor values automatcally to post it in xampp database?


text:
SPI communications with an Yost Labs IMU
I am pairing an Arduino UNO with a Yost Labs 3-Space Sensor Nano, the user manual for said sensor can be found here and the user manual for the sensor family here (kinda confusing, Yost Lab's documentation contradicts itself IMO)
This is my code, pretty straight forward (although this is my first time working with SPI). I am 100% sure the wiring is correct, and I have attached a diagram of my wiring here. The logic voltage converter I am using is this
I believe that as per the user manual, this should successfully return 3 floats in 4 bytes each, corresponding to the filtered euler angles of pitch, yaw, and roll. However, all I am reading is bytes full of 0xFF (or 11111111 in binary) which I believe corresponds to null / no command.
Are there any visible errors in my code?
#include <SPI.h>

SPISettings settings(6000000, MSBFIRST, SPI_MODE0 ); //variable to hold SPI settings
//Set Slave Select, MOSI, MISO, CLK
const int CSN = 10;
const int SI = 11;
const int SO = 12;
const int CLK = 13;

// Needed to convert the bytes from SPI to float
union u_types {
   byte b[4];
   float fval;
} data[3];  // Create 3 unions, one for each euler angle

void setup() {
 //Set Pin Modes
 pinMode(CSN, OUTPUT);
 pinMode(SI, OUTPUT);
 pinMode(SO, INPUT);
 pinMode(CLK, OUTPUT);
 //Set Slave Select High to Start i.e disable chip
 digitalWrite(CSN, HIGH);
 //Initialize SPI
 SPI.begin();
 //pour a bowl of serial
 Serial.begin(9600);
}

//function to transfer commands through SPI
byte transferByte(byte byteToWrite) {

 byte Result = 0x00;
 digitalWrite(CSN,LOW);
 delay(1);
 Result = SPI.transfer(byteToWrite);
 delay(1);
 digitalWrite(CSN,HIGH);
 return Result;
}

//function to swap endian
void endianSwap(byte temp[4]) {
 byte myTemp = temp[0];
 temp[0] = temp[3];
 temp[3] = myTemp;
 myTemp = temp[1];
 temp[1] = temp[2];
 temp[2] = myTemp;
}

void loop() {
 SPI.beginTransaction(settings);

 // Clear the internal data buffer on the IMU
 byte result = transferByte(0x01);
     Serial.print("Cleared internal buffer. Result: "),Serial.println(result);

 // Send start of packet:
 result = transferByte(0xF6);
      Serial.print("Send start of packet. Result: "),Serial.println(result);

 // Send command (tared euler angles)
 result = transferByte(0x01);
      Serial.print("Send commmand 0x01. Result: "),Serial.println(result);

 // Get status of device:
 result = transferByte(0xFF);
      Serial.print("Status of device. Result: "),Serial.println(result);

 while (result != 0x01) {  // Repeat until device is Ready
   delay(1);
   result = transferByte(0xFF);
   Serial.print("Status of device. Result: "),Serial.println(result);
 }

 // Get the 12 bytes of return data from the device:
 for (int ii=0; ii<3; ii++) {
   for (int jj=0; jj<4; jj++) {
     data[ii].b[jj] =  transferByte(0xFF);
     delay(1);
   }
 }

 SPI.endTransaction();

 for( int mm=0; mm<3; mm++) {
   endianSwap(data[mm].b);
 }

 Serial.print("fval 1:"), Serial.println(data[0].fval);
 Serial.print("fval 2:"), Serial.println(data[1].fval);
 Serial.print("fval 3:"), Serial.println(data[2].fval);

 delay(3000);
}

Please don't post the same question twice https://arduino.stackexchange.com/questions/76891/spi-communications-with-an-imu. If you have additional information, edit your post to add the information.

You almost certainly shouldn't raise CSN after each byte, only after the entire packet.
Although the data sheet is not explicit the chip select is usually used to frame an entire command. As it is at the moment it keeps starting a new transaction.
I like the comment in the data sheet that "...the 3-Space Sensor will not work properly in outer space or on planets with no magnetic field".

I've tried moving the CSN raise around and no luck, where would you put it? Intuitively, I would do CSN low and the start of the void loop, and high right at the end.

It should go low before the first command byte of a packet and be raised after the last data is received. The data sheet is very difficult to understand, they mention sending 0x69 to read SPI data but no reference to that elsewhere. Have you tried using one of the other modes of data transfer - serial ASCII would be the easiest to debug.

just tried low before the first command byte and raised after the last data is received, did not work. have not tried ASCII (I also have 0 experience with that)


text:
NodeMCU ESP8266
I am doing a project and using NodeMCU ESP8266. My project includes sensors for UART, I2C and 4 interrupts. I need to read the data from these sensors and get these data via microUSB in real time. While reading about NodeMCU ESP8266 there are so many points that came across and have certain questions.

Do flash uses GPIO6-11 all the time? Can we use any of these pins for our purpose? What if someone needs an SPI communication, as these pins are locked by flash.
Can I use GPIO-0 (flash pin) for my purpose, as after flashing the MCU the pin will get free.
Do CP2102 uses GPIO 1 and GPIO 3? Can I use these pins for my purpose? (Given I need the data via USB, which I guess comes through CP2102)
Can I receive the sensor data from SoftUART bus and get that data to my computer via USB?

I am confused from the articles given over internet. I request if anyone knows how these work, please explain.
Thank you

Related to the first question: https://arduino.stackexchange.com/questions/76091/why-do-esp-boards-break-out-the-spi-flash-pins

#3+4: if you only send data to usb, you don't need RX for that, just TX.

Do flash uses GPIO6-11 all the time? Can we use any of these pins for our purpose? What if someone needs an SPI communication, as these pins are locked by flash.

It is Quad SPI. The CS pins for this SPI interface are controlled by low level code. So you can't use this pins as GPIO and they have limited use as SPI too. If the flash access is set to normal SPI, the two pins io 9 and io 10 used for quad mode can be used as GPIO.

Can I use GPIO-0 (flash pin) for my purpose, as after flashing the MCU the pin will get free.

You can use io 0 as GPIO. Only make sure it is HIGH at boot. The bootloader reads it at boot to determine if it should go to flashing mode. Other boot config pins are io 2, it must be HIGH at boot and io 15, which must be LOW at boot.

Do CP2102 uses GPIO 1 and GPIO 3? Can I use these pins for my purpose? (Given I need the data via USB, which I guess comes through CP2102)

Pins io 1 and io 3 are wired to the USB chip and used for Serial. They can be used as io pins, if you don't need Serial communication over them. Serial in esp8266 Arduino can be swapped to different set of pins for use with a serial device. For output printing you can use Serial1 which has only TX. To relay this output to USB bridge io 2 (Serial1 TX) to io 4 (Serial TX wired to USB).

Can I receive the sensor data from SoftUART bus and get that data to my computer via USB?

You can use SoftwareSerail or the trick mentioned above.
see NodeMCU pins


text:
Nodemcu v3 - Power supply via VU pin?
I want to control two hitec hs55 micro servos via a Nodemcu v3. These need at least 4.8 V power supply acc to data sheet.
Specs:
Hs-55 micro servo:
Voltage range: 4.8-6 V
Current Drain - no-load (4.8V): 150 mA
Pulse Amplitude: 3-5V
NodeMCU (v3):
From what I found it seems like it can "reliably supply 600 mA".
3.3V pins (standard)
5 V (pin VU), Directly connected from the USB (?)
From what I understand it is generally a good idea to supply power to servos separately, otherwise the board can be damaged. Is this also the case here or would it be OK to connect the supplies to the servos from the VU pin? I'm thinking that there is a possibility it could be ok since it is directly connected to the USB.
For the signals I will use the normal GPIO pins.
Thank you in advance :-)

I'm not sure about the nodeMCU, but most AVR-based Arduino boards won't draw more than 500 mA from the USB port.

Supplying the servo from the USB is generally okay, but if it works or not depends on the USB host you use.
The data you mention is not relevant, though:

150mA are valid under no load, when there is a load the servo will sink more current
600mA probably refers to the onboard linear regulator which provides the 3.3V for the ESP. Depending on what the ESP has to do, it may require those 600mA on itsown and the connected circuit.

You can simply try what you suggested, it won't harm the nodeMCU. If it doesn't work the reason is probably the USB host not being able to provide the required current (a fast-charge usb wall charger should work).

Thank you, would you say it should be ok also to use this solution for a project where it will be installed for a longer period? If the USB is really connected directly to the VU port I guess this should also be ok. I can't find any electric diagram confirming this however. Yes I will try with that then! If I understand correctly a high max Ampere on the USB charger is OK as the servo motors will only use as much current as they need. One more question, what is the difference between the standard 3.3 V supply and this VU-supply that makes the 3.3 V to be bad for using as a supply?

The circuit diagram of a NodeMCU shows that there's a schottky diode between Vusb (the voltage input supplied by USB) and the Vin pin. This has the effect of reducing the approximate 5V voltage supplied by your typical USB jack/outlet/cable to something slightly lower. In my case, the apple USB charger adapter provides 5.1V but this gets reduced to 4.76V on the Vin pin. This Vin voltage is also quite noisy. I don't know if that will affect your servos. I've run one NodeMCU from the Vin pin of another NodeMCU pin without any trouble.
The schottky diode in the NodeMCU is a 1n5819/SS14/S4(SOD_323). I'm not certain, but if this is the correct datasheet, it says it can supply 1 amp, which sounds like enough. If I were you, I'd try and see if I could get power directly from the USB source rather than taking it off the NodeMCU pin. It might work off the pin, though. Try and make sure you get a USB that supplies at least 5.1V, though. It's going to be close.
EDIT: I would also add that the NodeMCU will be drawing power, too. If you are drawing 300mA with your servos and 100-150mA with your nodeMCU, that's cutting it pretty close for most USB power sources. A Macbook, for example, can only supply 500mA via a USB port. This article says a NodeMCU can consume up to 400mA under some circumstances.
Generally speaking, I've been told that it's a bad idea to use GPIO pins to drive anything that draws a significant amount of power. I'm thinking you should maybe consider using some kind of servo driver or relay or something.

"I've been told that it's a bad idea to use GPIO pins to drive anything that draws a significant amount of power."  This is imperative. Most Arduino boards have a recommended limit of 20 mA of sourced or sunk current on any GPIO line, and a peak limit of 40 mA. If you execeed 40 mA you will likely destroy either that GPIO pin or the entire board. You CANNOT power a servo directly from a GPIO line.

Thank you for the answer with much good and detailed information! However my nodemcu is the v3 (lolin) which has a VU pin (reserved in v2) that I want to power the servos with - not the VIN. This is a pin which I believe is directly connected to the microUSB voltage in, and thus should be possible to send enough Ampere through, also without loosing so much voltage. I have however not been able to find a electric diagram for this v3...

@Jmalecki as I mentioned in my post, trying to draw 300mA for servos plus the current for the MCU is probably asking a lot of many USB outputs. Those adapters that come with an iPhone these days can supply an amp, but a lot of USB ports on computers would max out at 500mA.


text:
How to use an Arduino Speaker module with DFPlayer Mini?
I've bought an Arduino speaker module. How should I connect the module, if I want to use it with DFPlayer Mini? The problem is that the speaker module has 3 pins: GND, VCC, and IN; though the DFPlayer Mini has 2 pins for connecting a speaker: SPEAKER + and SPEAKER -.

The DFPlayer already has an amplifier on it, so you can connect the speaker directly.
You can just leave out the board you bought from AliExpress, and only use the speaker.

Can I use the board with the DFPlayer? The DFPlayer has no filtering condensers, I'd like to use the ones bundled with the Speaker Module.

In that case you can use the DAC_R or DAC_L output of the DFPlayer, and connect that to the IN pin of your speaker amplifier board.

so I need to connect the board's GND to the player's GND, the board's VCC with the player's VCC, and the board`s IN with the player's DAC_R?

Yes. Though I'm still a bit puzzle why you'd want to go that route.

Gerben, do I need to run the startDAC command in my sketch?

I don't know. I don't think you have to change anything.


text:
Computer freezes while collecting serial data from Arduino Uno
I am an arduino noob. I have been searching for some interesting arduino projects recently and making a game controller using Arduino UNO seemed interesting. So I hooked up two dual-axis joystick modules to the arduino board and wrote a program to print something corresponding to the joystic movements. I collected the serial data through USB and passed it on to a python program. The code works fine, mostly. But the problem is, when I hook up the circuit and start using the joysticks, after few minutes my system  is freezing.
Why is my system freezing?
What can I do to avoid the freezing?
My system info:
1.Windows 10 64-bit
2.4GB RAM and 512GB HDD
Here is the code
int SW = 9;    // mouse joystick
int xpin = A0;
int ypin = A1;
int SW1 = 6;  //movement joystick
int xpin1 = A2;
int ypin1 = A3;
void setup()
{
  Serial.begin(9600);
  pinMode(SW, INPUT);
  digitalWrite(SW, HIGH);
  pinMode(SW1, INPUT);
  digitalWrite(SW1,HIGH);

}
int prev_state = 0; // previous state of switch
void loop() {
  int z = 0, xpos = 0, ypos = 0;
  int z1 = 0;char xpos1='0', ypos1='0';
  int x = analogRead(xpin);
  int x1 = analogRead(xpin1);
  int y = analogRead(ypin);
  int y1 = analogRead(ypin1);
  int sensitivity = 15; //mouse sensitivity

  if (x >= 550)                  // when moved up
    xpos = map(x, 550, 1023, 0, sensitivity);
  if (x <= 450)                // when moved down
    xpos = map(x, 450, 0, 0, -sensitivity);
  if (y >= 550)                 // when moved right
    ypos = map(y, 550, 1023, 0, sensitivity);
  if (y <= 450)               // when moved left
    ypos = map(y, 450, 0, 0, -sensitivity);
  int curr_state = digitalRead(SW);
  if (curr_state == 1 && prev_state == 0) // when SW is pressed
    z = 1;
  else
    z = 0;
  int prev_state1 = 0;
  if (x1 >= 550)                  // when pressed d
    xpos1 ='d';
  if (x1 <= 450)                // when pressed a
    xpos1 ='a';
  if (y1 >= 550)                 // when pressed w
    ypos1 ='w';
  if (y1 <= 450)               // when pressed s
    ypos1 ='s';
  int curr_state1 = digitalRead(SW1);
  if (curr_state1 == 1 && prev_state1 == 0) // when SW1 is pressed
    z1 = 1;
  else
    z1 = 0;
  if (xpos != 0 or ypos != 0 or z == 1 or xpos1=='d' or xpos1=='a' or ypos1=='w' or ypos1=='s' or z1 == 1) // prints when the joysticks are moved
  {
    Serial.print(xpos);
    Serial.print(":");
    Serial.print(ypos);
    Serial.print(":");
    Serial.print(z);
    Serial.print(":");
    Serial.print(xpos1);    // prints the data and separating by ":"
    Serial.print(":");
    Serial.print(ypos1);
    Serial.print(":");
    Serial.println(z1);
  }

  prev_state = curr_state;
  prev_state1 = curr_state1;
   delay(10);
}

I am using a python program, in visual studio code, to read the arduino serial data and perform the required operation.
The python code
import mouse, sys
import time
import serial
import keyboard as kb

mouse.FAILSAFE=False
ArduinoSerial=serial.Serial('com3',9600)  #assigning com port
time.sleep(1)

while 1:
      data=str(ArduinoSerial.readline().decode('ascii'))   #read the data
      (x,y,z,x1,y1,z1)=data.split(":")           # assigns to x,y,z,x1,y1,z1
      (X,Y)=mouse.get_position()        #read the current position of mouse cursor
      (x,y)=(int(x),int(y))
      mouse.move(X+x,Y-y)           # move camera/mouse
      # press the desired keys corresponding to joystick movement
      if y1=='w':
         kb.press('w')
         kb.release('w')
      if y1=='s':
         kb.press('s')
         kb.release('s')
      if x1=='a':
         kb.press('a')
         kb.release('a')
      if x1=='d':
         kb.press('d')
         kb.release('d')
      if '1' in z:                        # read the Status of SW
         mouse.click(button="left")    # clicks left button
      if '1' in z1:                    #read SW1
         kb.press('space')             # press space

To be clear, your system is freezing to the point where you need to power cycle the PC?

Even though the communication only runs at 9600, I suspect that's just to many keyboard presses you're generating here. If, for instance, you move left, it will generate around 9000 presses of the "a" button. No human would ever be able to do that.


text:
Arduino.Mk together with MightyCore
There's no end to my frustration trying to figure out how the arduino build system works -- despite my best efforts I just can't seem to grok it. Anyhow, I did this:
ALTERNATE_CORE_PATH=/path/to/MightyCore/avr
BOARD_TAG=324
...

make show_boards shows me several boards available, including 324. Yet whenever I try to build my project, I get this error:
avr-g++: error: missing device or architecture after ‘-mmcu=’

Can someone point me in the right direction?
Thanks.

what is after -mmcu=?

doesn't look like you use Arduino IDE or arduino-cli

I used Arduino.mk. I think I have managed to sort it out, just took a few extra Makefile options:
BOARD_TAG=324
MCU=atmega324a
VARIANT=standard

Resolved with the following Makefile options:
BOARD_TAG=324
MCU=atmega324a
VARIANT=standard


text:
Arduino Create and Raspi I2C
I'm trying to communicate via I2C on the Raspi, programming it with the Arduino Create Web Editor.  I have enabled I2C on the pi, made sure /dev/i2c-1 exists.  The pi can see the device (just a simple LCD for now) via the command line on the pi itself.
I'm getting the error "no I2C device available for Wire10".  I'm wired to SDA1/SCL1 (pins 3 and 5).  I have previously tested the display and the code on an UNO and it works fine.
Please help!  I saw someone had this issue before and simply said "I fixed it" but didn't provide an explanation.
Thanks!  (Code below for reference)
/* I2C LCD with Arduino example code. More info: https://www.makerguides.com */

// Include the libraries:
// LiquidCrystal_I2C.h: https://github.com/johnrickman/LiquidCrystal_I2C
#include <Wire.h> // Library for I2C communication
#include <LiquidCrystal_I2C.h> // Library for LCD

// Wiring: SDA pin is connected to A4 and SCL pin to A5.
// Connect to LCD via I2C, default address 0x27 (A0-A2 not jumpered)
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,16,2) for 16x2 LCD.

void setup() {
  // Initiate the LCD:
  lcd.init();
  lcd.backlight();
}

void loop() {
  // Print 'Hello World!' on the first line of the LCD:
  lcd.setCursor(0, 0); // Set the cursor on the first column and first row.
  lcd.print("Hello Worlds!"); // Print the string "Hello World!"
  lcd.setCursor(2, 1); //Set the cursor on the third column and the second row (counting starts at 0!).
  lcd.print("LCD tutorial");
}

There is some missing information. When you say: "I'm getting error" no I2C device... Where error is displayed? On RPi, Arduino IDE or what? What are conditions? What is connected and when? Uno? Display? What display? What is running on RPi? Another: When you saw someone having similar problem: provide a link, maybe someone can elaborate from there.

Here is the link o the original topic with the error: https://forum.arduino.cc/index.php?topic=560075.0, the error was on the arduino web IDE monitor, its an LCD display (Not sure of the exact model I will provide it when im able to get it) connected to the PI over i2c (gpio 2 and 3 from https://pinout.xyz/) That code posted is whats running on the pi.

did you run the I2C scanner sketch?

Yes i did and was not able to see anything with it. (Link to LCD: https://www.amazon.ca/WayinTop-Display-Interface-Adapter-Arduino/dp/B07TXGD3WS/ref=asc_df_B07TXGD3WS/?tag=googlemobshop-20&linkCode=df0&hvadid=341851109660&hvpos=&hvnetw=g&hvrand=11539534944715973135&hvpone=&hvptwo=&hvqmt=&hvdev=m&hvdvcmdl=&hvlocint=&hvlocphy=1002441&hvtargid=pla-910497129813&psc=1"


text:
Custom PS4 joystick with arduino
I am acquiring a Logitech G29 for my PS4 and I want to have an external handbreak. The handbrake only needs an input when active, so no "pressure level" or something like that required, only "on" or "off".
I have come around a few answers such as this, but I am not sure how to make it work on PS4 (and even if it needs some changes what so ever).
I don't have enough knowlegde to ask the correct questions, so I am asking for directions on basically how to send an arduino signal so the PS4 interprets as a joystick command (which in game I will configure as the handbrake option).
I am somewhat aware about the necessity of a custom library, but nothing more than that, not even what that really means to be honest.
The drawing bellow is somewhat the scheme for my project. And it is based on what I understood from this post.

Thank you for your time!

Do right as the reddit post says: Buy an Arduino with native USB capability (Leonardo or Micro for example). Then read the input from the handbreak switch. Then send keystrokes with the Keyboard library to the computer. Would that answer your question? If not, where exactly lies the problem?

Thanks for the reply. It's a good start. I have access to an Arduino UNO, so I will check about this USB capability. About the Keyboard library, you said "send keystrokes ... to the computer"... I actually need to send it to my PS4, is the approach the same? Does the library change? Again, thanks for the repply

The Uno has no native USB capability. You need a different Arduino. And computer and PS4 are equivalent here. The PS4 seems to support normal USB keyboards, just like a computer. When using the keyboard library, the Arduinos USB interfaces behaves like a normal USB keyboard. Thats exactly the way, that the reddit post took.

Thanls for the directions, I think I'll be able to continue from here. If I may ask one last thing, since I currently only have UNO, any way to implement the USB componet? I am not sure it even is a component, i'm really new to this - or any other way around to use the UNO?

The ability of using the Arduino as a Keyboard/Mouse depends on the Chip. For example, the Arduino Leonardo has a AtMega32U4, which has the ability but the Arduino UNO has a AtMega328P that isn't able to wok as a USB input device.


text:
How to identify pinout of ATmega 2560 derivative board?
My 3d printer, Creality Ender 4, has an ATmega 2560 chip based card, and I need to identify the number associated with a particular Pin.
I read, on the official Arduino website, a simple tutorial in which through a small led connected to two pins of the card, you wrote a code (sketch) that made it turn on, but you had to know the Pin number.
I would like to do this on my board, I unplug all cables (power supply, motors, etc.) and connect it to the PC via USB and from Arduino IDE, I execute the code, connecting the LED on the ground and on the signal (see image).
To identify the Pin number I thought I would go to exclusion, because I know all the PIN numers of the chip, until the LED lights up.
So I ask, is that correct? is there a chance of damaging the card? or is there a better method?
Thanks in advance

not correct because the microcontoller pins are not directly connected to peripheral plugs on the board ... yes, the board could be damaged ... it is better to obtain a schematic diagram or at least a table of pin functions

The 3dpinter/board manufacturer don't want give me the schematics, or just the number I need. On the internet there is very little info about the board...

I'd suggest using a multimeter in continuity mode, on the unpowered board. Then check which MCU pin is connected to the pin you're looking at.

Disconnect everything but the switch.
Run this:
for each pin,
  set the pin to INPUT_PULLUP mode;
  do,
    read and print the pin number and pin state;
  until operator touches a key;
  read and discard the serial input;
end;

You do:

Each time a new pin number prints on the terminal,
toggle the switch a few times to confirm whether you are seeing the result of your actions.
If not, touch the spacebar to try the next pin #
else, you found it.


text:
How to make a pairing and mode button on a remote control receiver
I'm working on a remote control project and have come across many different RF receiver/transmitter modules. Many have a pairing/mode button on the receiver that serves to pair the receiver and transmitter and to choose which mode the transmitter is in, momentary, latching, toggle, etc.

How can I replicate this feature using Arduino and those cheap RF transmitter/receiver combos on Ebay? Specific code would be nice, but just a general idea as to how it would be done in theory will work too. I've watched several tutorials that explain the use of the Radiohead library with the cheap RF combos, but none demonstrate how to set up a feature such as this. Thanks.

Remote sends a number before the command bits. The receiver checks if this number is the same with the number that corresponds with the position of the switches.
You can do the same in software. Have the first few bits be some number. The receiver can then check if the first few bits of the received "message" matches that number. If it doesn't it will just throw it out.
This is the same method used with IR-remote controls. The signal from your VCR remote will also be received by your TV. But the TV sees that the code doesn't match the one it's expecting. So it will ignore those.


text:
How to transmit DTMF signal to Arduino
I'm trying to read an incoming DTMF signal through the A0 input pin. I want to do this programmatically and not with the MT8870 module. This library (https://github.com/Adrianotiger/phoneDTMF) is supposed to do just that but I can't figure out how to connect my incoming DTMF signal to Arduino's A0 pin to receive the signal. Basically, my laptop produces the DTMF signal and I want to attach the line out, which is two wires, the positive and ground, to Arduino.  None of the configurations I've tried work.  I've tried to attach the positive to A0 and the ground to ground, but A0 doesn't seem to be detecting anything.  I also don't want to use a microphone on the A0 pin to detect the DTMF. A simple Fritzing type diagram showing how to connect the incoming DTMF signal to A0 would be helpful. Thanks.

Not an expert on DTMF, but have you made sure to get the signal range into the 0 to 5V range of the Arduino? Line Out is symmetrical around ground and I think the peak to peak range might also be wrong. The linked library also has a circuit for adjusting the range, though it is designed for the landline voltage levels

I was thinking of trying to connect an LM386 amplifier to boost the incoming signal, but I still don't know how to configure the two wires to Arduino.

Your problem is that you think there's a "positive" signal. In audio there isn't a "positive" signal, there is just a signal that swings around 0V.
You have to convert said signal to a "positive" signal by adding a DC offset to it.
The simplest way is with one capacitor and two resistors:

simulate this circuit – Schematic created using CircuitLab
That schematic will remove any DC offset that your laptop may add ("AC couple") and then add a 2.5V DC offset of your own to the signal.  The audio signal will then be alternating around 2.5V.
You may need to boost the audio signal's volume with an op-amp (note: do not use a "power" amplifier like the LM386, it is not suitable; use an op-amp) to increase the sensitivity of the input.  You could do this with a simple inverting amplifier arrangement with the DC offset being injected into the non-inverting input:

simulate this circuit
Here the gain of the amplifier is the ratio between R3 and R4 - in this case a 10:22 ratio (or a 2.2x gain).
From a software point of view you now remove 512 from each analog read value to give you a range of +/-511 for your sampled values. You then probably (maybe with the library you link to) take a block of samples at a defined frequency and perform an FFT analysis to find what dominant frequency components are present.

I set up the first schematic, and was able to detect the DTFM tones.  Thanks! The only problem, though, is that the program seems to be detect the wrong tone.  Using the tone generator here, https://onlinetonegenerator.com/dtmf.html, whatever button I push, the program detects the button down one row and to the right one column. Eg. I push 1 and 5 is detected. Or I push 5 and 9 is detected. I will post a question about this because it seems to be a software problem.


text:
How to use HM-10 as client, and send messages to specific services/characteristics?
I have been messing around with this module, unfortunately i bought a fake one, but got the original firmware running inside it (V550).
So far i can set the HM-10 up as client/master and by using an peripheral emulator on Android, i set up a peripheral as my server/slave
The peripheral is able to write to its own characteristic and it sends a notification to the client HM10 that fetches this value and displays it correctly on my serial reader (cutecom and arduino serial monitor)
After this, i'd like to write to the peripheral's characteristic, but i can't find any information about this, but it should be in the realm of possibility, i think.
I am using the Arduino IDE to interface with the HM-10 module.
Any information pointing in the right direction is very, very welcomed. Its driving me crazy now...

You can upgrade the firmware to V709 available on the manufacture's website and find instructions on how to update it. You'll need a USB to TTL converter or something that can act as one.
With firmware V709 you can use AT+FINDSERVICES? and AT+FINDALLCHARS? command to get the list of services and characteristics on the server and then read, write, notify, etc, on the characteristic you are interested in. It is outlined in the datasheet. They call it self learn function and there's a document outlining how to use it.