text:
How to Adjust MQ131 Sensor?
The problem
Hey. I'm trying to use the sensor Mq131 to measure some ozone data in a closed environment, but I'm having some bad time to adjust the trim in the sensor and get results in ppb. By searching on the internet I could not find any elucidative manual/instruction.

My Hardware set
As my first attempt, I've made the following wiring with the Arduino UNO and the sensor module.

Notice that my potentiometer does not have any indication of the resistance reached when spinning the potentiometer screw.

My software script
To get the value of tension in the output from the sensor I'm using the following approach.
int sensor_AOUT = A1; //connected from AOUT to the sensor to A1 on the Arduino
int sensor_DOUT = 2; //connect DOUT from sensor to Arduino pin 2
int wartosc_AOUT; //variable for the value of AOUT
int wartosc_DOUT; //variable for the value of DOUT

void setup() {
 Serial.begin(9600); //start the monitor serial port
 pinMode(2, INPUT); //set pin 2 as input

}

void loop() {

 wartosc_AOUT = analogRead(sensor_AOUT); //load values from AOUT
 wartosc_DOUT = digitalRead(sensor_DOUT); //load values DOUT

 Serial.print("D0: "); //display on serial monitor
 Serial.print(wartosc_DOUT);
 Serial.print(" -- A0: ");
 Serial.println(wartosc_AOUT);
 delay(200); //delay between consecutive readings
 }

which gives me values 30 < A0 <50. How can I get a value in ppb (parts per billion) and how can I calibrate the potentiometer screw?

Sensor Datasheet
The datasheet of this sensor can be found in this link.

what do you expect the potentiometer to do? ... you will need to have the datasheet to determine the ppb conversion ... another way to calibrate is to compare the output against an already calibrated sensor

@jsotola I've edited the question including the datasheet of the sensor. I would expect that the potentiometer enhances the sensibility of the sensor. I don't have any other calibrated sensor here, so I can not consider this option.


text:
Does toCharArray prevent a String being created on the heap?
I know it's bad to use Strings due to the memory problems that can occur.
I've tried to remove all instances of strings from my code.
But I'm not sure about this line:
http.getString().toCharArray(ipAddressBuffer, lengthOfIPAddress);

Is calling toCharArray() enough to prevent memory problems? Or is there a string still being created on the heap?
If it's still created on the heap, how can I modify the code so it only deals with cstrings?
Here's my code:
void setIPAddress(char* ipAddressBuffer){
  HTTPClient http;
  http.begin("http://bot.whatismyipaddress.com/"); //Only allowed to call once per 5 mins.
  http.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
  int httpCode = http.GET();
  if (httpCode > 0) {
    http.getString().toCharArray(ipAddressBuffer, lengthOfIPAddress);
  }
  else {
    Serial.println("Error on HTTP request");
  }
  http.end();
}

I'm using the HTTPClient.h library btw.

BTW: Which HTTPClient library? I know one which allows for HttpClient objects, not for HTTPClient

The return value of getString allocates and the deletes a char array in heap for a temporary String object.
For ESP8266HTTPClient and ESP32 HTTPClient library you can use writeToStream or getStream()to read the response without using String class with getString(), where stream is WiFiClient& stream = client.getStream();
getStream, returns the underlying WiFiClient. You can read the data with classic while (stream.available()) { char c = stream.read; ... }
writeToStream copies the data to a stream. My StreamLib library has a stream wrapper over a char array. It is called CStringBuilder.

One caveat to your answer: I read in the ArduinoJson documentation that if you do client.getStream() you bypass the chunked transfer encoding code and that for that case you must fall back to HTTP1.0 using useHTTP10(true). Did you encounter that, and is that something you could incorporate in your answer?

Or would writeToStream(Stream * stream), which getString() uses internally be a good idea?

@hansmbakker my StreamLib has ChunkedStreamReader. see the ReadChunkedJson example. StreamLib is in the Library Manager

http.getString() creates a temporary Arduino String object and fills text into dynamic memory on the heap. Calling the method .toCharArraycopies this text to a char array, wherever you defined it.
Immediately after that, the temporary String gets out of scope and the text on the heap is deleted again.

source: Stack Exchange

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

sort: votes


text:
NodeMCU ESP32 as a replacement for my arduino project
I would just like to ask if this microcontroller can power or can manage 2 servos, 2 motors, and 2 hc-sr04 ultrasonic distance sensor combined? Also, does this board come with a bluetooth module?

Thanks for the answer @StarCat but how would I do the "logic level translation"?

Easiest would be to use the little 4-channel bidirectional level converters. Sometimes a simple voltage divider made out of two resistors would be enough (5V output to 3.3V input) and some 5V peripherals are 3.3V tolerant.

thank you so much @StarCat

The ESP32 has more than enough free GPIOs to manage those peripherals. Also, the ESP32 does indeed come with a bluetooth module.
Your question about powering these peripherals very much depends on their power requirements. I would not count on being able to run motors or servos from the internal power supply of a NodeMCU board, so you would need an external supply.
Also, note that the ESP32 is a 3.3V device and might require logic level translation if you’re using 5V peripherals.

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


text:
Bike Gear Indicator Coding Problem
Lack of practice I forgot many function of C & C++...
Can anyone help me with this coding Please...
I think this is The Main coding:
Topic: Gear indicator
I first found this, Gear_Indicator_Raw
But, There was many problem in those sketch,

Those sketches work just like simple counter,
Can't Show "2" from "0"
No Neutral Detection,

As Bike Gear, (1 N 2 3 4 5) One Down Four up, I made some Changes,
But can't add the Neutral part smoothly...
And here, My code:
#define BUTTON_DOWN 13
#define BUTTON_UP 4
#define BUTTON_N 11

int ledPinA = 7;
int ledPinB = 12;
int ledPinC = 10;
int ledPinD = 9;
int ledPinE = 8;
int ledPinF = 6;
int ledPinG = 5;

int val_up = 0;
int val_down = 0;
int val_n = 0;
int old_val_n = 0;
int old_val_down = 0;
int old_val_up = 0;
int gear = 0;
// The setup() method runs once, when the sketch starts

void setup()
{
  pinMode(BUTTON_N, INPUT);
  pinMode(BUTTON_UP, INPUT);
  pinMode(BUTTON_DOWN, INPUT);

  pinMode(ledPinA, OUTPUT);
  pinMode(ledPinB, OUTPUT);
  pinMode(ledPinC, OUTPUT);
  pinMode(ledPinD, OUTPUT);
  pinMode(ledPinE, OUTPUT);
  pinMode(ledPinF, OUTPUT);
  pinMode(ledPinG, OUTPUT);
}

void led0()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, LOW);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, HIGH);
}
void led1()
{
  digitalWrite(ledPinA, HIGH);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, HIGH);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, HIGH);
}
void led2()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, HIGH);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, LOW);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, LOW);
}
void led3()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, LOW);
}
void led4()
{
  digitalWrite(ledPinA, HIGH);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, HIGH);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}
void led5()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, HIGH);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}
void led6()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, HIGH);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, LOW);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}
void led7()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, HIGH);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, HIGH);
}
void led8()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, LOW);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}
void led9()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}

void setLed(int number)
{
  switch (number)
  {
    case 0:
      led0();
      break;
    case 1:
      led1();
      break;
    case 2:
      led2();
      break;
    case 3:
      led3();
      break;
    case 4:
      led4();
      break;
    case 5:
      led5();
      break;
    case 6:
      led6();
      break;
    case 7:
      led7();
      break;
    case 8:
      led8();
      break;
    case 9:
      led9();
      break;
  }
}

// the loop() method runs over and over again,
// as long as the Arduino has power

void oldloop()
{
  led0();
  led1();
  led2();
  led3();
  led4();
  led5();
  led6();
  led7();
  led8();
  led9();
}

void loop()
{
//neutral

    val_n =  digitalRead(BUTTON_N);
    if ((val_n == HIGH) &&gear<=2)
    {
      gear = 0;                         //Posted wrong "gear = HIGH"
      delay(100);
    }

// Gear Up

    val_up = digitalRead(BUTTON_UP);
    if ((val_up == HIGH) && (old_val_up == LOW) &&(gear<6) && (gear>0))
    {
      gear += 1;
      delay(100);
    }

    else if ((val_up == HIGH) && (old_val_up == LOW) &&(gear==0))
    {
      gear += 2;
      delay(100);
    }
    old_val_up = val_up;

// Gear Down

    val_down = digitalRead(BUTTON_DOWN);
    if ((val_down == HIGH) && (old_val_down == LOW)&& (gear>1))
    {
      gear -= 1;
      delay(100);
    }

    else   if ((val_down == HIGH) && (old_val_down == LOW) && (gear==0))
    {
      gear += 1;
      delay(100);
    }
    old_val_down = val_down;

// Max Limit

    if (gear >= 5)
    {
      gear = 5;
    }

    setLed(gear);
}

The Problem:

Without the "// neutral" part it's work OK, but can't show "0" without reset.
With the "// neutral" part, While gear up, instead of increasing, display shows "0" after "1".
If I press pin "4" very quickly, then it's increasing to Max gear.

I think there is some problem in this part:
//neutral

    val_n =  digitalRead(BUTTON_N);
    if ((val_n == HIGH) &&gear<=2)
    {
     gear = HIGH;
      delay(100);
    }

And, Please, If anyone can tell me about "Void oldloop()", what this is for?

Likely problem
I'm not sure how to solve the problem, however, I see at least one item that looks strange in the //neutral part:
gear = HIGH;

This seems gear is a pin status (LOW/HIGH), but two lines above:
if ((val_n == HIGH) &&gear<=2)

Here gear is an integer value. This seems quite inconsequent to me.
Pin 4
The reason is you do not have a debouncing algorithm, check for a Debounce Arduino example. When a button is pressed or depressed, it switches sometimes very fast a few times; this might result in multiple increases/decreases of the gear.
oldLoop
The function oldLoop is not used, but if you swap the names of loop and oldLoop you can use the 'test' scenario which is contained in oldLoop.
Some other tips

Use spacing consequently
You can refactor the LED code a lot.
You can use gear++;  to increase or gear--; to decrease.

Update
(Changed debouncing problem for pin 4).
You changed in your neutral code:
gear = 0;

Shouldn't that be gear = 1;? As gear 1 means Neutral (gear 0 is 1).

Oops, sorry, I actually I used "gear=0", But maybe It's a mistake while I was editing it to post here..!!!

Thanks, I shorted the code, as you said, the oldloop is useless, gear++ & gear-- working smoothly... But the neutral function still interrupting with gear up...

Than change the last line from setLed(gear) to setLed(gear == 1 ? 0 : gear) ... at least that's the simplest solution for the code you have now.

No, That does not works for me... But I guess I worked it out with if ((val_up == HIGH) && (val_n == LOW) && (gear>0))... The "oldloop" was confusing me... Let me check couple of times...

All working very good, Also thanks about the debouncing part... It helps... But one last thing... How to ignore "hold" button... Holding the button/sensor little more It keeps increasing/decreasing to max limit... I want the output, only after releasing the button...

You can prevent holding a button when only triggering for a falling edge (i.e. depressing a button), or a rising edge (i.e. pressing a button)... the debounce algorithm will make sure you only have one edge.

kay, after hours I was testing the circuit...The problem raises again...!!! Also change the whole pin set up, then the gear-up running it's own... I think there is issue on pin sensitivity...!! (checked with other boards) Maybe I should use some pull-up resistors...Or use analog pins for Input,,,

No digital pins are ok, but you should indeed use pull-up or pull-down resistors in case the button is depressed.

Yes, I used 10k pull-down... It's working now... Let me check my final & actual project, so I can mark this as solved... :)

Thanks a lot...

Glad it's working!

Your problem is that you are confused about the meaning of gear.
One possible meaning could be 0 = neutral, 1 .. 5 = gear. But then, when changing gears you can't simply do + or -,  as the sequence is 1 - 0 - 2 - 3 - ...
The other interpretation is:  gear-- from 2  means neutral and you display something that indicates neutral ( e.g. a '0' or a '-' ) whenever gear==1, and you display a '1' when you do another gear--, and have a numeric value of 0 in gear.
Your decision.

Actually I was confused about the "oldloop" part, and the original code was very complicated... I kind of shorted it... I think for the 7-segment, it could be done more simple...

Easiest is to change your  switch (number) {   case 0: led1(); break;     case 1:  ledneutral(); break;

All I understand after lots of failing... That, the problem is with Arduino pins sensitivity...!!! -_-  There should be a full list of all common problems..!!!


text:
Output of mlx90614 to mcufriend tft/lcd, not getting displayed
Newbie here !! Im trying to display the output of my MLX90614 sensor on mcufriend tft display (with arduino UNO). But unable to do so. I can only see the TFT being lit to white color, text -> "Target" flashes on screen for millisecond and then again white lit screen.

But I tried tft-lcd sample codes, which are working fine &
I also tried mlx90614 (mlxtext code), which is also working fine.

But I combined the two codes so as to output it on TFT, which doesnt work. Hence I think this code might have some issue.
Im a beginner pls help!!
#include <Adafruit_TFTLCD.h>
#include <Adafruit_GFX.h>
#include <TouchScreen.h>
#include <Wire.h>
#include <Adafruit_MLX90614.h>

#define LCD_CS A3
#define LCD_CD A2
#define LCD_WR A1
#define LCD_RD A0
#define LCD_RESET A4

#define BLACK   0x0000
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
Adafruit_MLX90614 mlx = Adafruit_MLX90614();

boolean buttonEnabled = true;

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

  mlx.begin();
  tft.reset();
  uint16_t identifier = tft.readID();
  tft.begin(identifier);
  tft.setRotation(1);
  tft.fillScreen(WHITE);
  tft.drawRect(0,0,319,240,YELLOW);

}

void loop() {

  tft.setCursor(0,1);
  tft.setTextSize(2);
  tft.print("Target  ");
  tft.setTextColor(BLACK);
  tft.print(mlx.readObjectTempC());
  tft.print(" C");
  Serial.print("*C\tObject = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");
  Serial.println();
  delay(500);

}

look at #define LCD_CS A3 ... do you see it conflicting with another define? ... look for other conflicts

@jsotola, deleted all the unnecessary defines, still not working

start with working tft code ... add a couple lines of mlx code an test ... repeat until failure

The Adafruit library Adafruit_MLX90614 already includes the wire library in the .h file and the constructor calls wire.begin in the .cpp file. Please try removing the wire library you've included in your sketch. If that doesn't solve the problem, follow jsotola's suggestion and add 1 line of code at a time to the working example until it "breaks".


text:
Multiple Buttons to control the same led for different on off times
I am just learning the Arduino, it is a learning curve that's for sure.
Using the onboard Led I want to use two buttons to make the Led blink for different times.
I am not sure what is missing from the code, as pressing BUTTON2 gives the same time as BUTTON.
Any help would be greatly appreciated.
 const byte BUTTON = 2;
const byte BUTTON2 = 3;
const byte LED = 13;

unsigned long buttonPushedMillis;
unsigned long ledTurnedOnAt;
unsigned long turnOnDelay = 500;
unsigned long turnOffDelay = 500;
unsigned long turnOnDelay2 = 1000;
unsigned long turnOffDelay2 = 1000;
bool ledReady = false;
bool ledState = false;

void setup() {
  pinMode(BUTTON, INPUT_PULLUP);
  pinMode(BUTTON2, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop() {
  unsigned long currentMillis = millis();
  if (digitalRead(BUTTON) == LOW) {
    delay(50);
    buttonPushedMillis = currentMillis;
    ledReady = true;
  }
  if (ledReady) {
    if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay) {
      digitalWrite(LED, HIGH);
      ledState = true;
      ledTurnedOnAt = currentMillis;
      ledReady = false;
    }
  }
  if (ledState) {
    if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay) {
      ledState = false;
      digitalWrite(LED, LOW);
    }
  }
  {
    unsigned long currentMillis = millis();
    if (digitalRead(BUTTON2) == LOW) {
      delay(50);
      buttonPushedMillis = currentMillis;
      ledReady = true;
    }
    if (ledReady) {
      if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay2) {
        digitalWrite(LED, HIGH);
        ledState = true;
        ledTurnedOnAt = currentMillis;
        ledReady = false;
      }
    }
    if (ledState) {
      if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay2) {
        ledState = false;
        digitalWrite(LED, LOW);
      }
    }
  }
}

\\

Please format your code properly (indent it all 4 characters of start and end it with three back-ticks on a line of their own).

You're making your program too complex for its own good.
Instead of changing your blink code depending on which button is pressed, just make the button change the blink code's parameters, and stick to just one blink code.
That means having just one set of blink variables which your blink code uses, and your button code then just changes what values those variables contain.


text:
How to supply more than 500mA while powered by USB
I'm about to build myself a new BrewPi and I have some Arduino power/USB questions.
Something smiliar to a combination of these projects:
https://i.sstatic.net/gZHZt.jpg
https://www.homebrewtalk.com/threads/how-to-brewpi-lcd-add-on.510036/
The device will have a Raspberry Pi Zero W, an Arduino UNO (clone?), a LCD screen with backlight, and some relays and probes. The Pi must be connected to the Arduino via USB. The Arduino will drive the screen and some relays/probes. For simplicity's sake, I would like to power everything from the same regulated 5V power supply, and for ease of wiring I would prefer to power the Pi only and have it power the Arduino via USB, with the Arduino then supplying power to the rest.
My preference:
5V ----> Pi Zero --(USB)--> Arduino --(5V)--> Screen/etc.
However, according to this datasheet the max draw of the screen might exceed 1000mA:
https://www.vishay.com/docs/37314/lcd020n004l.pdf
This obviously exceeds the 500mA limit from the Arduino's 5V pin while being powered via USB. However, a Pi Zero has few safety features and does not limit outgoing current from it's USB port:
https://www.reddit.com/r/raspberry_pi/comments/3zyhuq/pi_zero_usb_power_outputmilliamps/
Given this, is it feasible to short/bypass the Arduino's polyfuse and then draw more than 500ma from the 5V pin of the Arduino without too many problems?
If not, can I 'add' the power supply's 5V to the Arduino's 5V (either from the Pi's 5V pin, or direct from the power supply) at the same time as maintaining the USB connection (which uses the same 5V source)? I'm stretching the limit of my circuit understanding here. If not how should I power the other components?
Would it instead be better to have a 12V supply and power the Arduino directly, then attempt to power everything else from its 5V pin (remembering that there is still a USB connection from the Pi back to the Arduino). What I'd really like to avoid in this situation is having to provide a second 12V->5V conversion.
Any help or advice would be greatly appreciated.

neither the RPi, nor the Arduino are meant to be used as a power supply ... using them as a power supply makes them act as an expensive fuse

just run everything off the 5v, don't use USB connectors.

@dandavis My concern with that option is I must also have the USB connected from the Pi, and I haven't managed to find a source that says that's going to be OK

When you power the Zero and the Uno with the same 5V power supply, the additional USB connection between them should be OK. But the power has to run outside of both boards.

Simply don't connect anything to the Uno's 5V pin, but feed it via USB. (That's how I understand @dandavis' comment) ?

I'm not sure where you got the 1000mA from. The LCD itself only has a max of 10mA. You might be talking about the ratings of the background LED with has a max of 1080mA. I very much doubt you can run the LED at that current. It would probably be very bright for a short while, and then die. That value is probably the max pulsed current (in short bursts).

If you power both your screen and RPi from the same 5V, just add an additional cable from the charger to the screen, that way you won't use the poor RPi as a fuse. In addition to that, if the current draw of the display is potentially high, peaks, then attach a 100-2000uF capacitor to the power pins, it helps to avoid any potential issues.

Do not bypass the fuse. Drive your external components directly from the external 5V power supply. Do not pass everything through the Arduino.
You say you have a regulated 5V power supply. Assuming it provides enough current you should use it to drive your external components directly.
You might need to add a filter capacitor near the feed for the Pi/Arduino, to filter out fluctuations in the 5V supply as your high current components switch on and off. You should be able to google "Power supply filter capacitor" to learn more.

Yeah, this.  They didn't put that fuse there just to stifle you while the thing is actually capable of more.  They put that fuse there so you don't burn up the boards you paid good money for.


text:
Connecting OV2640 with 17 Pins Binocular Camera module, to any microcontroller (System clock on module pin 18 -NC)
These pins are on the module:

3.3V
GND
VSYNC
SCL
SDA
HREF
D0-D7
DCLK
PWDN
I have tried many codes and connections of the OV7670 Monocular cameras, none seem to work(Instructables ,  Circuit Digest , Youtube).
The binocular cameras seem to be just daisy-chained using the I2C SCCB interface. I cant get any image reading on any of their codes provided. Some other guides mention programming the XCLK on board using SCCB PLL, but I'm not sure how to do it as I don't have much background in this domain.

Edit:-
1.Another resource
2.Wiki with datasheet and schematic (the module is a copy of this camera)

please add a link to the camera datasheet to your post ... do not put link into comments


text:
Arduino nano IoT antenna broke
I have an Arduino Nano 33 IoT and have used it for a good time now. I was using it when the antenna snapped off. Is there any way to fix it by either an external antenna or some other method? I tried to just hold the antenna in place as I tried to connect to wifi but it failed to connect.

Please show some good pictures of the damage. You can edit your question to include them

The problem that I see in the photo is that the pads from the PCB are pulled off and attached to the antenna. So now there is nothing to solder the antenna back to.
While it's possible to rework this with some solder rework tools, I suspect you don't have those.  There is really not much else you can do but replace the Nano with a new one.  You should still be able to use this one for an application that doesn't need WiFi.
It looks like the two active leads (the two in the upper right-hand side of the green module may be those) are still intact.  If you have a small tip soldering iron and a steady hand you may be able to put a tiny drop of solder on both of them and then resolder the antenna to them.  You could support the antenna with some silicone caulk or other non-conductive adhesive after you get it attached.
Keep in mind, that this is tricky to solder by hand but there is little to lose since that part of the module is not non-functional anyway.

So the 2 pads that got ripped off don't matter much other than support?

That's what it looks like but, as you now know, supporting the antenna is important!

Okay, I will try that.

It is still possible to get work. I see the copper pads have been pulled off so you need to use extra amount of solder and hopefully it attaches to the remained copper wire.
My case is even worse because the antenna is lost, so I have to remade one.

And it works.


text:
nRF24L01+ radio not transmitting anything but says it is
I have a nRF24L01+ radio that was working like a charm for many months now, and a few days back, I was trying to send something and then receive it. The transmitter initialized properly and said it was transmitting but the receiver got nothing. I made sure all wiring is good, power is sufficient, etc. I made sure the receiver was working with another radio and indeed. So what is wrong. Any help is appreciated.
The transmitter is a high range radio with large antenna and the receiver is the standard PCB antenna ones. When I do printDetails, everything looks fine.
TX Code:
/*
Demonstrates simple RX and TX operation.
Any of the Basic_RX examples can be used as a receiver.
Please read through 'NRFLite.h' for a description of all the methods available in the library.
Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND
*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 1;             // Our radio's id.
const static uint8_t DESTINATION_RADIO_ID = 0; // Id of the radio we will transmit to.
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket // Any packet up to 32 bytes can be sent.
{
    uint8_t FromRadioId;
    uint32_t OnTimeMillis;
    uint32_t FailedTxCount;
};

NRFLite _radio;
RadioPacket _radioData;

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

    // By default, 'init' configures the radio to use a 2MBPS bitrate on channel 100 (channels 0-125 are valid).
    // Both the RX and TX radios must have the same bitrate and channel to communicate with each other.
    // You can run the 'ChannelScanner' example to help select the best channel for your environment.
    // You can assign a different bitrate and channel as shown below.
    //   _radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN, NRFLite::BITRATE2MBPS, 100) // THE DEFAULT
    //   _radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN, NRFLite::BITRATE1MBPS, 75)
    //   _radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN, NRFLite::BITRATE250KBPS, 0)

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }

    _radioData.FromRadioId = RADIO_ID;
}

void loop()
{
    _radioData.OnTimeMillis = millis();

    Serial.print("Sending ");
    Serial.print(_radioData.OnTimeMillis);
    Serial.print(" ms");

    // By default, 'send' transmits data and waits for an acknowledgement.  If no acknowledgement is received,
    // it will try again up to 16 times.  This retry logic is built into the radio hardware itself, so it is very fast.
    // You can also perform a NO_ACK send that does not request an acknowledgement.  In this situation, the data packet
    // will only be transmitted a single time and there is no verification of delivery.  So NO_ACK sends are suited for
    // situations where performance is more important than reliability.
    //   _radio.send(DESTINATION_RADIO_ID, &_radioData, sizeof(_radioData), NRFLite::REQUIRE_ACK) // THE DEFAULT
    //   _radio.send(DESTINATION_RADIO_ID, &_radioData, sizeof(_radioData), NRFLite::NO_ACK)

    if (_radio.send(DESTINATION_RADIO_ID, &_radioData, sizeof(_radioData))) // Note how '&' must be placed in front of the variable name.
    {
        Serial.println("...Success");
    }
    else
    {
        Serial.println("...Failed");
        _radioData.FailedTxCount++;
    }

    delay(1000);
}

RX Code:
/*
Demonstrates simple RX and TX operation.
Any of the Basic_TX examples can be used as a transmitter.
Please read through 'NRFLite.h' for a description of all the methods available in the library.
Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND
*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 0;       // Our radio's id.  The transmitter will send to this id.
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket // Any packet up to 32 bytes can be sent.
{
    uint8_t FromRadioId;
    uint32_t OnTimeMillis;
    uint32_t FailedTxCount;
};

NRFLite _radio;
RadioPacket _radioData;

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

    // By default, 'init' configures the radio to use a 2MBPS bitrate on channel 100 (channels 0-125 are valid).
    // Both the RX and TX radios must have the same bitrate and channel to communicate with each other.
    // You can run the 'ChannelScanner' example to help select the best channel for your environment.
    // You can assign a different bitrate and channel as shown below.
    //   _radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN, NRFLite::BITRATE2MBPS, 100) // THE DEFAULT
    //   _radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN, NRFLite::BITRATE1MBPS, 75)
    //   _radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN, NRFLite::BITRATE250KBPS, 0)

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }
}

void loop()
{
    while (_radio.hasData())
    {
        _radio.readData(&_radioData); // Note how '&' must be placed in front of the variable name.

        String msg = "Radio ";
        msg += _radioData.FromRadioId;
        msg += ", ";
        msg += _radioData.OnTimeMillis;
        msg += " ms, ";
        msg += _radioData.FailedTxCount;
        msg += " Failed TX";

        Serial.println(msg);
    }
}

Please provide details of what you mean by "said it was transmitting", eg. evidence. Have you tried it with more than one receiver? Are each of those receivers known to be working currently?

I only have 1 receiver and it is working just fine. By transmitting, I meant that in the Serial Monitor, it says that it transmitter and an acknowledgment signal was received but the receiver got nothing.

I suggest you go for the simplest program possible to echo what is transmitted. If that doesn’t work then please post the simple program together with the results.

Yes, I am currently running an echo program and it is the default examples on the nRFLite library. I am using the Basic TX and RX example. I put the program in the question.

this is unrelated ... you had a deleted post about flysky and nRF24L01 ... here is some info that came up since you deleted your post .... google DeviationTX ... also look here for possibly useful info ... https://drones.stackexchange.com/questions


text:
Can't sync with programmer Arduino Uno
I have a weird problem, and it's probably because I'm doing something wrong. I'm quite new to Arduino.
My Uno R3 (Elegoo) has been working fine for a month. It has been sitting on a bench for the past week, unused though. Last night I tried to push a sketch from the IDE: v1.8.14 on Windows 10 Pro (fully updated), board: Arduino Uno, Com port 5. I got this error:
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe6

So, I googled it and tried to fix it. No luck. And, the code changes frequently (right now it's 0x3a). So, I tried

Using the blink sketch
Rebooting my laptop
Using a different USB port
Using a different USB cable
Using different settings in the IDE (Mega 2560 with the ATMega2560 processor)
Using a different operating system (Ubuntu) on a different laptop with a different version of the IDE (1.8.13)
Using a different Arduino (A Freenove Uno r3 from a robot kit)

Using a different board on windows does work! So, my original board is bricked maybe?
I got the same result, more or less. The only difference was that the response code changed. On Ubuntu, the response code is always 0x00 so I suspect the changing code is down to some problem in windows (I trust Linux a lot more than windows). I used the default blink sketch for all these attempts.
Note: I do have a green 'on' led and the L is orange and does the 3xflash on powerup and reset. This is the only USB port in use, so there's only one to choose in the IDE (happens to be com5) and it's clearly shown as Arduino. When I push the sketch, the orange L led stays solid orange and there is no flashing of the rx or tx leds.
Update:
I have read, with interest:
Have I bricked my Arduino Uno? Problems with uploading to board
Because of this I have now checked the power rail with a multimeter and found 5v and 3.3v respectively on USB, and with a 9v battery I have 3.3v and 7.8v respectively. The L led flashes 3 times as expected on power up and reset.
Also, I have nothing attached to the board at all.
When I tried the loopback test the board would not power-on with reset connected to ground, so I don't know how to proceed with that.
I have just tried the Atmega16U2 chip test, and it failed. I'm pretty sure the wiring is correct (though it's hard to tell -- I can't find a dot indicating pin 1 on the good board so I'm guessing it's close to the 'n' in 'on' as mentioned in the post).
How could I have damaged this? What could I have possibly done to break that? I was only driving leds.

See Have I bricked my Arduino Uno? Problems with uploading to board and report (edit into your question) what the results are of trying my various suggestions.

Using different settings in the IDE (Mega 2560 with the ATMega2560 processor) - that is the wrong processor type to select. You want a Uno.

Did your previous sketch use the watchdog timer?

Does this answer your question? "avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program

@NickGammon - Arduino Uno was the first board I tried. I only tried the Mega in desparation. I haven't run a watchdog in a previous sketch - my previous sketch was driving some neopixels. I haven't read your first link yet (will do now), but I tried a 2nd arduino (a new one) and had the same problem.

@NickGammon I have been through your thorough answer linked above and have commented on my progress in the question.

It seems to be the 16U2. The https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293 post really helped diagnose this. That should be referenced on the arduino site. Thanks for the help @NickGammon

Btw: I now recognise that this is a duplicate of https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293

I was only driving leds. - how, exactly? LEDs need a current limiting resistor. I can't see how that would break the Atmega16U2 however.

They were neopixel type 'jewel' LEDs (7 per board, in a circle-ish pattern x 3 boards). I was using a capacitor between the power rails and a resistor as per the instructions. I made this video (https://youtu.be/g4enns1v0Ys) when I originally powered it incorrectly (I fixed that though).

Sometimes boards can glitch depending on wear and tear or on how well they have been manufactured. Personally I always buy boards direct from the Arduino store and  I have never had this issue. One thing that could help is placing a 0.1 uF capacitor between the +5V pin and ground and another between AVcc and ground. There will be some on the PCB already but this can help in some cases. Another thing that can help is pressing the reset buttom just after pressing upload on your PC.
Unfortunately, when out of sync errors occur it can be heavily luck based as to what works and how long it takes. Hopefully one of these tricks will work! But like you say, if other boards are working fine then it could just be bricked

A few things to make sure:

Disconnect your Arduino from any sensor or module
Closely look at the Arduino to see any signs of worn-out solder or damage
Make sure that the programming USB cable is plugged in all the way on the Arduino and the computer
Check the temperature of the ATMEGA chip, as well as, the voltage regulator

If everything looks normal there, you can try reflashing the bootloader on it. You can only do this if you have another Arduino Uno. Here is a good guide: https://www.instructables.com/How-to-Upload-Bootloader-to-Any-Arduino-/. Try that and then comment on what worked and what did not.


text:
Timer question: Phase Correct PWM at specific frequency
I am trying to create a sinusoidal wave segmented in 64 Frame, each holding a Duty cycle precisely varying from 0x00 to 0xff. This is for an Arduino Nano.
I have trouble understanding the following:

Which Wave Generator Mode and Matches will cause an interrupt at the constant Frame as well as help do a phase correct/fast PWM for the varying Duty Cycle?
How to tell which pin to use? I guess OC0B means Pin5 according to Pin Mapping but I'm not sure I truly understand.

This is what I have for the moment.
const byte waveFrame = 126;
const byte wave[]    = {
    0x80,0x98,/*a total of 64 values*/,0x67
};
byte frame = 0;
void setup(){
    pinMode(3,OUTPUT);
    noInterrupts();
    TCCR0A = (1<< WGM00)  // Phase correct PWM with top as OCR0A
           | (1<<COM0A0)  // Toggle OC0A on match
           | (1<<COM0B1); // Clear/Set OC0B on Compare Match when up/down-counting.
    TCCR0B = (1<<  CS01); // Prescaler of 8 (16MHz/8= 2MHz)
    TCNT0  = 0;           // Counter restarted
    OCR0A  = waveFrame;   // Constant frequency/64 for each frame
    OCR0B  = 0;           // Duty Cycle
    interrupts();
}
ISR(TIMER2_COMPA_vect){
    OCR0B = wave[frame & 0x3f]; //Rolls around
    frame++;
}

Thank you! I've lost a little bit of hair on this.

Are you sure your attiny runs at 16Mhz? The output pin is pin  OC0B, which is pin 6 on the ATTiny45. Not sure why you are using the pin mapping of the ATMega644P. Please tell us which processor you are actually using, because mentions three.

Thanks Gerben, I removed the comment regarding the ATTiny as it was not relevant to the issue here described. I'm using the Arduino Nano's ATMega indeed.

OC0B is on arduino pin 5. It seems you code also enables output on OC0A, which is Arduino pin 6, giving you a fixed 50% percent duty cycles. Which is quite useful when you are debugging things, and have it connected to a oscilloscope, or logic analyzer . EDIT Disregard this last part if you actually want to use waveform mode 1.

You'd want Waveform Generation Mode 5. This is PWM, Phase
Correct, but with TOP being the value of OCR0A instead of 255. For mode 5 you need to set both the WGM00 and WGM02 bits. Note that the WGM02 bit is in the TCCR0B register

pinMode(3,OUTPUT);

Pin 3 on the Nano is OC2B. It's PWM is controlled by Timer 2. You
want to use pin 5 (OC0B), since you are using Timer 0. Or
switch to Timer 2.

Phase correct PWM with top as OCR0A

Note that this is the description of mode 5. If you want this mode, you
have to set both the bit WGM00 in TCCR0A (which you did)
and the bit WGM02 in TCCR0B (which you didn't). Here you have set
mode 1: phase correct PWM with top = 0xff.

Not sure why I didn't validate it then. Thank you! That helped quite a fair bit!


text:
Voltage from batteries in series operating on 3 ATTiny, 3 Buttons, and 3 Piezo buzzers
I intend to power three ATTiny45 chips (each requiring around 3.5V) in parallel with 2 pill batteries (namely Maxwell's CR2032) in series (which would come to around 6V). They will each play a sound with a piezo buzzer when a button is pressed.
Now maybe my thinking is wrong but I think dividing the power between the three chips may result in only around 2V delivered to each chip? Does the other components play a role?
So my question is this:

How much voltage is delivered across elements in parallel?
What changes should I do to the wiring to make the most of the voltage?
What kind of resources should I get to make sense of what to do? Cause I thought I was more advanced but this stomped me.

In any case I've added the schematic of what's intended.
[This schematic used to contain resistors to pull the switch but this need was removed with the help of jsotola's input_pullup comment]

simulate this circuit – Schematic created using CircuitLab

the Vcc pin of all three ATTiny45 chips are connected to the same power point ... what voltage would you expect to appear at each Vcc pin?

why don't you enable data pin internal pullup resistor, remove the external pulldown resistor, and connect the switch between data pin and ground?

At first I was hoping for 6V but it looks like it's going to be 2V if I understand well, so would need more power. I actually did not think input_pullup was possible for them AtTinies! Giving it a try now :D

if you are measuring 2 V, then it is because the battery is overloaded ... your schematic shows all three ATTinys connected to the same voltage, which is 6 V

I unfortunately don't own a measuring tool. But ok so that means the voltage does not get divided in 3 because of the parallel chips?

it is the same arrangement as all of the lightbulbs and power outlets in your house ... they all have the same voltage no matter how many are turned on

Alright, I must admit I was dumb for a moment, sorry -_- In terms of amperage though, are 3 chips and 3 piezo disc going to put too much of a strain on 2 pill batteries? How can I find out? In any case @jsotola thank you for the input_pullup you just helped me simplified the process and wiring!

The term "pill battery" is pretty ambiguous.  Please update your question and add the specific batteries being used.  Also, why are you using 100 Ohm resistors on the switches?  When you close the switch you are going to pull WAY more power from the battery than you need to signal an input.  Try something more reasonable like 10K Ohm.

https://www.allaboutcircuits.com/textbook/direct-current/chpt-6/kirchhoffs-voltage-law-kvl/

6V is the absolute maximum rated voltage for the ATTiny45, according to the datasheet. So your at the edge. The ATTiny45 will run just fine at only 3V. So maybe that's an option. Depending on what the piezos require to produce the volume you want.

Coin-cell batteries can't supply a lot of current. If your systems requires more current, you could put additional batterie(s) in parallel. But I'd probably switch to AA batteries instead. 3 AA (Alkaline) batteries in series would give you around 4.5V. Or 4 MiNH AA giving you around 4.8V.

@jwh20 thanks for pointing out! The pill battery I was thinking about is Maxwell's CR2032, added in the question now. Based on jsotola's answer I turned the input as input_pullup and it works fine without the resistor so I will change the schematic shortly.

@Majenko Thank you I am reading on it and it helps make more sense. of how this works. I guess I was closer to Square 1 than I thought ^^"

@Gerben This is very useful comments. I actually don't know what kind of amperage a piezo buzzer require to make louder sounds which is one of my queries, and I will see how to use parallel batteries vs serial. I didn't realize one could actually parallel batteries. I'm actually going for the pill size as it fits better the item, but may have to switch to AAA

Gerben suggested AA batteries, not AAA. AAA batteries don't store very much energy. Better than a CR032 button cell, but still not very much.

If you connect the AtTiny chips in parallel, they will all receive the full voltage from your battery. If you exceed the current output of your battery the voltage will droop.
If the AtTiny chips need 3.5V and you give them 6V instead, it will likely destroy the chips.
The short answer: Don't try to drive microcontrollers directly from batteries. You should get a 3.5V switching power supply. Then you will be able to drive all 3 chips cleanly from your battery. (Switching power supplies are very efficient. They don't waste much power at all.)
Note that button cells produce very small total power (in milliwatt/hours) so they won't drive your processors for very long before they are exhausted. I suggest using 4 AA batteries and a switching regulator instead. The 4 AA batteries would give you a 6V VIN to your voltage regulator, but a lot more total power.

Thank you! I am looking into switching power supplies but they do seem bulky. I also understand that button cells are not very powerful, but what is your thoughts on its lifespan if, say, the chip is mostly asleep?

The math is pretty easy. Calculate current drawn over time. If you draw 1/10 amp for an hour, you have consumed 100 milliamp-hours (mAh) of power from the battery. Batteries are rated by their capacity in milliamp-hours. Voltage regulators waste a little, so you should add some slop for that (look up a given regulator's efficiency to figure out how much waste to calculate.) Look at the "in use" current of your system, and the "asleep" current. Figure out what percentage of the time it will be in each state, and do some algebra to figure out the current used over time.

Here is an article that talks about using sleep mode on an AtTiny45 to reduce power: https://www.re-innovation.co.uk/docs/sleep-modes-on-attiny85/. Note that you also need to turn off various subsystems and set the digital pins to input mode in order to get the lowest power consumption in sleep mode. It sounds like if you do all that, you can get the power consumption down to around  0.2mA. So yes, you can greatly increase the lifespan of your button cells if the AtTiny spends most of its time asleep.

thank you kindly for such a complete answer with side quests too! I've researched a bit the subject around sleep modes but I didn't know it was best to turn pins to input, will do that! Unfortunately the article at https://jira.kdc.capitalone.com/browse/AOM-1290 can't connect? Says Server not found. Thanks a lot again!

Sorry, that was the wrong link.Here is what I meant to post: Note that the more current you draw from a battery, the shorter its lifespan. That is a complex subject. Check this article if your interested: https://www.embedded.com/how-much-energy-can-you-really-get-from-a-coin-cell/


text:
How to use a push button & transistor as a kickstarter for power supply?
My goal is to save energy, and I intend to do so by powering a chip with itself, and cut power whenever unnecessary. The best image I can have is of a startled monkey who jumps on the branch, screams its profanities while holding to the branch, and when the screams are done, lets go of the branch and falls back on the floor, asleep.
The chip, in my case an ATtiny45, has a program that just makes a specific sound (hopefully more pleasing than an angry monkey's) with a PWM, but would also power an output pin connecting to a transistor acting as a relay between the battery and the power pin.
This is the ideal protocol:
(No closed circuit, no power)
Press Button
Battery power goes through to transistor
Transistor allows current from Battery to PWR pin
Software: Chip starts PWM to Speaker and Outputs constantly the Hold Pin
Hold pin powers the transistor and thus the chip for when the button won't be pressed
Software: When Button still pressed, makes Chip Scream louder
Software: Button not pressed anymore makes chip scream softer until it's done screaming
Software: Scream is finished, stops powering the Hold Pin
Transistor isn't powering the chip anymore.

I think the idea is plausible, though I can't test it at the moment due to not having NPN transistors (?)
My questions are the following:

Truth: Is is possible for a transistor as relay to power a chip on demand?
Risks: Is the power going to be stronger due to the amplifying nature of the transistor? What about the chip, I've read that a chip can maintain its code for 20+ years without power supply. Is this true?
Goals: Is there a better way to save power? Would it be best for the chip to just have sleep enabled?
Name: If this works, is there a better name than the Startled Monkey?

Thanks again for your help, this community has already taught me a lot!

simulate this circuit – Schematic created using CircuitLab

why do you expect the ATtiny45 to wake up when it is disconnected from power? ... research deep sleep

I have a feeling, that you would need a PNP transistor in this case, because you need a specific minimum voltage difference between base and emitter for the NPN transistor to get conductive, which would not work with the MCU connected to the emitter. NPN transistors are usually low side switches, not high side. Currently not sure about that, but I've definitely seen a good answer somewhere from Majenko, who described a similar circuit, only based on NMOS transistors.

I think all this effort is unnecessary. The ATTINY45 pulls a maximum of 2uA when sleeping...

..and in practice I've found the typical current to be much less.
If, say, you are using AAA batteries for you project then you could sleep for more than 100 years. In practice your batteries will self discharge long before this, so any potential power savings by completely disconnecting the chip are wasted (and remember there is some leakage loss though the transistors that might even be more than the sleep power used by the ATTINY).
Instead connect the batteries directly to the power pins of the ATTINY and connect the button between any IO pin and ground. Activate the internal pullup on the IO pin and then set a pinchange interrupt on that pin to wake the chip when the button is pressed. Now go to sleep and wait for a button press to wake you.

A lot more simple and practical than my aspiration, especially due to the fact I need to do it for multiple units. Thank you!

Your idea is sound, but your implementation is flawed.
First, you don't want to bother with "wake" and things like that - when the chip gets power it just starts from scratch - that's your "wake" signal. Your code will just be "Hold it on" and "Make a sound" followed by "Let it switch off".
You only need one IO pin for that - the "Hold it on" signal. The "catch" signal in your schematic is just the chip getting power.
And then there's your schematic.  You should really use a P-channel MOSFET to do the switching of the power, not an NPN transistor. An NPN won't work, and a PNP (which would be what you would use for this if you were using a BJT) would impose a voltage drop, which you don't want.
Your circuit would in fact need to look like this:

simulate this circuit – Schematic created using CircuitLab
When idle M1 (P-channel with threshold voltage well below the battery voltage) is turned off by R1 pulling the gate up to the source voltage. Pressing the button pulls the gate below its threshold voltage allowing M1 to turn on. The chip then gets power.
M2 (N-channel with threshold voltage well below the chip voltage) is then activated by the chip by driving the GPIO HIGH to bypass the switch and connect the gate of M1 to GND.  R2 keeps M2 turned off while idle.
M2 is needed so that there is no current flow between the battery and the GPIO when the power is turned off.  Without it current can flow through R1 into the GPIO, through the ESD protection diodes inside the chip, and potentially break the chip.
Now to help clear up some of your questions:

Truth: Is is possible for a transistor as relay to power a chip on demand?

Yes, it is.

Risks: Is the power going to be stronger due to the amplifying nature of the transistor?

No. Amplification, with a BJT, is really a misnomer. It doesn't "amplify" a signal, it takes one small signal and uses that to proportionally control a larger signal. But that's only in the "linear" portion of the curve. When used in "saturation" like this it's more like a switch - power applied to the base turns on the flow of current from collector to emitter.

What about the chip, I've read that a chip can maintain its code for 20+ years without power supply. Is this true?

Yep. Flash memory typically has a retention time in the order of 10 to 100 years. 20 years is a reasonable ballpark figure.

Goals: Is there a better way to save power? Would it be best for the chip to just have sleep enabled?

Zero power is the best low power there is. Even in the deepest sleep mode the chip will still draw power. But if you do it right there can be little difference between the current drawn by a sleeping chip and the self-discharge of a battery as it sits idle.

Name: If this works, is there a better name than the Startled Monkey?

I like the name Startled Monkey. I think I'll use that in future myself.

Wow @Majenko this is a thorough answer that makes me understand a lot more! For the PNP, the fact that it does a voltage drop actually would solve another problem of mine. As per another question I posted, 2x3V batteries are too much voltage and could likely destroy the chip, and the PNP induced voltage drop could work, depending on how much voltage is dropped?

However why is the second transistor and resistor necessary instead of a simple diode? As for the resistor, if I understand properly, is it to direct the current a certain way, or to protect the chip from full amperage on the input pin?

@B7th A diode won't protect the chip from the incoming current when turned off. You need to sink current from the gate of the P-channel, which means the diode would have to be oriented to allow current flow into the chip - thus negating any possible protection. The resistors are purely pullup/down resistors to keep the gates at the right level when the chip is unpowered.

@B7th And for the battery voltage you should be considering a proper buck regulator with very low (or zero) dropout voltage, or at worst a zener diode to clamp the voltage at 5V (which is wasteful of power).

So a buck converter will help correct the voltage, the two MOSFET must be of the opposite "charge", and the two resistors to pull the gates. I understand the importance of each of them, however I will have to repeat these for each of the chips that will do the same task and there will be between 12 and 32 of them, all screaming asynchronously. If there is any of these items that can be removed, paralleled, simplified, or coded in one way or another, what could it be? The buck converter can be used for more than one so that helps.

@B7th You can get a single chip with the P/N channel MOSFETs in them as a pair, such as this one (though of course check your current requirements, but it sounds like you don't need much).

If you need that many of them, it might be better to not do this in hardware, but putting the chips in sleepmode instead. That way, all that's needed is the chip, the button, and the buzzer. It's perhaps a bit more work to get the software right, but you only need to do that once, not 12-32 times. Current in sleepmode should be negligible, like Majenko said.


text:
Nano: All digital pins do not output anything
New user here. Using the examples provided on the Arduino IDE software I could produce melodies with a piezo buzzer, or have a blinking LED.
Not anymore. No digital pin is giving anything. I can see the embedded LED blink if I program the Pin 13, but no impact outside of it.
So I tried connecting an output digital pin (13) to an Analog input pin, or any one that can be put as input (A7, D5, etc.) (with a resistor so not to destroy the little thing).
const char out=13;
const char  in=8;
char         i=0;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);
  pinMode(in,  INPUT);
  digitalWrite(out, LOW);
}
void loop() {
  if(i&1){
    digitalWrite(out,i&2?HIGH:LOW);
  }else{
    Serial.println(analogRead(in));
  }
  i++;
  delay(50);
}

The output has been 0, whichever digital pin it is connected to.
How can I actually find out if, by any chance, I successfully (!) damaged all my digital pins?

I currently use a breadboard
The ground is connected correctly (to GND)
It stopped working between uses, last time I was trying a Tone(out,val) melody
I'm measuring the out-pin value by connecting it to an analog in-pin with a resistor in series
I did set the out-pin as such during setup. (pinMode(out, OUTPUT);)

So! Looks like I didn't understand the codes for the digital pins. I thought we had to use the pin number, but the digital pin number (say 10 for D10) is what it takes to address it. And I was always referring myself back to the schematic for each pin -_-.
As well with the accepted answer, I needed to pull down (or up? still can't figure it out!) the input pin with a resistor to ground.
Thanks everyone!

Welcome! Could you add a little more information about your setup. Do you use a breadboard? Do you have GND correctly connected to your external components? When did it stop working? How are you measuring the pin’s output? Did you set the pins to OUTPUT in setup()?

Thank you StarCat! I have added the information thank you!

Do you have a multimeter available to measure the voltage on the output pins and the supply voltage? Is the Nano behaving normally otherwise?

A6 and A7 are analogue inputs only. They can't do digital reading or writing.

Thanks Majenko and StarCat! I don't have a multimeter available, but the reading with analogRead starts high and go lower and lower.

Did you set the pins to OUTPUT?  Show the whole code.

Added the corrected code Thank you Delta_G!

Your sketch works on a Nano (clone) that I have

I am using a high-brightness white LED with a 10kΩ resistor to bring the brightness down to a bearable level, so the current drawn is about (5v-2.2v)/10kΩ = 0.28mA. This is a low level of current and should be safe for poking around with.

I can see the embedded LED blink if I program the Pin 13, but no impact outside of it.

That suggests that the ATmega328P is essentially undamaged and that at least the IC leg connected to D13 is working as it should.

How can I actually find out if, by any chance, I successfully (!) damaged all my digital pins?

Without a multimeter or other tools,  I would take a LED and resistor that draw less than 5mA, test them between VCC and GND to make sure they work
Then I would use the resistor and LED to check the output of each of the D2 to D13 outputs using your existing sketch.
When the onboard LED blinks, I am able to attach a LED and series resistor to pin D13 and get it to blink.

I wasn't sure what you intended by setting in to 8 so I later changed your program as follows:
const char  in=A1;

and I got this output on the serial monitor after connecting a jump lead from D13 to A1
0
1010
0
1009
0
1009
0
1009
0
1009
0
1009
0
1009
0
1009
0
1008

If I pivot the LED away from pin D13, I can use a jump lead as a test probe

Main points:

pick a high resistor value that minimises current drawn but is still easily visible.
check the LED works! (is right way around etc)
use a jump lead as a probe.

There are more sophisticated test circuits you could build with a FET etc but this would normally be enough for me to decide if an Arduino's outputs are damaged.

Extract from ATmega328 datasheet - note the max current draw per pin is 40mA. Exceeding that is probably the easiest way to damage the IC but if the onboard LED labelled "L" (and connected to D13) works, it means that part of the IC is undamaged.

I'm impressed by how nice people already are, thank you! That is an exhaustive answer and shows you spent actual time to solve my issue. I'll test it and let you know what's the results!!


text:
Reliably using analogRead as a compact digitalRead
My goal is to reduce pins being used for micro-controllers with limited pins, or projects requiring a few different digital input values.
How I intend to do so is by using ADC pins to gather four specific different values through resistors with analogRead, which would otherwise need 2 pins (!A+!B, !A+B, A+!B, and A+B).
value = analogRead(adcPin1) >> 8;

This would give, if properly wired, 4 possible results like some sort of "Quartary bit", as analogRead yields a 10-bit response.
So my questions are the following:

Can analogRead be sufficiently reliable to tell the difference between four possible values?
What would the wiring/casing/etc. need to look like to prevent any errors?

Thanks!

I don't know how reliable it is, but it seems to be a quite commonly used technique.

Thank you Edgar that's exactly what I was looking for! Thank you I don't know why I missed on the research :/

There are 5-button-pads (https://www.sainsmart.com/products/lcd-keypad-shield-for-arduino-duemilanove-uno-mega2560-mega1280) available using this technique. It assumes you press only one of the buttons at a time. Just an info, no advertising, no recommendation :)


text:
Arduino IDE on Attiny45: What kind of power does a chip need?
I have this little AtTiny45 which I'm loading a program with Arduino as ISP.
My goal to use this chip along with a op amp, a piezo buzzer and a press button, and have it automatically sleep between uses.
I intend to use 2 3V pill batteries in parallel (specifically CR2032 if this makes a difference) as the power source, so here are my two questions:

Can 2 3V pill batteries in parallel power a small application that will produce audible sound?
How long could these batteries last --based on constant use-- if someone used this item for an hour per day?

Thanks jsotola! I've updated the question to fit more the need as I was not as clear as necessary. It has a press button which will spark a sound for a short while then resume sleep.

Everything depends on used parts, and overall current consumption... For now it's just "it might or it might not" to almost every question you have

Assuming 5mA when on, one hour a day; 2µA when sleeping the rest of the time; I get around 40 days of runtime. But you can probably have the MCU sleep in between task during that 1 hour of usage. You might have to find a way to turn of the opamp when it's not needed, to keep the sleep current as low as possible. I'm unsure how much current a piezo uses, but I don't think it's much.

I guess one could provide current to an opamp through a transistor?

@Gerben I followed the link very useful! Thank you


text:
SPI communications with an 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: 1.
This is my code, pretty straight forward (although this is my first time working with SPI). I am 100% sure the wiring is correct.
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 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);
}

not the problem, but SPI.begin() configures the SPI pins so your list of pin numbers and pinmode settings are unnecessary for MOSI, MISO and CLK

the sensor is not 5V tolerant. how did you wire it?

@hcheung not sure where am I using the Arduino board as a slave here?

@Juraj SPI.beingTransaction(settings) uses my pin numbers and settings, downstream from SPI.begin(), correct?

@Juraj Wiring graphic: https://i.imgur.com/ShAVLqc.jpg

hardware SPI pins on Uno are not selectable. I don't see level conversion in the picture? is the device SPI master?

If I read the section 4.4.1 of the datasheet correctly, you send a write command 0xE9 follow by a TSS command to tell the device what you want to retrieve, and if the return value is either 0x00 or 0x06, you send a 0x69 to read the data. I don't see your code is doing that. In fact, I have hard time to find where you get those commands that you used from the data sheet.


text:
How to separate in columns the data contained in a barcode
I have the following code, which allows me by scanning a typical 128 barcode to write this code in SD card under the Header "FA" as well as the time and date of scanner under the Header "Zeit".
I use for that an Arduino Uno, Waveshare scanner module connected in Serial to the arduino and SD/RTC mounted on top of the Arduino.
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <Wire.h>
#include "RTClib.h"
#define rxPin 2
#define txPin 3
RTC_DS1307 RTC;
SoftwareSerial mySerial = SoftwareSerial (rxPin, txPin);
File main_folder; // initialize folder for saving
File dataFile; // initialize sd file
const int chipSelect = 10; // CS pin on sd card module
int prev_file_indx = 0; // used for file naming
String fileName = "000";
char timestamp[30];

const unsigned int MAX_INPUT = 50; // how much serial data we expect before a newline

void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

void setup ()
{
  Serial.begin (115200);
  mySerial.begin (115200);
  Wire.begin();
  if (!RTC.begin()) {
    return;
  }

  pinMode(10, OUTPUT);
  if (!SD.begin(chipSelect)) {
      return;
    }

    main_folder = SD.open("/");
    fileName = sd_saver(main_folder);

 // end of setup

    delay(1500);
    dataFile = SD.open("DATA"+fileName+".csv",FILE_WRITE);
  if (dataFile) {
    Serial.println(dataFile);
    Serial.println("Writing Headers...");
    dataFile.println("FA,  Zeit");
    dataFile.close(); // close the file
    Serial.println("File closed, Headers written");
  }
 }//Open-Create file , populatrd with headers (2 collumns)

void process_data (const char * data)//to process the incomingserial data (from Scanner + timestamp when scanned) after a terminator received

{ delay(500);
    SdFile::dateTimeCallback(dateTime);
  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
     dataFile = SD.open("DATA"+fileName+".csv",FILE_WRITE);
  if (dataFile) {
    Serial.println("Writing to file...");
    dataFile.print (data);
    dataFile.print(",");
    dataFile.println (timestamp);
    Serial.println (data);
    Serial.println (timestamp);
    Serial.println("Done.");
    dataFile.close();
  } else {
    Serial.println("error opening test.txt");
    delay(1000);
  }

}

void processIncomingByte (const byte inByte) //Processsing of the incoming scanned data
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
  {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // i here reset the buffer for the next time
      input_pos = 0;
      break;

    case '\r':   // discard the carriage return
      break;

    default:
      // keep adding if not full and permit for a terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }  // end of the switch

} // end of processIncomingByte

void loop() {
  delay(2000);

  // if serial data available, process it
  while (mySerial.available () > 0)
  processIncomingByte (mySerial.read ());
  mySerial.write(processIncomingByte);
  delay(1000);

  //possibility to do other stuff while testing digital?? ...

}  // end of loop

String sd_saver(File dir){
  while(true){
    // iterate all files to ensure no overwrites
    File entry = dir.openNextFile();
    if (!entry){
      break;
    }
    // naming routine
    String entry_name = entry.name();
    if ((entry_name.substring(4,7)).toInt()>=prev_file_indx){
      prev_file_indx = (entry_name.substring(4,7)).toInt()+1;
      if (prev_file_indx>=100){
        fileName = String(prev_file_indx);
      } else if (prev_file_indx>=10){
        fileName = "0"+String(prev_file_indx);
      } else{
        fileName = "00"+String(prev_file_indx);
      }
    }
    entry.close();
  }
  return fileName;
}

My question is, can you come up with a way or guidance on how I should redo the code so that allows me to split the information of the barcode in different headers? that is columns. So for example the number "10000" as shown in the image after "@" to be in logged in another column called "Machine Number" ? I tried to insert control characters in the barcode to be scanned , but they are not interpreted as such but as characters .
Any help or thoughts are most than welcome
Thanks

google c++ parsing text data

take a look at strtok.

@hcheung before I delve into this function, assuming that "pch stands for recompiled header, would you tell me if this "precompiled header" is acknowledge by Arduino Library , do I need a new one?

It's possible that the code's author decided to abbreviate the variable name, which could mean is stands for "pointer to a char". If you search our site for char * pch;, there are a few example of the code adapted to work in the Arduino IDE.

@VE7JROthanks for your answer. You mean by your site: http://www.cplusplus.com/?

@Maximilian1988 - I'm not sure what you mean when you say "your site". I am not affiliated with cplusplus.com, or any other Arduino website, except for this one. You are free to use any code at cplusplus.com as long as you can get it to compile in the IDE you are using. Once you have mastered the language reference here https://www.arduino.cc/reference/en/, and want to do advanced "things", generic C++ websites will be your friend.