text:
Continuous voltage on IO Pins while 5V is not Connected?
i have a small project where i just sucessfully destroyed my frist of 5 Digisparks (Attiny85).

In the Picture you see the Cirucit. I have 2 Liion cells connected in series to get high enough voltage to step it down to constant 5V. To these 5V some Neopixels and a Digispark controller are connected which will set the color for the Neopixels. A0 and A1 measure the Voltage of the Cells to signal the user if the Voltage is to low so it can manually be switched of.
While prototyping it i didnt have the 10k resistors in there.
Now what happend: While connecting the cells after each other the Controllers LEDs already lit up with the Frist cell. I guess it was powered trough the A0 pin (again i didnt have the 10k resistor in there),  so i guess the internal IO Protection diodes conductet the voltage trough and this way the controller got damanged. Since this happend it wont turn on Anymore.
The problem: since i have really small space i cant use a multiple pole switch to also remove the voltage from the IO pins and therefore i will always have voltage von A0 and A1 while there is no 5V Supplyvoltage. I would guess that the Series resistance on the pin would be enough to Limit the current trough them and this way protect the controller from damange. But i dont really have experience with that and hope that you guys can give me some hints what could also be a problem or what could help :) I really dont want to destroy a second one xD
Thanks in advance and have a nice day :)

You are correct in your analyses of the original problem. The 10k resistor should be fine, as it would only let through 0.4mA. Though it's not exactly elegant. This current might be a problem for the bottom battery, if it's left turned off for a long time. As it would slowly drain the battery.

@Gerben I thought the analog inputs on most Arduino boards were capacitive, so the current flow is near zero? (I guess if the board is off, the pin might be operating as a digital output on LOW, which would connect it to ground.)

Normally in this situation you would isolate the connections to the batteries with P-channel MOSFETs and only switch them on when you want to sample the voltage.

@DuncanC the problem here were the clamping diodes inside the IC on each IO pin. So the 3.7V was going into the pin, though the clamping diode, to Vcc. Powering the entire circuit through this diode. This can work for a few milliamps, but with the LED strip, the diode won't survive for long.

That makes sense. I forgot about the clamping diodes providing a path for inputs going to VCC.

For this I would recommend isolating the power from the batteries with P-channel MOSFETs and only switching them on when you want to sample the voltage. This means that there is no power consumption at all (aside from an absolutely minuscule leakage current) when turned off.
The whole setup would require 4 MOSFETs - two P-channel and two N-channel. They don't need to be big, since the currents involved are very small, but they do need to have "logic level" thresholds, ideally < 1.5V (-1.5V for the P-channel).
The basic circuit looks like this:

simulate this circuit – Schematic created using CircuitLab
The circuit is made up of two identical segments - M1+M3 and M2+M4.  The operation is fairly straightforward:

M1 (M2) is kept in the OFF state by R1 (R2) pulling the gate up to source.
M3 (M4) can pull the gate of M1 (M2) LOW turning it on and allowing current to flow
Any GPIO pin (D7 in this example) can control both M3 and M4 together
R5 keeps M3 (M4) off when there is no power - otherwise it floats.
R3/R4 are your existing voltage divider.

The purpose of M3 and M4 is to both turn the GPIO (D7) into "open drain" so that it's either pulling down or floating high (rather than driving high at 5V) and to isolate the two pullup gate voltages. The same effect could be achieved by two diodes and one MOSFET but it's simpler to just use two MOSFETs and not have to get diodes as well.

Wooow, didnt expect such a detailed answer, thanks very much.

Sendt out the last comment before i wanted xD so here the rest:
Now i have to order some common logic level mosfets :')
Since im using a mechanical switch to turn off the power i guess i would still have to assure that Pin D7, in this example, would be low when i switch off, because if not it would still be connected to the pin for a split second. Any thoughts on this ? :)

You can keep the inline current limiting resistors for that.

Also you would only have the FETs turned on briefly when you're doing the reading of the battery voltage, and off the rest of the time.

As a general rule, you should not apply a higher voltage to the logic pins of digital ICs than you do to their power pin. This means that if you disconnect power, you must also shut off voltage to the logic pins.
Failure to follow that rule will often destroy an IC.
I don't know about the specifics of the inputs on your DigiSpark. 10K resistors will certainly lower the current that is able to flow into those pins, but you would still be breaking the "don't put more voltage into an input pin than you put into the VIN pin" rule.

If all you are doing with A0/A1 is 'signalling the user that the voltage is too low for continued operation', then consider the following:

remove the lead from the top of the lower battery entirely
instead of the 1/1 voltage divider, use something like 10/1 (i.e. a 680K on top and a 68K on the bottom to provide a large series resistance (making the steady-state current drain on the battery negligible).  This will also put the nominal full-charge voltage as measured at the ADC input well within the DC voltage range of the Digispark at a small cost in accuracy.  The specs for the ATiny85 ADC input impedance is something like 100 MegOhms, so the accuracy drop from using a 680K series resistor shouldn't be more than a few percent.  Use a variable power supply to calibrate the A/D setup so your controller will alert the user when the battery stack gets low.  If you don't have a variable power supply, consider something like this

Frank

Jeah, measureing only the top cell is great if you always use "married cells" and have some puffer for inaccuarcy, but since i plan to make the Cells swappable i think in my application i should always monitor both cells.

Miss-matching battery types is usually a very bad idea, but if you must, measure both voltages with high-ratio voltage dividers as described above in order to make the current drain through the divider comparable to the self-discharge current of the batteries.


text:
3.3V to 5V PWM level shift
I need to shift a PWM signal from a ESP32 (3.3V) to receiver that supports 5V. The signal is at maximum of 400Hz. Can this shifter do the job ?

Yes, it can. Though depending on the receiver you may not need it. If the receiver is a 5V Arduino, it will see 3.3V on its digital input pin as HIGH.

Already bought it and it works, and no, the receiver is not an Arduino, it's an ESC (Electronic speed controller) for a quadcopter.

That should work, but it's overkill. Those devices are made for bidirectional signaling. You should be able to use a single transistor that is driven to saturation at 3.3V. A Suitable "logic level" MOSFET with a 3.3 gate voltage should do the trick.
And, as Chris L said in his answer, you may be able to drive an input on a 5V Arduino directly with 3.3V. That's a high enough voltage to be read as a logic level 1.

source: Stack Exchange

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

sort: votes


text:
Cannot send any UDP packets from ESP8266 Wemos D1
I am attempting to send sensor data from a battery-powered device using UDP. The goal is to send a datagram immediately after the wifi station awakes from sleep then immediately go back to sleep after writing the datagram to a given IP address or hostname.
I can send data to Thingspeak's API using their library so I know the device works, but when attempting to use the WiFiUDP library to send a datagram to an IP address on the same LAN I see nothing happen. My device is getting on the wifi and the udp.endPacket() command is returning successful, but I am not receiving the packets on the server. I know the server works because I can use nc to send UDP packets from other machines on the LAN.
Here is my sketch with the irrelevant bits redacted.
// https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html
#include <ESP8266WiFi.h>
// https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/udp-examples.html
#include <WiFiUdp.h>

// Create udp class instance
WiFiUDP udp;

void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to WiFi");
  WiFi.mode(WIFI_STA);
  WiFi.hostname(hostname);
  WiFi.begin(ssid, pass);

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

  Serial.print("SSID:\t");
  Serial.println(WiFi.SSID());

  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());

  Serial.print("Gateway:\t");
  Serial.println(WiFi.gatewayIP());

  uint8_t buffer[50] = "hello world";
  char message[] = "hello world 2";

  IPAddress staticIP(192, 168, 1, 118);
  udp.beginPacket(staticIP, 3381);
  udp.write(buffer, 11);
  //udp.write(message);
  udp.endPacket();

  // Calculate required sleep time and go to sleep
  long sleepTime = measurementInterval - millis(); // in milliseconds
  if (sleepTime < 100) sleepTime = 100; // set minimum sleep of 0.1 second
  Serial.print ("Going to sleep now for ");
  Serial.print((float)sleepTime / 1000, 3);
  Serial.println (" seconds.");
  Serial.print ("Time going to sleep=");
  Serial.print ((float)millis() / 1000, 3);
  ESP.deepSleep(sleepTime * 5000); // convert to microseconds
}

And my node server just to be complete here:
const dgram = require('dgram')
const server = dgram.createSocket('udp4')

server.on('error', (err) => {
  console.log(`server error:\n${err.stack}`)
  server.close()
})

server.on('message', (msg, rinfo) => {
  console.log(`got message from ${rinfo.address}:${rinfo.port} - ${msg}`)
})

server.on('listening', () => {
  const address = server.address()
  console.log(`server listening ${address.address}:${address.port}`)
})

server.bind(3381)

I've also tried adding delays between each function to no avail.

I don't see udp.begin(). Some Arduino libraries require it even for sending.

run wireshark on your server or on any pc on your LAN ... see what is being sent

@Juraj udp.begin() is for listening, but I did try it and see no difference.

@jsotola wireshark captures no information from the ip of the esp8266 device, udp or otherwise.

you have to send the packets to the IP address of the PC that is running wireshark

@jsotola that is what I tried. I'm thinking it may be a problem with the client software I just don't know what.

Per the esp8266 subreddit, you need to add a sufficient delay() of 50-100 milliseconds (not microseconds) before going to sleep as none of the udp functions are blocking.

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


text:
nRF24L01 - Measuring distance using time elapsed
For school usage, my team and I are working on a wristband that will alert the user if they are too close to another wristband (for social distancing). The problem is measuring distance using radio waves. Since I cannot use signal strength, I'm thinking about calculating distance from time taken to transfer some data and velocity (which will be around the speed of light). I discarded the idea of using ultrasound because it is too easily interfered with by other obstacles.
My plan is along the lines of this:

Sensor 1 and 2 are synchronised to a clock.
Both will run a
"stopwatch", and the time values should be exactly the same at the
same time.
Sensor 1 sends out a message to Sensor 2. The message
contains the time at which the transmission started.
Sensor 2
receives the message, immediately records the time of reception, and
calculates the time taken for data to travel
d = v/t
Vice-versa

If the distance is smaller than the radius, a warning is triggered in the form of a vibration motor.
Limitations include clock speed; I intend on using a Seeeduino XIAO, an Arduino-compatible board. The clock speed is max. 48MHz, meaning that the smallest increments it can measure is 20.82 nanoseconds. I also calculated that it would take 13.33 nanoseconds to travel two metres (the former distance to keep in public). Hence, with the clock speed available to me, I can only measure 3m and beyond.
Assuming I was happy with this distance, would I be able to do this using one single Arduino sketch? I know that Arduino programs can only run one at a time. Would a constant background clock/stopwatch be too complex? Could you give me any other pointers?

You'd want an atomic clock strapped to each user's back for those kinds of timing accuracies...

@Majenko Timing accuracies aside, would it be possible for that kind of code to be run simultaneously? Run a counting clock whilst constantly sending radio pulses? Subroutines?

If you write it properly you can make it like two things are running at the same time, but that won't get you around the basic physical barriers that make it impractical.

the ultrasound idea may actually work ..,some type of a ping exchange .... perhaps a unique sequence of pulses could be transmitted ... when the sequence is received, a response would be sent .... the originator of the exchange would listen for the response and, when received, calculate the round trip .... a radio link could be used for administrative functions, such as system synchronization

@jsotola Ultrasound sensors have a narrow detection angle and area - typically about 30 degrees. If I used it on a wristband, I might pick up false positives from objects around me such as tables and chairs, not to mention the fact that I could be standing right in front of someone and not pick them up. Ultrasound cannot penetrate objects... they are useful because they bounce off them.

how about this .... radio is used to assign every wrist band a spot in a queue so that there is no interference between bands .... when a band has its turn, it sends out a synchronizing radio message and an ultrasonic pulse.... all the other bands wait for the ultrasonic pulse ... any band that receives the pulse before a timeout value will be deemed to be too close ... a radio message would be used to alert of proximity .... it makes no difference if the ultrasonic pulse is reflected from an object .... the ultrasonic transmitter and receiver would have to be made omnidirectional

Omnidirectional ultrasonic sensors are expensive, and this is a school-wide project. Thanks for your ideas, but I have chosen to go with BLE.

13.33 nanoseconds is actually 4 meters. The NRF send bits at 2Mpbs, using FSK. So the transmission is divided in chunks 250ns. So don't expect ns precision from the signal detection logic inside the NRF.

@Gerben My mistake... Originally I had planned for the signal to go from S1 to S2 then back to S1, thus making the formula v=2d/t and d=vt/2. Thanks for pointing this out. I have abandoned this idea anyway, and am now pursuing BLE. It's not accurate, but it's what I need.

Speed-of-light-delay measurements are not practical for the use-case you propose. As Majenko suggests in his comment, you'd need EXTREMELY accurate time measurement, as well as high speed radio-frequency signal processing. Any measurements you do through software will be far too inaccurate as a result of the software timing.
Apple's iBeacons (which are based on BLE) offer immediate, near, medium, and far distance readings that are based on signal strength. You should be able to achieve something similar with your own wristbands using BLE. The different distance thresholds would have some slop to them, but it should be possible to get decent results.

How about if I subtracted process time from the overall time? I know that the RF module takes 2us to process each bit.

No. This WILL NOT WORK without specialized hardware.

I am looking into BLE - it looks like it's what I need.

@Hari5000: Re “the RF module takes 2us to process each bit”: do you mean it always takes exactly 2.000 µs? Or is it more like (2.00±0.01) µs?

@Hari5000 The official Covid-19 API from google and Apple also uses BLE beacons. They have chosen that approach for a reason. Distance calculation between two arbitrary (and moving) points in that range are not that easy. BLE is the way to go for best and easiest results.

Maybe not "best" results, but easiest, and good enough, results, using inexpensive hardware.


text:
Blink LED with different on off times just once with millis
So Im having trouble trying to figure this out. My project needs a valve to stay shut and when an event is triggered, 3 seconds into that event the valve opens for 2 seconds, then remain shut till it's triggered again. I was just treating it like an LED in the code. I was trying to code it to jump from one if-statement to the next with the appropriate delays but it doesn't work the way i thought it would. Any help would be great. Thanks
//the event does ventGo0 = true;

 if(((millis() - previousVenting) > offoffDuration)&&(ventGo0==true)){
        previousVenting1 = millis();
        ventGo1=true;
        ventGo0=false;
       }

     if(((millis() - previousVenting1) > onDuration)&&(ventGo1==true)){
       digitalWrite(ventPin, HIGH);
       previousVenting2 = millis();
       ventGo2=true;
       ventGo1=false;
     }

       if(((millis() - previousVenting2) > offDuration)&&(ventGo2==true)){
         digitalWrite(ventPin, LOW);
         ventGo2=false;
       }

      ```

just a note ... if (ventGo1==true) is same as if (ventGo1)

You could use two millis() based timers.
// Sketch uses 1066 bytes (3%) of program storage space.
// Global variables use 27 bytes (1%) of dynamic memory.
// Arduino Uno, IDE 1.8.9
class MillisTimer{

  private:

    unsigned long m_timeInMilliSeconds;
    unsigned long m_previousMillis;
    byte m_timerActive;

  public:

    MillisTimer(unsigned long timeInMilliSeconds):
      m_timeInMilliSeconds(timeInMilliSeconds){
      m_timerActive = 0;
      m_previousMillis = 0;
    }

    bool Update(){
      if(m_timerActive && (millis() - m_previousMillis >= m_timeInMilliSeconds)){
        m_previousMillis += m_timeInMilliSeconds;
        return 1;
      }
      else{
        return 0;
      }
    }

    void Start(){
      m_timerActive = 1;
    }

    void Stop(){
      m_timerActive = 0;
    }

    void ReStart(){
      m_timerActive = 1;
      m_previousMillis = millis();
    }

    byte IsActive(){
      return m_timerActive;
    }

};

// Make copies of the object to work with.
MillisTimer TwoSecondTimer(2000);
MillisTimer ThreeSecondTimer(3000);

void setup(){

  // Call this function when an event is triggered.
  ThreeSecondTimer.ReStart();

  // Timer status indicator.
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // Call the update function as fast as possible.
  if(ThreeSecondTimer.Update()){
    digitalWrite(LED_BUILTIN, HIGH);
    ThreeSecondTimer.Stop();
    TwoSecondTimer.ReStart();
  }

  // Call the update function as fast as possible.
  if(TwoSecondTimer.Update() && !ThreeSecondTimer.IsActive()){
    digitalWrite(LED_BUILTIN, LOW);
    TwoSecondTimer.Stop();
  }

}

Great thanks Ve7jro. I put your code in my project and it works great, just what I needed. When the arduino is booted up for the first time, it does tigger the the led or in my case the valve. Is there a way to stop that from happening? Thanks

@Jason8899 _ If you update your question with the complete "sketch", I'll take a look at it for you. Keep in mind that, ThreeSecondTimer.ReStart(); in setup() starts the timer immediately, so you should remove it from setup() and add it to your code, the "event driven" part of your code.

I found the issue, thanks again.


text:
StoreProhibited error while trying to read file to PROGMEM
I'm trying to read a file from micro SD on an ESP32-cam board and upload to an FTP server, but when I try to read data from the opened file to an unsigned char, it gives me the following error:
Guru Meditation Error: Core  1 panic'ed (StoreProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x4008c674  PS      : 0x00060030  A0      : 0x800ed1c7  A1      : 0x3ffb1e20
A2      : 0x00000000  A3      : 0x3ffd7c78  A4      : 0x00000080  A5      : 0x00000000
A6      : 0x474e5089  A7      : 0x0a1a0a0d  A8      : 0x00000000  A9      : 0x3ffb1df0
A10     : 0x00000080  A11     : 0x3ffb66e4  A12     : 0x3ffd7c78  A13     : 0x00000080
A14     : 0x00002494  A15     : 0xff000000  SAR     : 0x00000018  EXCCAUSE: 0x0000001d
EXCVADDR: 0x00000000  LBEG    : 0x4008c670  LEND    : 0x4008c68c  LCOUNT  : 0x00000007

ELF file SHA256: 0000000000000000

Backtrace: 0x4008c674:0x3ffb1e20 0x400ed1c4:0x3ffb1e30 0x400ed245:0x3ffb1e60 0x400d06e7:0x3ffb1e80 0x400d084f:0x3ffb1f20 0x400d2b5a:0x3ffb1fb0 0x4008efde:0x3ffb1fd0

Rebooting...

The code is the following:
// Wifi and FTP Client Lib
#include <WiFi.h>
#include <WiFiClient.h>
#include "ESP32_FTPClient.h"

// MicroSD
#include "driver/sdmmc_host.h"
#include "driver/sdmmc_defs.h"
#include "sdmmc_cmd.h"
#include "esp_vfs_fat.h"

// FTP Server credentials
char ftp_server[] = "192.168.1.50";
char ftp_user[]   = "username";
char ftp_pass[]   = "password";

// wifi access
const char* ssid = "ssid";
const char* password = "psk";

// file to be read and uploaded
FILE *fileUpload = NULL;

// ftp client object
ESP32_FTPClient ftp (ftp_server, ftp_user, ftp_pass);

// micro sd initialization
static esp_err_t init_sdcard()
{
  esp_err_t ret = ESP_FAIL;
  sdmmc_host_t host = SDMMC_HOST_DEFAULT();
  sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
  esp_vfs_fat_sdmmc_mount_config_t mount_config = {
    .format_if_mount_failed = false,
    .max_files = 10,
  };
  sdmmc_card_t *card;
  ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card);
}

void FTP_upload( void );
void FTP_upload()
{

  // initialize file name
  char fileName[100];
  sprintf(fileName, "/sdcard/img.png");
  fileUpload = fopen(fileName, "r+");

  // notify reading of the file
  Serial.print("Reading file: ");
  Serial.println(fileName);
  if (fileUpload == NULL)
  {
    Serial.println("Cannot open file");
    return;
  }

  // retrieve file size
  fseek(fileUpload, 0, SEEK_END);
  long int size = ftell(fileUpload);
  fclose(fileUpload);

  // print file size to serial
  Serial.print("File size: ");
  Serial.println(size);

  // Reading data to array of unsigned chars
  fileUpload = fopen(fileName, "r+");
  unsigned char * in PROGMEM = (unsigned char *) malloc(size);

  // display allocated memory
  Serial.print("Allocated memory: ");
  Serial.println(sizeof(in));

  // read file to allocated memory
  int bytes_read = fread(in, sizeof(unsigned char), size, fileUpload); // <------- THIS ROW RISES THE ERROR

// close file
  fclose(fileUpload);

  // Open FTP connection
  Serial.println("Starting FTP upload...");
  ftp.OpenConnection();

  //Create a file and write the image data to it;
  ftp.InitFile("Type I");

  // change remote directory
  ftp.ChangeWorkDir("/Shared/");

  // specify remote file name
  String strNome = "img.png";

  // convert String to char
  const char *f_name = strNome.c_str();

  // create a new file with the given name inside the remote directory
  ftp.NewFile( f_name );

  // write data read above from local file to remote file
  ftp.WriteData(in, sizeof(in));

  // close remote file
  ftp.CloseFile();

  // notify completed upload
  Serial.println("File uploaded successfully");

  // wait
  delay(100);

}

void setup() {

  // begin serial communication
  Serial.begin(115200);

  // initialize micro sd
  esp_err_t errSD = init_sdcard();
  if (errSD != ESP_OK) {
    Serial.printf("Cannot initialize SD. Error code: 0x%x", errSD);
    return;
  }

  // begin wifi connection
  WiFi.begin(ssid, password);

  // wait for the connection to be estabilished
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // notify successful connection
  Serial.println("");
  Serial.println("WiFi connected");

  // show the assigned IP
  Serial.print("IP: ");
  Serial.println(WiFi.localIP());

  // call the FTP upload procedure
  FTP_upload();

}

void loop() {
  // empty
}

How can I solve this? Thank you

This line doesn't make sense to me: unsigned char * in PROGMEM = (unsigned char *) malloc(size); Either it's in PROGMEM, or it's on the heap. It can't be both. [I don't think that's your problem though, since PROGMEM doesn't exist on the ESP32 ASFAIK]

Heh, that's all we need: progmalloc().  Or is it malloc_P() ? =)  I haven't checked the ESP32, but usually non-AVR cores have dummy F(), PSTR(), PROGMEM, pgm_read_whatever, etc  that just put things the only address space they have.  So there's kind of a notion of having them in the sense that they don't cause errors for unrecognized identifiers.

@timemage That's exactly what I think, yes. In the program above, it may not do anything, but it's just wrong. The data needs to be read to the normal RAM.

@PMF, ah, that makes sense. I'd had a different reading of it before.

@PMF yes sorry, that was an error that I missed, indeed. Removing PROGMEM didn't change anything though. @timemage what do you mean? I successfully used malloc in another code, so I can confirm it gets recognized by the ESP32 core.

Is sizeof(unsigned char) = 1? If it was not, this would explain the crash.

@PMF, for char, regardless of how signedness is (or isn't) specified, sizeof will always yield 1.  It's sort of definitional in the standard.  Basically, the way it's specified, what sizeof returns is the number of char needed to represent something where char is made synonymous with "byte", regardless of whether or not bytes are octets.

@timemage Thanks for the explanation. I wasn't sure about this any more. I'm mainly a C# programmer, where sizeof(char) is just not 1, because strings are by definition unicode.

Solved, I changed the method a little.
In a loop, I read a portion of the file and write it to the opened FTP remote file, then I close both at the end of the cycle
// open FTP connection
ftp.OpenConnection();

// open local file
fileUpload = fopen("/sdcard/img.png", "r+");

// initialize file type
ftp.InitFile("Type I");

// change remote directory
ftp.ChangeWorkDir("/Shared/");

// define remote file name
String strName = "img.png";

// convert to char
const char *f_name = strName.c_str();

// create remote file with given name
ftp.NewFile( f_name );

// read all file in a loop
unsigned char buff[64];
while(!feof(fileUpload)){

    // read a portion of the file
    fread(buff, sizeof(char), sizeof(buff), fileUpload);

    // write that portion to the remote file
    ftp.WriteData(buff, sizeof(buff));
}

// close both the local and the remote file
fclose(fileUpload);
ftp.CloseFile();

It would be good to get a more specific explanation of the cause.  One thing you did was move away from malloc() which is a good idea.  In the process it seems you fixed a memory leak that was caused by not having a corresponding call to free().  You also got rid of ftp.WriteData(in, sizeof(in));, which was writing only the first 4 four bytes of what in points to, because sizeof (in) is the sizeof of the pointer, not the size of the allocated block.

For what remains, there's the possibility of fopen failing, which you should probably check before trying to use fileUpload.  When it comes to feof and fread it's important to know that feof doesn't tell you when you're at the end of the file.  It tells you when you tried to read past the end of the file.  So to make the loop correct, you'd need to first attempt an fread, then check to see if it failed because of an EOF condition, and then either break the loop or write the data.

@timemage The reason for this solution is that the row fread(in, sizeof(unsigned char), size, fileUpload); tries to read size elements (size is the full size of the file) and tries to put those elements in the in char, but in char has only 4 bytes, regardless the malloc function.

If you show up on freenode sometime, I'd go into what I'm thinking about that.  For here, I'll just say I think you may need to keep looking at it a bit longer.


text:
Hexadecimal array does not add up as expected
I have an array of hexadecimal values as given below.
byte Hexa_Val[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

I want to increase this array from the end. As in, go from {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} all the way to {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, and then increase the value next to it to {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, and continue. The increment should go as shown below.
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}
.
.
.
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}
.
.
.
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}
{0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00}
.
.
.
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}

The code I am came up with is
byte Hexa_Val[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

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

void loop() {

  Hexa_Val[7] = Hexa_Val[7] + 1;

  if(Hexa_Val[7] = 0xFF){
    Hexa_Val[6] = Hexa_Val[6] + 1;
    Hexa_Val[7] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF)){
    Hexa_Val[5] = Hexa_Val[5] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF)){
    Hexa_Val[4] = Hexa_Val[4] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF)){
    Hexa_Val[3] = Hexa_Val[3] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF) && (Hexa_Val[3] = 0xFF)){
    Hexa_Val[2] = Hexa_Val[2] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
    Hexa_Val[3] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF) && (Hexa_Val[3] = 0xFF) && (Hexa_Val[2] = 0xFF)){
    Hexa_Val[1] = Hexa_Val[1] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
    Hexa_Val[3] = 0x00;
    Hexa_Val[2] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF) && (Hexa_Val[3] = 0xFF) && (Hexa_Val[2] = 0xFF)  && (Hexa_Val[1] = 0xFF)){
    Hexa_Val[0] = Hexa_Val[0] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
    Hexa_Val[3] = 0x00;
    Hexa_Val[2] = 0x00;
    Hexa_Val[1] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF) && (Hexa_Val[5] = 0xFF) && (Hexa_Val[4] = 0xFF) && (Hexa_Val[3] = 0xFF) && (Hexa_Val[2] = 0xFF) && (Hexa_Val[1] = 0xFF)  && (Hexa_Val[0] = 0xFF)){
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
    Hexa_Val[5] = 0x00;
    Hexa_Val[4] = 0x00;
    Hexa_Val[3] = 0x00;
    Hexa_Val[2] = 0x00;
    Hexa_Val[1] = 0x00;
    Hexa_Val[0] = 0x00;
  }

  //to find out what I am sending
  for( byte a=0; a<8; a++ ) {
    Serial.print(Hexa_Val[a], HEX);
  }
  Serial.println();

  delay(500);

}

But it just gives me zeros in the serial monitor. If I just leave the first two IF statements
byte Hexa_Val[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

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

void loop() {

  Hexa_Val[7] = Hexa_Val[7] + 1;

  if(Hexa_Val[7] = 0xFF){
    Hexa_Val[6] = Hexa_Val[6] + 1;
    Hexa_Val[7] = 0x00;
  }

  if((Hexa_Val[7] = 0xFF) && (Hexa_Val[6] = 0xFF)){
    Hexa_Val[5] = Hexa_Val[5] + 1;
    Hexa_Val[7] = 0x00;
    Hexa_Val[6] = 0x00;
  }

  //to find out what I am sending
  for( byte a=0; a<8; a++ ) {
    Serial.print(Hexa_Val[a], HEX);
  }
  Serial.println();

  delay(500);

}

The increment will start from the third value on the right. Something like
00000200
00000300
00000400
00000500
00000600
00000700

How do I get it to increase as I mentioned at the beginning? Why does the code recognize 0xFF as a zero?

Your second (and following) if compares Hexa_val[7] with 0xFF, but the first has already reset it to 0.

Boy, I feel an itch to write assembly code that does that without branching.

There are multiple problems here:

if(Hexa_Val[7] = 0xFF)

First of all, = is the assignment operator. You are setting
Hexa_Val[7] to 0xFF. If you want to compare for equality, you should
use ==.
Second problem, The value 0xff will never be displayed, because you
are replacing it by zero. This byte will then count 0xfd, 0xfe, 0x00,
skipping 0xff. If you want to count 0xff, the condition should be
Hexa_Val[7] == 0, i.e. increment Hexa_Val[6] only after
Hexa_Val[7] has overflowed.
Third problem, your second if test comes too late. At this point
Hexa_Val[7] has already been reset. You should test for Hexa_Val[6]
overflowing only within the previous test.
With all that fixed:
Hexa_Val[7] = Hexa_Val[7] + 1;
if (Hexa_Val[7] == 0) {
  Hexa_Val[6] = Hexa_Val[6] + 1;
  if (Hexa_Val[6] == 0) {
    Hexa_Val[5] = Hexa_Val[5] + 1;
  }
}

If you don't want to write 8 nested conditions (which is kind of
cumbersome), you can instead loop over the array backwards, incrementing
each element in turn, and break out of the loop as soon as an increment
does not overflow:
for (int i = 7; i >= 0; i--) {
    if (++Hexa_Val[i] != 0) break;
}

If you don't mind the array being backwards, you can also handle the
whole array as a single 64-bit number, and just increment it like you
would increment any integer. But then you have to print the array
backwards, starting from the mast element:
union {
    uint64_t number;
    byte bytes[8];
} Hexa_Val = { .number = 0 };

void loop() {
    // Increment the array.
    Hexa_Val.number++;

    // Print out.
    for (int i = 7; i >= 0; i--) {
        if (Hexa_Val.bytes[i] < 0x10) Serial.write('0');
        Serial.print(Hexa_Val.bytes[i], HEX);
        Serial.write(' ');
    }
    Serial.println();

    delay(500);
}


text:
send images from Arduino Uno to raspberry pi
I am a new to work with ov7670 camera module and Arduino . please let me know whether it could be possible to send images captured from ov7670 module with Arduino Uno to Raspberry pi??

Wouldn't it be easier to connect the OV7670 directly to the Raspberry Pi?

It really would be way easier to directly use the Pi's camera interface and ditching the Uno. The Uno is not good for handling images, though it is generally capable of doing it (in limits). If you want to go on vacation you wouldn't try to tow your car with a boby car to the destination. You would directly use the car itself, because it is way more capable.

Thanks for your response :) .But would it be possible to connect ov7670 to raspberry pi directly?? In some websites I saw that 0V7670 is a arducam and doesn't compatible with raspberry pi ?? Isn't it ? Pls let me know ASAP .


text:
Arduino simulator - generating sine wave from PWD (Oscilloscope read is rectangular)
trying to create this simple circuit where a rectangular voltage input is transferred to a sine wave output.
the process is quite simple, but I couldn't see the actual sine wave when connecting an oscilloscope.
I'm currently working on a simulator online, so I thought it would be best to share the circuit with the c++ code, and perhaps you would have any insights on why I keep seeing rectangular output voltage rather than sine when the data is indeed a sine wave:
here's an image of the circuit for some specific time:

and the code that generates the sine wave is
#include <math.h>

const int numSamples = 500;
const float pi = 3.1415;
int f = 2; // signal frequency
float sf = 500.0; // sample frequency > 2*f (Nyquist)
int sineSignal[numSamples];

void setup(){
    pinMode(13, OUTPUT);
    // creating sine signal:
    for (int i = 0; i < numSamples; i++){
        float t = i / sf;
        // +1 shift to get values from 0 to 2
        sineSignal[i] = (int) (127 * (sin(2 * pi * f * t) + 1.0));
    }
}

void loop(){
    int pinToConnect = 9;
    for (int i = 0; i < numSamples; i++){
        analogWrite(pinToConnect, sineSignal[i]);
        delay(2);
    }
}

ps. this is all based on this video: How to Generate Sine Wave using Arduino?

It's working as intened.
The arduino UNO has no DAC (digital to analog converter) onboard, so all it can produce are digital signals, either 0 or 5v. The analogWrite function uses Pulse Width Modulation to produce an output that, on average, has the requested voltage, by quickly alternating between logic low and high with different durations.
This is done at the hardware level using the Atmega's timers, and it's very useful in driving LEDs, servos, steppers and more, but it doesn't produce a steady analog output.
I would suggest either moving to a chip that has an onboard DAC, using an external DAC chip such as this one, or building a simple DAC yourself.
An even simpler solution would be building a RC lowpass filter on the output pin, which would provide a simple, but probably imprecise, way to smooth out the signal and make it look like an analog one

The light you see from the LED is averaged out by your eye, which can't really see the frequencies in the hundreds of Hz used by Arduino's PWM. The oscilloscope, on the other hand, is triggered on rising/trailing edges and has a much higher resolution, so it will show more details at high frequency. Hypothetically, if you filmed the LED in slow motion, you would be able to see it turn on and off repeatedly


text:
How to make ultrasonic and light sensors detect whether a person moving in or out
I am trying to make a circuit that will be used for turning on a light whenever there are 1 or more people in a room. I need to add to a variable counter when someone enters and subtract when someone leaves. However, I do not know how to use the ultrasonic sensor for this purpose. What can I do?

Google. If you know how to use the Ultrasonic sensor and know the C++ basics, this will be very easy.

How do you find out whether the person is entering or exiting

Is there some distance change thing

You'd have to place two Sensors next door, and if both are triggered, someone got in or out. You can check whether the person went in or out by looking what Sensor was triggered first.

thanks for the help

but it will always detect some distance so I need to check if the distance is less than a certain amount

Yes, you have to expermient a little bit with it to find the best value.

Unless the person swings his hand around

Then you'd have to use a camera + Raspberry Pi.

Let us continue this discussion in chat.

See this tutorial on the Arduino Projecthub, that project was already made. Here is a tutorial how to use a Ultrasonic sensor.


text:
LED Blink in assembly with timer1 output compare interrupt not working
I was trying to have some fun with avr-assembly on my arduino and I tried the following codes to blink my LED
first I tried the ISR approach and when It didn't work I tried the CTC mode one,
both codes are listed respectively. on the first one the LED lightsup and stay that way (no blinking) on the second one it just stays off
one more thing to note is on trying to load OCR1AL first The led would blink nicely if my hand got near PORTD pins for some reason,
I guessed it's some grounding problem and It's fixed when I pulled high all PORTD pins and it disappeared completely when I figured out that I need to load (the high byte) OCR1AH first
.nolist
.include "m328Pdef.inc"
.list

.org    0x0000
jmp     Init

.org    0x0016
jmp     TIMER1_COMPA

.EQU    LED_PIN = PB1

Init:
    ;ldi    r16, 255
    ;out        DDRD, r16
    ;out    PORTD, r16

    ;First configure The led pin as output and initilize it to high
    sbi     DDRB, LED_PIN
    sbi     PORTB, LED_PIN

    ;Second Enable Global Interrupts
    sei

    ;Enable the Output compare Interrupt in the TIMSK1 Register
    ldi     r16, 0b00000010
    sts     TIMSK1, r16

    ; Reset the TCCR1A
    ldi     r16, 0b00000000
    sts     TCCR1A, r16

    ; Set the prescalar to 256 in the Timer Control 1B register
    ldi     r16, 0b00000111
    sts     TCCR1B, r16

    ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
    ldi     r16, 0b00111101
    ldi     r17, 0b00001001
    sts     OCR1AH, r16
    sts     OCR1AL, r17

LOOP:

    rjmp    LOOP

TIMER1_COMPA:
    ;First Reset the coutner
    ldi     r16, 0
    sts     TCNT1H, r16
    sts     TCNT1L, r16

    ;Second Toggle the Pin (LED) state
    sbi     PINB, LED_PIN

    reti

CTC:
.nolist
.include "m328Pdef.inc"
.list

.org    0x0000
jmp     Init

.org    0x0016
jmp     TIMER1_COMPA

.EQU    LED_PIN = PB1

Init:
    ;ldi    r16, 255
    ;out        DDRD, r16
    ;out    PORTD, r16

    ;First configure The led pin as output and initilize it to high
    sbi     DDRB, LED_PIN
    sbi     PORTB, LED_PIN

    ;Second Enable Global Interrupts
    sei

    ;Enable the Output compare Interrupt in the TIMSK1 Register
    ldi     r16, 0b00000010
    sts     TIMSK1, r16

    ; Reset the TCCR1A
    ldi     r16, 0b01000000
    sts     TCCR1A, r16

    ; Set the prescalar to 256 in the Timer Control 1 registers
    ldi     r16, 0b00001111
    sts     TCCR1B, r16

    ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
    ldi     r16, 0b00111101
    ldi     r17, 0b00001001
    sts     OCR1AH, r16
    sts     OCR1AL, r17

LOOP:
    rjmp    LOOP

TIMER1_COMPA:
    ;First Reset the coutner
    ;ldi    r16, 0
    ;sts    TCNT1H, r16
    ;sts    TCNT1L, r16

    ;;Second Toggle the Pin (LED) state
    ;sbi        PINB, LED_PIN

    reti

I am not set up to test your code right now, perhaps later.  But:
    ; Set the prescalar to 256 in the Timer Control 1B register
    ldi     r16, 0b00000111
    sts     TCCR1B, r16

When set to ones, the low order three bits of TCCR1B, select an external clock source at the T1 pin, for clocking on a rising edge.  Probably what's happening is that when you finger is near enough the T1 pin you are capacitively coupling mains frequency to it causing it to tick.
/256 prescaler would have 100 in the lower three bits.
If I manage to get a proper environment up to test your code, I'll look into it a bit more thoroughly.

OPS, Yup that Was it although I read the datasheet and saw that it was 100 don't know how it ended up as 111. anyway as a suggestion for an environment I use avrdude and avra assembler on linux mint terminal with the arduino uno

and the main frequency in my country is around 60 HZ and the LED clearly didn't blink on that frequency it was fast but not that fast at all. How is that? is there an explanation for the altered frequency?

Well, the frequency of what appears on T1 is being effectively divided by what you're doing with your ISR/TCNT1/OCRA1A; one cycle on T1 is not one execution of sbi PINB, LED_PIN, and each toggling corresponds to just the high or just the low period of the LED cycle.  Then, you might also have high frequency components being seen at T1.  If you wanted to experiment with that, the thing to do would be to feed a solid 60Hz into T1 to eliminate the unknown components there.   By the way, your ISR should probably be preserving r16.


text:
Receiving code between atmega328P (C) and Feather m0 (Arduino)
I've tried to create a receiver code for receiving my data (really only want the ac/gy values and nothing else) and use the following main code for sending via C programming: https://github.com/YifanJiangPolyU/MPU6050/blob/master/main.c
the sending receiving code in Arduino this far is the following (that doesn't work):
void do_send(osjob_t* j){
    // Check if there is not a current TX/RX job running
    if (LMIC.opmode & OP_TXRXPEND) {
        Serial.println(F("OP_TXRXPEND, not sending"));
    } else {
        // Prepare upstream data transmission at the next possible time.

byte strArray[30];
    int i = 0;
    if(Serial1.available()>0) {
       while (Serial1.available()>0){
          strArray[i] = Serial1.read();
          i++;
       }
            // send the 6 bytes payload to LoRaWAN port 7 --> now port 1
            LMIC_setTxData2(1, strArray, sizeof(strArray), 1); //might need to be converted to type data, not char.

            digitalWrite(LED_BUILTIN, HIGH);    // turn the LED on by making the voltage HIGH                      //optional: for confirmation
    }
        }
    }
    // Next TX is scheduled after TX_COMPLETE event.
    //delay(60000);

I've noticed that I cannot send char arrays with LMIC function for the feather m0, so I tried receiving it as a byte array which works to send. Any help/suggestions/snippets of code etc. would be greatly appreciated.

https://majenko.co.uk/blog/reading-serial-arduino


text:
Rocket deploy system
I found a code from Astronomica Messier that allows to activate a servo from a Gyroscope MPU 6050 change in direction. I followed the wiring and uploading correctly. The thing is that the MPU is initializing but the connection is failing. Could you help me please to figure out whats happening here? I'm using a GY-86, an Arduino Nano and a Micro Servo 9g. Here's the code. Thank you.
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Servo.h"

MPU6050 mpu;
int16_t ax, ay, az;
int16_t gx, gy, gz;
Servo servo1;

int val1;
int prevVal1;

void setup()
{
Wire.begin();
Serial.begin(38400);
Serial.println("Initialize MPU");
mpu.initialize();
Serial.println(mpu.testConnection() ? "Connected" :
"Connection failed");
servo1.attach(9);
}

void loop()
{
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
val1 = map(ax, -17000, 17000, 120, 10);
if (val1 != prevVal1)
{
servo1.write(val1);
prevVal1 = val1;
}
delay(50);
}

Have you tried using an i2c scanner to see if the gyro is detected on the bus?

Missing pullups are a common problem when struggling with i2c, but they might be included on the sensor module. Giving a link to the module you ctually use will help to odd this out.


text:
Using an accelerometer with an Arduino as a shock sensor
I really need some help.  I have absolutely no experience with accelerometers and have a project that would work great if I could integrate one into it.  I am not hinting to have some write me a code, just get me looking in the right direction.
My code (below) was written to work with 2 buttons and an LED.  Basically, its nothing but a reaction timer using an RGB liquid crystal display.
Sequence of events...

power on
displays “push button to start”
when panel button is pushed, the loop begins by randomly selecting a
“FIRE” time when “fire” button is pressed, it echoes the time it
took
my FOR statement, allows it to loop three times before returning to
the begin.

This was all what I set out to accomplish, originally.  My sister has been using it at a retirement home for some of the patients to play with.  Lately she asked if instead of a “fire” button it could be programmed to simply, tap the whole unit, push the unit, or even use a tether of some sort.  I figured an accelerometer was the ticket.
I purchased an ADXL345, I tried playing with several sketches from GitHub.  What I find is the accelerometer is ALWAYS giving out information. I thought it would actually “rest” when not being physically moved.
How can I use my ADXL345 to be at  complete standstill, until it is “moved,” that it would activate a WHILE statement???
#include <Wire.h>
#include <LiquidCrystal.h>
#include <SparkFun_ADXL345.h>

ADXL345 adxl = ADXL345();
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

int lcdRedPWMPin = 17;
int lcdGreenPWMPin = 16;
int lcdBluePWMPin = 15;

void setDisplayRGB(int r, int g, int b)

{
  analogWrite(lcdRedPWMPin,   r);
  analogWrite(lcdGreenPWMPin, g);
  analogWrite(lcdBluePWMPin,  b);
}

void setup()
{
  lcd.begin(16, 2);
  lcd.clear();
  pinMode(13, OUTPUT);
  Serial.begin(115200);
  adxl.powerOn();
  adxl.setRangeSetting(2);    // Accepted values are 2g, 4g, 8g or 16g
  //adxl.setSpiBit(0);
  adxl.setActivityXYZ(1, 1, 1);
  adxl.setActivityThreshold(70);
  adxl.ActivityINT(1);
  pinMode(13, INPUT);
  digitalWrite(13, LOW);

  pinMode(9, INPUT); //panel button
  digitalWrite(9, HIGH);

  pinMode(8, INPUT); //FIRE button
  digitalWrite(8, HIGH);

  pinMode(10, OUTPUT); //FIRE led
  digitalWrite(10, LOW);

  // int    fireButton = digitalRead(8);
  int    panelButton = digitalRead(9);
  lcd.clear();
  setDisplayRGB(100, 100, 75);
  lcd.setCursor(1, 0);
  lcd.print("Let's see what");
  lcd.setCursor(1, 1);
  lcd.print("what you got!");
  delay(2000);
}
double timeToFire = 0; //time it took to (fire-trigger)
double fireTimerStarts = millis(); //fire (timer starts)
double triggerTimerStops ; //trigger (timer stops)
int ran; //random

void loop()
{

  int x, y, z;
  adxl.readAccel(&x, &y, &z);
  // byte interrupts = adxl.getInterruptSource();
  int average = (x + y + z);

  while (digitalRead(9) == HIGH)
  {
    lcd.clear();
    setDisplayRGB(40, 200, 75); //purple 40,200,75
    lcd.setCursor(0, 0);
    lcd.print("Press Button");
    lcd.setCursor(0, 1);
    lcd.print("to Start ...");
    delay(50);
  }
  for (int panelButton = 0; panelButton < 3; panelButton++)

  {
    lcd.clear();
    lcd.setCursor(0, 0);
    setDisplayRGB(255, 255, 0); //blue
    lcd.print("  ---READY---");
    delay((int)random(1000, 5000));
    {
      ran = random(1, 3);
      Serial.println(ran);
      if ( ran == 1)
        lcd.clear();
      lcd.setCursor(0, 0);
      setDisplayRGB( 0, 155, 155 );  //red
      lcd.print("     <FIRE>   ");
      lcd.setCursor(0, 1);
      lcd.print(average);
      fireTimerStarts = millis();
      digitalWrite(10, HIGH);

      // if(adxl.triggered>activityThreshold)

      while (adxl.triggered(13, HIGH))

        //while (digitalRead(8) == HIGH)
      {
        triggerTimerStops = millis();
      }
      digitalWrite (13, LOW);
      digitalWrite(10, LOW);

      setDisplayRGB(100, 100, 225); //green
    }
    timeToFire = (triggerTimerStops - fireTimerStarts) / 1000;

    delay(500);
    {
      lcd.clear();
      setDisplayRGB(0, 255, 0);
      lcd.setCursor(0, 1);
      lcd.print(timeToFire);
      lcd.setCursor(11, 1);
      lcd.print("Sec's");
      lcd.setCursor(0, 0);
      lcd.print("Your time was ...");
      delay(1500);
    }
  }

}

An alternative to using an accelerometer is a simple Vibration Sensor Switch. Adafruit has a Fast Vibration Sensor Switch: https://www.adafruit.com/product/1766, Medium Vibration Sensor Switch: https://www.adafruit.com/product/2384 and a Slow Vibration Sensor Switch: https://www.adafruit.com/product/1767, each costing 1 USD.
Edit 1:
If you look for "ADXL345_ACTIVITY" in the SparkFun_ADXL345_Example.ino sketch, there is a comment that says "add code here to do when activity is sensed".
My suggestion is to get the ADXL345 working with this sketch first, then start removing the excess code from it that you don't need. Once you have the bare minimum code required to accomplish your goal, try to integrate that with you current sketch.
There are several "sensitivity adjustments" you can make under the "Configure ADXL345 Settings" section of the code.

Honestly VE7JRO, until you posted this response, I didn't know these things even existed.  Of course going to the Adafruit website, I didn't know lots of that stuff existed.  Your idea would work great, but I am at war with this accelerometer right now and not giving up quite yet.

I purchased an ADXL345, I tried playing with several sketches from GitHub. What I find is the accelerometer is ALWAYS giving out information. I thought it would actually “rest” when not being physically moved.

The accelerometer reports its current acceleration on each axis at all times, whether that acceleration is changing or not. When at rest and upright, it will report close to 1.0 g on the Z axis; when rotated to some other direction and held steady, the vector magnitude of the accelerations on the three axes will be close to 1.0. The vector magnitude is computed as the square root of the sum of the squares of the elements, so rather than averaging, you'll want to do this:
int x, y, z;
adxl.readAccel(&x, &y, &z);

float mag = sqrt( x*x + y*y + z*z );

This mag value should change only slightly if you gently rotate the accelerometer. That baseline value represents 1.0g of acceleration from Earth's gravity.
A rapid motion of the accelerometer will produce some higher or lower value, briefly. Figure out what threshold makes sense for your application and do something like:
if (mag > (BASELINE_GRAVITY * 1.2f))
{
    lcd.setCursor(0, 0);
    lcd.print("You moved!");
}

Thank-you for your response Russell.  What would "BASELINE_GRAVITY" be defined as?

I wasn't able to determine that from a glance at the documentation -- it's unclear to me what units are returned by the adxl library.. It's whatever mag averages when the accelerometer is stationary.

According to the datasheet of adxl345, this chip (so the module) has single-tap, double-tap functionality. As described in the datasheet, you can configure the chip as you want it to operate. The chip has 2 interrupt pins. When it is configured to operate one of the tap modes and senses the tap, it gives an interrupt signal. You can check that signal and process the information.

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


text:
Atmega328p with arduino without the board
Perhaps this is a beginners question and I am not sure. I currently have a custom made circuit with an atmega328p chip connected to an mpu6050. However, when I program in Arduino I am not sure what to do? I can't pick a "board" as the atmega328p doesn't belong to a board? (from what I'm aware at least)
How in Arduino do I choose to program for my atmega328p chip? Without having to pick a board such as Arduino Uno etc. As I don't have any board for this. Or does the atmega328p chip always belong to a certain board?
I have a fully working circuit with a cyrstal (16MHz), battery sources, atmega328p etc. But I don't know how to program it with Arduino? I can program it in C, but would like to use Arduino due to certain libraries.

Does that 328P have the optiboot bootloader, like an Uno?

The board option is actually selecting a variant out of the installed cores (which provide the basic Arduino framework for a group of boards/chips). Each core can support multiple variants/boards/chips and can give each of them individual lists of options. There certainly also is a core, which supports the Atmega328p with all needed config options (like the frequency setting). You just need to install it from the boards manager.
Though, since you use a 16MHz crystal just like the Uno/Nano, you could just select the Uno or Nano as board. Neither the Arduino IDE, nor the Atmega328p can know, that the Atmega is actually a standalone one and not mounted on an Arduino board. So you can just use that board when you keep the config options inherent to an Arduino Uno/Nano (frequency setting and pin mapping mainly).


text:
Is it possible to extract the firmware of an Arduino BLE or IoT board wirelessly?
I've looked at previous questions regarding sketch extraction and know that it is possible to extract the hex code from an Arduino board using avrdude from the command line.
However, I want to see if the following is possible:

Connect to Arduino 33 IoT board
Extract onboard Firmware as a hex file
Disconnect from Arduino 33 IoT board.

I understand that getting the initial source code is not possible, but I am in particular looking to just get the hex code in a wireless manner. If it is not possible via the Arduino 33 IoT board, is there any Arduino board with which this can be done? Any help or guidance would be appreciated.

Technically, the firmware can read its own application section, but it won't send it to you wirelessly (or via any interface) if such a feature isn't implemented in that firmware. If you were to implement the firmware yourself, you can do (almost) anything. But if it is a third party firmware, this will not be possible.
The reason this works with arduinos and avrdude is, because firmware up- and download are implemented in hardware (ISP, works without a bootloader).

Thank you for the answer. Just to be sure, you're saying that for any Arduino device the methodology I stated in my initial question is just not possible unless I code it myself into the firmware beforehand?

@TjHasan Yes, that's it...


text:
Recover .ino file from tmp files?
Is it possible to recover an .ino file/sketch in/for Arduino? I really need my file back, but ones i uploaded it to my device it vanished from the sketch folder, nor can I find it in the build folder; however, a ton of TMP files are left. Is it possible to use those to recover my .ino file?
They're named something like filename.ino1238437381212.TMP

Have you looked in them to see what they contain?

It would seem that all the 20 files contains the old code I was looking for... Do you know why I get so many tmp files with the same code in?

I would strongly encourage using some form of source control.

Well, stupidly enough, the missing code was inside of the TMP files... in all of them...

I gather that you solved your problem.  I'm guessing someone reading this with the same probably would want to know more though.  You must have learned something useful between the question and answer, what was that?


text:
Reading a flash ROM chip (M45PE20) through SPI with an ATMEGA 2560 -- output only FF's
I'm trying to communicate through SPI to a Flash ROM chip (M45PE20) with an ATMEGA 2560. I'm looking to read the data off the chip, but the output I'm getting is nothing but FF's. I've checked my wiring and everything looks okay on that end, I also don't have a scope to probe the output unfortunately.
I've the crude code below:
void setup() {
  Serial.begin(9600);
  pinMode(SS, OUTPUT);
  digitalWrite(SS, HIGH);
  SPI.begin();
}

void loop() {
  Serial.println("Starting");
  Serial.println("Waiting 1s");
  delay(1000);
  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));

  digitalWrite(SS, LOW);
  Serial.println(SPI.transfer(0x03));
  Serial.println(SPI.transfer(0x00));
  Serial.println(SPI.transfer(0x00));
  Serial.println(SPI.transfer(0x00));
  for (int i = 0; i < 16384; i++) {
    Serial.print(i * 32, HEX);
    Serial.print(" ");
    for (int j = 0; j < 32; j++) {
      Serial.print(SPI.transfer(0xFF), HEX);
      Serial.print(" ");
    }
    Serial.println();
  }

  Serial.println();
  digitalWrite(SS, HIGH);
  delay(500);
  SPI.endTransaction();
  delay(5000);
}

Link to datasheet: https://drive.google.com/file/d/1_Zlg-hb5B08u7_m_N4_addmmjyv_nANS/view?usp=sharing
Picture of specific read command from datasheet:

Can you provide a wiring diagram? Also, a blank/new chip will be full of 0xFF.

I will update my post tomorrow evening, this is part of a game cartridge so the wiring is going to be a bit weird looking.
I can also confirm that the chip is filled with random data, and not full of 0xFF.


text:
Error Performing HTTP GET request on google sheets (Apps Script) using TTGO T-CALL
I've tried using several libraries such as TinyGSM, SoftwareSerial, AT commands but I'm guessing the problem to be with my GET request url is https://script.google.com/macros/s/GAS_ID/exec?tag=1234&value=5678 and the Apps Script code is
   function doGet(e){
      Logger.log("--- doGet ---");

      var tag = "",
      value = "";

   try {

// for debugging
if (e == null){e={}; e.parameters = {tag:"test",value:"-1"};}

tag = e.parameters.tag;
value = e.parameters.value;

// save the data to spreadsheet
save_data(tag, value);

  return ContentService.createTextOutput("Wrote:\n  tag: " + tag + "\n  value: " + value);

   }
 catch(error) {
   Logger.log(error);
return ContentService.createTextOutput("oops...." + error.message
                                        + "\n" + new Date()
                                        + "\ntag: " + tag +
                                        + "\nvalue: " + value);
        }
      }

     // Method to save given data to a sheet
    function save_data(tag, value){
    Logger.log("--- save_data ---");

    try {

    // Paste the URL of the Google Sheets starting from https thru /edit
    // For e.g.: https://docs.google.com/..../edit
     var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/SPREAD_SHEET_ID/edit#gid=0");
var dataLoggerSheet = ss.getSheetByName("Sheet1");

// Get last edited row from DataLogger sheet
var row = dataLoggerSheet.getLastRow();

// Start Populating the data
dataLoggerSheet.getRange("A1").setValue(tag);
dataLoggerSheet.getRange("B1").setValue(value);
  //dataLoggerSheet.getRange("C" + row).setValue(tag); // tag
       /// dataLoggerSheet.getRange("D" + row).setValue(value); // value

    }

        catch(error) {
           Logger.log(JSON.stringify(error));
         }

         Logger.log("--- save_data end---");
          }

I've already tested the HTTP GET requests on other websites so there seems to be no problem with the device.
BTW this code (Apps Script) worked perfectly with nodeMCU with appropriate libraries and arduino code.
Please help me out.

What is the error?

please format your code properly ... the way it is now, the code indentation is awful, which makes the code unclear without doing copy and format


text:
SD Card Library interferes with Adafruit
Im currently working on a datalogger that uses oled i2c displays and current sensors. Both of them uses adafruit libraries. To write the data, im using arduino's sd library, but somehow, the sd library interferes with my i2c components that they won't work while sd card functions work. adding any sort of code from the sd library would completely make the i2c components malfunction. To test this, i tried to view 2 different text in 2 different i2c displays.
Here's the current code where the i2c components work :
#include <Adafruit_SSD1306.h>
#include "SdFat.h"

#define OLED_RESET 4
Adafruit_SSD1306 Display1(OLED_RESET);
Adafruit_SSD1306 Display2(OLED_RESET);

int i, j;

void setup()   {

  //Serial.begin(9600);

  Display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  Display1.clearDisplay();
  Display1.display();

  Display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
  Display2.clearDisplay();
  Display2.display();

}

void loop() {

  Display1.setTextSize(1);
  Display1.setTextColor(WHITE, BLACK);
  Display1.setCursor(0, 0 );
  Display1.println("Hello");
  Display1.display();
  Display1.clearDisplay();

  Display2.setTextSize(1);
  Display2.setTextColor(WHITE, BLACK);
  Display2.setCursor(0, 0);
  Display2.println("There");
  Display2.display();
  Display2.clearDisplay();

}

And here is the code where the components doesn't work
#include <Adafruit_SSD1306.h>
#include "SdFat.h"

#define OLED_RESET 4
Adafruit_SSD1306 Display1(OLED_RESET);
Adafruit_SSD1306 Display2(OLED_RESET);
SdFat SD;

int i, j;

void setup()   {

  //Serial.begin(9600);

  Display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  Display1.clearDisplay();
  Display1.display();

  Display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
  Display2.clearDisplay();
  Display2.display();

}

void loop() {

  Display1.setTextSize(1);
  Display1.setTextColor(WHITE, BLACK);
  Display1.setCursor(0, 0 );
  Display1.println("Hello");
  Display1.display();
  Display1.clearDisplay();

  Display2.setTextSize(1);
  Display2.setTextColor(WHITE, BLACK);
  Display2.setCursor(0, 0);
  Display2.println("There");
  Display2.display();
  Display2.clearDisplay();

}

Adding any sort of code that involves the sd card library like adding files or declaring the SD command itself would make the i2c components unusable, does anyone know how to fix this?

I don't see SD library in your sketch. You use SdFat

The same effects also happens with the SdFat Library

you run out of memory with the display buffers and the SD buffer

how can i test this? when i tried it with only 1 sensor and 1 display, it works well with writing the sd card. Not to mention there are no errors regarding memory when uploading the code to the nano

the memory is allocated at runtime so the build process can't evaluate it. the display library has buffer = (uint8_t *)malloc(WIDTH * ((HEIGHT + 7) / 8)))

There are no compilation errors for the memory issue, because the compiler can only calculate the global/static memory usage. The local variables are not counted there. Thags the reason why the Arduino IDE warns you at (I think) 75% memory usage. That it works with just one display supports the hypopyhsis of  running out of memory

Then how do i fix this?

A practical solution is probably to get an Arduino with more RAM.  There are a lot of those, but the Nano Every (6KB rather than 2KB) seems to make sense.  Some of the things I mentioned in answer to a similar question might be worth reading.  Even with them you might be at or over the limit though.


text:
AT+IPSCAN HC-05 Command
I have a HC-05 module, directly connected to an STM32 via UART interface and connected simultaneously to a mobile application in order to exchange
real time data. I am trying to reduce the power consumption of my HC-05 BT module. After few researches, I discovered that if I set the command AT+IPSCAN and
put the Query duration (2nd parameter) and the Call duration (4th parameter) to 1, the current dramatically decreases. Thus, the energy which the BT
module consumes decreases as well. My problem is I didn't understand how and why it decreases ? What are exatly the parameters AT+IPSCAN and what each one
does mean ?
Thank you for providing me a detailed description of the AT+IPSCAN command as well as its parameters.

https://s3-sa-east-1.amazonaws.com/robocore-lojavirtual/709/HC-05_ATCommandSet.pdf


text:
Prevent timeout while exchange data between two stm32
I am trying to exchange data (str data) between two STM32 throughout Lora connectivity. Both STM32 has a lora module and the connection between them is working fine. Based on two functions:
T_eError_eErrorType eDataPlane_eReceiveData_Cmd (uint32_t in_uiTimeout, uint8_t* out_pucData, uint8_t inout_pucLength, T_stSx1276_eRxPacketStatus out_pstRxPacketStatus)

T_eError_eErrorType eDataPlane_eSendData_Cmd (uint8_t* in_pucData, uint8_t in_ucLength)

I am trying to send and receive messages instantly. I discovered a huge problem: for example I am trying to send a data which has a duration equal to 300ms while the timeout of receiving the data is fixed to 3000 ms. It may, in one rare case, be a loss of such a data, when the data arrives at the time of 2800 ms of the timeout of the receiver. Such a problem is similar to the exchange of data in the UART interface when using the blocking mode (HAL_UART_Receive (&huart1, UART1_rxBuffer, 12, 5000);).
My question is how to garantee receiving the data without losing any byte and by using a receiving with timeout function.
Thanks in advance.


text:
How to switch HC-05 from DATA mode to AT mode?
I am asking how to enter from the data mode to the AT command mode without restarting and disconnecting any power supply. In other words, I am trying to make a driver to handle HC-05 module and now I have to switch between DATA mode to AT mode. When I try to switch backwards, it worls ( by putting off the EN pin and then send “AT+RESET” ) but from DATA mode to AT Mode I can’t reset the module. Anyhelp please ?

What Microcontroller do you use? You tagged both arduino uno and stm32

old time modems used to have an escape sequence that caused the modem to drop out of data mode into command mode ... the sequence was +++  .... the HC-05 may have something similar .... though, I suspect that a hardware pin is involved

@PythonSchlange I am using stm32

I am pretty certain there is no way to enter command mode from data mode without resetting the whole module.  The only way to enter command mode is by setting the KEY pin high, and that pin is only read during the initialization phase of the module - and that means either a power cycle / reset, or a command-initiated reset.
You could either:

Provide a power control circuit which turns the module on and off (MOSFETs are good for this), or
Modify the module to attach a wire to pin 11, the RESET pin, and pulse that LOW to reset into command mode (I assume LOW, since that's the most common, though I haven't found anything to confirm it yet).

Thank you for your response. I think that the best solution is the first one and I will search about a MOSFET type that responds to my application. Best,


text:
Issue with bluetooth and a large number LED strip
I want to be able to control multiple LED strip via bluetooth with one arduino.
I coded my own android app and everything work fine with one or two led strip with few pixel. But as soon as I had to many pixel data send by BT is missing a few byte (ex "colfff5dff" instead of "color fff5dff"). It doen't happen every time but it's unrealiable.
I feel like sending data to the led strip take so many time that it skip some letter.
I'm ussing dsd tech hc-05 with an arduino UNO R3 and a esp8266 led strip.
#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>

#ifdef __AVR__
 #include <avr/power.h>
#endif

//SoftwareSerial blueTooth(13,12);

#define PIN       5
#define SIZE      200

#define BRIGHTNESS 200

enum MODE {FIXED, LOOP_RGB, RUNNING, RAINBOW};
enum MODE mode = FIXED;

Adafruit_NeoPixel strip(SIZE, PIN, NEO_RGB + NEO_KHZ800);

int lastTime;

uint32_t color;
char Incoming_value = 0;
char bufferStr[100];
int bufferIndex = 0;

void setup() {

  Serial.begin(9600); //open the serial port
  Serial.setTimeout(10);
  strip.begin();
  strip.show();
  strip.setBrightness(50);

  color = Adafruit_NeoPixel::Color(0, 255 ,0 );
}

void loop() {
  if(Serial.available() > 0)
  {
    String s = Serial.readString();
    Serial.print(s);

    //I've tried some other way like read();  readString();  readBytes(); readBytesUntil();

    /*
     * ---- not needed for the issue
     */
  }
  switch (mode){
    case FIXED : fixedMode(); break;
    case RUNNING : runningLights(); break;
    case RAINBOW : rainbow(); break;
    }
    showAll();
}

void parseBlueTooth(){
  //---- not needed for the issue
}

void fixedMode(){
  setAll(color);
  showAll();
}

void rainbow(){
  //---- not needed for the issue
}

void runningLights() {
  //---- not needed for the issue
}

void setAll(byte r, byte g, byte b) {
  setAll(Adafruit_NeoPixel::Color(r,g,b));
}

void setAll(uint32_t color) {
  strip.fill(color, 0, SIZE);
}

void showAll(){
  long curTime = millis();
  if(curTime - lastTime >16){
    if(strip.canShow()) {
      strip.show();
    }
    lastTime = curTime;
  }

}

IMHO, after reading Majenko and raddevus reply,
you may do something to "reduce missing data"

reduce baud rate (may be 9600), give more time for bluetooth data transfer.

add a checksum byte for your data.

Rererence :
https://lucidar.me/en/serialib/most-used-baud-rates-table/

Your problem is that you are using two blocking routines that can't operate together. Both the SoftwareSerial and the NeoPixel objects take time to perform operations stopping anything else from happening.

SoftwareSerial blocks inside an ISR while receiving a byte
NeoPixel blocks with interrupts disabled while outputting the LED status

That means that while NeoPixel is being updated SoftwareSerial is incapable of receiving any data.  It was fine when you only had a few LEDs, since NeoPixel only took a very short time to update, but now that you have more LEDs it takes too long to update and SoftwareSerial can no longer work reliably.
In order to get around the problem you will have to use a hardware UART port. The Uno only has one - pins 0/1 and the Serial object. If you're not using that for communication with your computer you can connect your Bluetooth module there instead and use Serial instead of SoftwareSerial - however you will most probably need to disconnect your Bluetooth module every time you want to upload fresh code to your Arduino.

That's exactly what I did and it got better but not perfect.

Maybe you need to upgrade your Arduino to one that will update the NeoPixels using DMA instead of locking up the CPU.

I'm gonna try that, thanks for the information

I am working with HC-05 also and retrieving files over it.
I send commands and get files back over Bluetooth.  The speed of bluetooth should be fine.  (Although you need to set it faster -- mine's at 38400)
Up in your setup() loop do:
Serial.begin(38400)

Also your code to read off serial is a bit different.
You just need the following:
while (Serial.available()){
    command = Serial.read();
}

I was sending String-based commands but just today I decided to change them to 1 byte commands because it is much easier to deal with in a switch statement.  In the code above my command variable is a byte.
Then my switch looks like the following in loop():
switch (command){
    case 49: { // ASCII Char 1 - get Temperature
      SW_Serial.print(getString(currentRoom) + " : " + currentTemp);
      // CALL YOUR SPECIFIC CODE TO DO EACH THING IN EACH CASE
      break;
    }
    case 50: { // ASCII char 2 - start data write
      // #### Allow Data Write start/stop to be done via BT
      // turns on logging of temp data (to SD card)
      // turn on data writing and LED
      // CALL YOUR SPECIFIC CODE TO DO EACH THING IN EACH CASE
...

Of course, each time through the loop you should set your command variable back to 0 (I use 0 as the no-command).  Otherwise you'll keep processing on the same command value.


text:
Adafruit Thermal Printer unwanted gradient
I have thermal printer from adafruit and when printing images I have problems getting a proper black.
I tried playing with the dot print time and the dot feed time using the setTimes function, but this seem to have no effect.
  unsigned long dotPrintTime = 3000*30L;
  unsigned long dotFeedTime = 2100*30L;
  printer.setTimes(dotPrintTime, dotFeedTime);

Also the setHeatConfig seems to have no effect. I tried different values.
  uint8_t dots = 11;
  uint8_t _time = 120;
  uint8_t interval = 40;
  printer.setHeatConfig(dots, _time, interval);

Here an image of the result:

Is it possible to print fully black the whole width of the paper?

Does the test page you get from holding the button print correctly? How are you powering it?

I already recognized that the barcode also gets light grey, printing the full width. The adapter I am using is 2.4A and 5.0V.

Just to be clear, the barcode you're talking about is the QR code from the test page?

no it is not...

Alright, I don't know what you're saying, or why, or to whom.  The reason why I'm asking about the test page (as seen here) that you get from holding the power button is because the test page happens entirely under the printer's control, and not your code.  Which means if you have the problem with the test page, your code and the Adafruit library are irrelevant to fixing the problem.  And that seems like something anyone trying to help would want to know.

It may not actually be a "power" button.  But the button in any case.  The printer also has an escape sequence for printing the page.  So, in theory it could be done that was as well, but it would be better to use the button if possible so that it's certain to be operating under default settings.

Thermal printers generate quick pulses of heat to change thermal paper from white to a darker color.  This may require more than the expected amount of current most Arduino project need.
Consider checking the maximum current rating of your power source.  From the Adafruit printer web page regarding using this Mini Thermal Receipt Printer:

This printer in particular requires 5 to 9 Volts, 1.5 Amps current!
That means you will need a fairly beefy supply and you cannot run it
off of USB power. An external adapter is required!

Also consider trying different thermal paper manufactures and colors.
Lastly, consider how you might avoid BPA from thermal paper.

I was kind of hoping to get them to confirm it before posting an answer, but alright.

Ah, I see ... get them to reason it out for them selves - clever of you.  Hanging out here and other embedded processor stack exchange sites, I've see more than an expected number of problems associated with power supplies not capable of supply the necessary current.  I've been caught on this once or twice my self.

We are all here to improve these questions and answers for people who stumble upon these entries in the future.  I am not sure why there is a down vote but upon reading my answer I see there is no explanation why checking the power supply is a good idea.  So I added one.  If that was not the reason for the vote please leave a comment saying what is missing from the answer.

I can't speak for downvote motivations, but it strikes me as more of a comment/suggestion/request-for-details than answer. It may end up being the/an answer, but currently (see what I did there) it's a guess/hint that may or may not be relevant. I don't know the Arduino SE culture; no idea how it's similar/different to SO, so I don't participate much in voting yet unless I think it's obvious ¯_(ツ)_/¯

I was the initial upvote, in case that needs clarification.

Thanks @timemage.


text:
Has anyone had issues when trying to download the "CE_ARDUINO_LIB" from Github?
Hello all: I am very new to all of this and suspect that I am doing something wrong. I try to download the library using the IDE (Version 1.8.15) and get the error messageArduino: 1.8.15 (Windows Store 1.8.49.0) (Windows 10), Board: "Arduino Uno"
Error downloading https://downloads.arduino.cc/packages/package_index.json
Specified folder/zip file does not contain a valid library
Specified folder/zip file does not contain a valid library
I am trying to use a 4-20mA current loop board from NCD.io and this is the library that they say to use.
Thank you for your time

The file is the standard Arduino boards management package file that to be setup via Arduino -> Preferences, and you probably already have it under "Additional Boards Manager URLs". To download an Arduino Library from IDE, go to "Tools" -> "Manage Library..." to search for the library you want to download.

I have searched the Arduino Library Manager several times but the "CE_ARDUINO_LIB" is not on it. I can find it on Github but for some reason when I download it and try to add zip file from the IDE that is when the error message appears.

Sometime the library does not have the proper setup of library.properties file  or registered with the Arduino library that  Arduino Library Manager used to find the library. Just down the library from the github and add it to the library directory(if not available, create one) inside your Arduino/ directory, or use git clone <the_library>.git to download it.

Thank you for the advice. I will give it a try and let you know


text:
What is the chip in this board?
Doing some research about SD card adapters, I found these boards with a chip on them.

They are actually very common. They have a linear voltage regulator because UNO for example use 5V but SD card adapters use 3.3V. The voltage regulator has two capacitors one on the input one on the output. but what is C3? Looks like it is between the output and GND.
The other question is what is the other chip? I guess it turns sd card signals from 3.3 to 5v and viceversa. What is the name of this and what could be this chip model?

It's probably a 74HCT08 or something similar.

C3 is a capacitor

but what is C3? Looks like it is between the output and GND.

C3 is likely a 10 uF cap for the 3v3 output of the regulator.

(Source: datasheet for Sunrom SD module (PDF))

The circuit design used in the AMS1117 series requires the use of
an output capacitor as part of the device frequency compensation.
The addition of 22µF solid tantalum on the output will ensure
stability for all operating conditions.
When the adjustment terminal is bypassed with a capacitor to
improve the ripple rejection, the requirement for an output
capacitor increases. The value of 22µF tantalum covers all cases of
bypassing the adjustment terminal. Without bypassing the
adjustment terminal smaller capacitors can be used with equally
good results.

(Source: datasheet for AMS1117 voltage regulator (PDF))

The other question is what is the other chip? I guess it turns sd card signals from 3.3 to 5v and viceversa. What is the name of this and what could be this chip model?

At least some of these modules use the LVC125A quad bus buffer gate.

Thank you, your answer was very complete.


text:
Can't access SD card when running timestamps.ino from sdfat.h lib on arduino MKRZero
Im trying to run Timestamps.ino (an example sketch) from the sdfat.h lib into a mkrzero arduino.
This is the code I am running:
/*
 * This program tests the dateTimeCallback() function
 * and the timestamp() function.
 */
#include <SPI.h>
#include "SdFat114.h"
#include "sdios.h"

SdFat sd;

SdFile file;

// Default SD chip select is SS pin
const uint8_t chipSelect = 28;

// create Serial stream
ArduinoOutStream cout(Serial);
//------------------------------------------------------------------------------
// store error strings in flash to save RAM
#define error(s) sd.errorHalt(F(s))
//------------------------------------------------------------------------------
/*
 * date/time values for debug
 * normally supplied by a real-time clock or GPS
 */
// date 1-Oct-14
uint16_t year = 2014;
uint8_t month = 10;
uint8_t day = 1;

// time 20:30:40
uint8_t hour = 20;
uint8_t minute = 30;
uint8_t second = 40;
//------------------------------------------------------------------------------
/*
 * User provided date time callback function.
 * See SdFile::dateTimeCallback() for usage.
 */
void dateTime(uint16_t* date, uint16_t* time) {
  // User gets date and time from GPS or real-time
  // clock in real callback function

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(year, month, day);

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(hour, minute, second);
}
//------------------------------------------------------------------------------
/*
 * Function to print all timestamps.
 */
void printTimestamps(SdFile& f) {
  dir_t d;
  if (!f.dirEntry(&d)) {
    error("f.dirEntry failed");
  }

  cout << F("Creation: ");
  f.printFatDate(d.creationDate);
  cout << ' ';
  f.printFatTime(d.creationTime);
  cout << endl;

  cout << F("Modify: ");
  f.printFatDate(d.lastWriteDate);
  cout <<' ';
  f.printFatTime(d.lastWriteTime);
  cout << endl;

  cout << F("Access: ");
  f.printFatDate(d.lastAccessDate);
  cout << endl;
}
//------------------------------------------------------------------------------
void setup(void) {
  Serial.begin(9600);
  // Wait for USB Serial
  while (!Serial) {
    SysCall::yield();
  }
  cout << F("Type any character to start\n");
  while (!Serial.available()) {
    SysCall::yield();
  }
  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
    sd.initErrorHalt();
  }

  // remove files if they exist
  sd.remove("callback.txt");
  sd.remove("default.txt");
  sd.remove("stamp.txt");

  // create a new file with default timestamps
  if (!file.open("default.txt", O_WRONLY | O_CREAT)) {
    error("open default.txt failed");
  }
  cout << F("\nOpen with default times\n");
  printTimestamps(file);

  // close file
  file.close();
  /*
   * Test the date time callback function.
   *
   * dateTimeCallback() sets the function
   * that is called when a file is created
   * or when a file's directory entry is
   * modified by sync().
   *
   * The callback can be disabled by the call
   * SdFile::dateTimeCallbackCancel()
   */
  // set date time callback function
  SdFile::dateTimeCallback(dateTime);

  // create a new file with callback timestamps
  if (!file.open("callback.txt", O_WRONLY | O_CREAT)) {
    error("open callback.txt failed");
  }
  cout << ("\nOpen with callback times\n");
  printTimestamps(file);

  // change call back date
  day += 1;

  // must add two to see change since FAT second field is 5-bits
  second += 2;

  // modify file by writing a byte
  file.write('t');

  // force dir update
  file.sync();

  cout << F("\nTimes after write\n");
  printTimestamps(file);

  // close file
  file.close();
  /*
   * Test timestamp() function
   *
   * Cancel callback so sync will not
   * change access/modify timestamp
   */
  SdFile::dateTimeCallbackCancel();

  // create a new file with default timestamps
  if (!file.open("stamp.txt", O_WRONLY | O_CREAT)) {
    error("open stamp.txt failed");
  }
  // set creation date time
  if (!file.timestamp(T_CREATE, 2014, 11, 10, 1, 2, 3)) {
    error("set create time failed");
  }
  // set write/modification date time
  if (!file.timestamp(T_WRITE, 2014, 11, 11, 4, 5, 6)) {
    error("set write time failed");
  }
  // set access date
  if (!file.timestamp(T_ACCESS, 2014, 11, 12, 7, 8, 9)) {
    error("set access time failed");
  }
  cout << F("\nTimes after timestamp() calls\n");
  printTimestamps(file);

  file.close();
  cout << F("\nDone\n");
}

void loop() {}

And this is the error I get when I press any key into the serial.
Type any character to start
Can't access SD card. Do not reformat.
SD errorCode: 0X30,0X2

It's not and sd format problem, and I know that the chipselect pin for the SD is 28.
I have no idea what is wrong. Is it maybe a samd21 limitation with this library? is it there a samd21 lib for sd card?
I have written data in the sd card with other avr so I dont think the sd card is the problem.
Thanks

the SDFat library doesn't know that MKR Zero doesn't have the on-board SD card on SPI, but on SPI1. the Arduino SD library uses defines from variant.h of MKR Zero

So is it possible to make it to work by changing the variant.h? I was doing this test but I actually want to make it work with arduino zero. Do you know if arduino Zero has two spi also? if so, how can I know which one I am using? They both run the same atsamd21

you have to configure or change the SdFat library. but I don't know it. I use the Arduino SD library


text:
Duplicate Arduino SD Library
I need to have two independent arduino sd libraries so that I can modify one and have the other one intact. I struggle to do so.
Does anyone know if this is even possible?
What should be the path to properly do so?
I tried a lot of things but I always end up in a spot where I dont know what code is working and what is not. Last try I duplicated all the files and renambed all the functions to whatever"2" but couldn't make it work

What is the background of your project? Do you want to use both libraries in the same sketch? If so, why? What requirements do you have? Please [edit] your question and add these informations, don't use comments.

Do you need to use both of them insifde the same project?

If not then just create the library folder and copy it within the project where you are editing it Then include it as #include "Sd.h" rather then #include "Sd.h"

Yes I need to use them both inside the same project

If your objective is to use 2 SD card readers (pseudo) simultaneously in a project then this may help: https://forum.arduino.cc/t/two-sd-cards-on-the-same-project/1012605

that wont work, I need two independent sd libraries on the same sketch

You urgently need to add your goal to the question by [edit]ing it. Don't let us and future viewers pick up all the details like bread crumbs from your comments. -- Do you want the two different libraries access the same SD card or two different SD cards? -- Does you project build the libraries from source, or does it use ready-built libraries?

@the-busybee Quote from post "I need to have two independent arduino sd libraries so that I can modify one and have the other one intact." Quote from title "Duplicate Arduino SD Library"

Well, I'm giving up. Good luck!

If you want to use two SD card than instead of copying the whole library just create another instance of the class like
SDClass SD2;

Now you can call SD2.begin(CS_PIN_2) or any other function of the sd library.

That wont work because you are using the same library just changing the name where you call it. I need two independent libraries

Why do you need two independent libraries? Are you aware that the variables of both objects of SDClass are already independent?

@Espada86 Why you want two libraries? Because you want to use two SD cards ?

@the-busybee the requierement is to have two independent libraries because I want to modify one and have the other one unchanged but being able to call any of them on the same sketch.

@Espada86 Can you give a hint what you want to change in the library ?

@Espada86, use one modified library. modify it that way so it can be used the unmodified way too


text:
A9G gsm module not displaying message body after receiving SMS
I am trying to receive an SMS on my arduino and print it out to the serial monitor. I am using the A9G gsm/gps module for doing that. Here is the code for it
#include <SoftwareSerial.h>

//Create software serial object to communicate with A6
SoftwareSerial mySerial(10, 11); //A6 Tx & Rx is connected to Arduino #3 & #2

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(115200);

  //Begin serial communication with Arduino and A6
  mySerial.begin(115200);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CNMI=2,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

The code works and I get a response but the response does not include the body of the message. This is the response I got after sending "hello" to it;
CIEV: "MESSAGE",1
+CMT: "+233201729573",,"2021/06/18,12:20:03

As you can see it rightly sends me a notification but it does not include the "hello" which is the actual message I want to receive. Can anyone help me out?

I have sorted that out for sometime now. It turns out for some reason SerialSoftware was truncating my messages because the serial buffer size was too small. All I had to do was increase the buffer size to a higher number in the SoftwareSerial.h file and it worked.

Your serial reception code is much much much too primitive to be of any use.
You're waiting for 0.5 seconds for data to come in, which gets stored in a 64 byte buffer. Then you read out the contents of that 64 byte buffer.
Anything more than 64 bytes gets discarded.
You need to read the data actively as it comes in (NO delay()!) looking for specific things in the data (OK, ERROR, your text message response, etc) until the whole response from the modem has been received.

I recently jsut found out that I could change from 64 byte buffer to a much higher buffer. Which is what I did and now it works. However I am only able to do this on a windows pc and not from a linux system which is what I use.

Just to add up, after searching for the SoftwareSerial.h file and finding out its location and changing the serial buffer size, I am able to get it working on a linux system(ubuntu) now. Thanks.


text:
Nikon IR remote trigger (ML-L3) emulator not working
I have tried to follow along/reproduce the results from several sources for emulating the Nikon infrared remote trigger:

Adafruit Guide
DIY Nikon ML-L3 IR Wireless Remote Hack with Arduino UNO
Teardown and Project: Clone Nikon ML-L3 IR Remote and Emulation
Teach you how to DIY Nikon ML-L3 infrared remote control did not read yet
Arduino wireless remote for Nikon DSLR
Arduino Nikon Infrared command code
Arduino – IR remote/ intervalometer for Nikon D80 DSLR

I can read the signal from my remote trigger, but I cannot reproduce it with my Arduino setup. The signal I can receive (w/ TSOP38238 receiver diode) matches all of the signals given by the links above (there is some expected variance in pulse durations).
I don't think my hardware is at fault:

TSOP38238 receives @ 950 nm
my IR LED is 940-950 nm per datasheet
my IR LED works (I can see it emitting when I point it at my phone camera)

simulate this circuit – Schematic created using CircuitLab
My Code:
I have tried the code given in the links above, most don't use Port Manipulation and instead trial-and-error the delay durations to account for the overhead in Arduino functions. I have experimented with different values of the wait variable (8-13 microseconds) but have not gotten it working so far. I prefer to have my code versatile like this (no hard coded durations) so I can use it with other remotes in the future.
uint16_t Signal[] = [2050, 27800, 430, 1650, 430, 3650, 430, 65000]; // ON & OFF pulse durations (microseconds)
uint8_t wait = 13; // duration (microseconds) between pin state changes

// the setup function runs once when you press reset or power the board
void setup() {
    DDRB = B00000001; // set digital pin 8 to output
    PORTB = B00000000; // set digital pin 8 LOW
    Serial.begin(9600); // start serial monitor
}

// the loop function runs over and over again forever
void loop() {
    delay(1500); // wait a bit between sending signal
    sendSignal();
    sendSignal();
    // send signal twice, this is what the actual remote does
    Serial.println("Signal sent"); // message saying signal was sent
}

// function that sends the signal
void sendSignal(void) {
    for (int i = 0; i < sizeof(Signal)/sizeof(Signal[0]); i++) { // for each element in Signal array
        if (i%2 > 0) { // odd numbered index, is an OFF pulse
            PORTB = B00000000; // set digital pin 8 LOW
            delayMicroseconds(Signal[i]); // delay for OFF pulse duration
        } else { // even numbered index (including i=0), is an ON pulse, 38 kHz (26.3 usec period), 50% duty cycle
            unsigned long currentTime = micros(); // get current time
            while (micros() - currentTime < (unsigned long)Signal[i]) { // while still in ON pulse duration
                PORTB = B00000001; // set digital pin 8 HIGH
                delayMicroseconds(wait); // leave ON for time
                PORTB = B00000000; // set digital pin 8 LOW
                delayMicroseconds(wait); // leave OFF for time
            }
        }
    }
}

I hold my camera in direct line of sight of the LED (not blocking the receiver on the camera) from distances of ~2in to ~3ft away without success.
Has anyone tried this before? Is there a mistake in my approach or code?

generating an 38kHz signal with delayMicroseconds doesn't result in a very accurate frequency. It's probably lower due to the while loop taking some time to execute. The code provided in you second to last link actually uses 7µs of delay, and uses a simpler for-loop. It also uses a 810µs delay after the first pulse, where your code uses 27800µs

@Gerben That link uses delay(27) and delayMicroseconds(810) for a total delay of 27810 microseconds. It also uses digitalWrite instead of port manipulation which is slower.

But the delayMicroseconds documentation does say "the largest value that will produce an accurate delay is 16383" so I will try to combine delay w/ delayMicroseconds like that link does.

one if the links you posted includes code ... why are you not using it?

@jsotola none of the provided code worked for me

Got it working. The problems were the delayMicroseconds input being too large (see comments) and the frequency mismatches.
I set up a script to time the code segments of interest and that allowed me to select the best wait duration. It looks like this:
while (i < 256) {
    /* your code to time here */
    i++;
}
i = 0;
unsigned long time = 10000000 + micros();
Serial.println(time);

Make sure to time the empty loop and subtract that from your readings w/ code. Take the difference between time read outs, subtract the printing statement overhead (which is dependent on how many digits it is printing, hence the 10000000 + micros() to keep # of digits constant) and divide by 256.
I measured 4 different combinations to find the closest frequency match:

Command Type:
Wait duration (micro seconds):
Frequency (Hz):
% difference from 38 kHz

Port Manipulation
14
36990
-2.7 %

Port Manipulation
13
39960
5.2 %

digitalWrite
11
35980
-5.3 %

digitalWrite
10
38790
2.1 %

The final code ended up looking a lot like the one from this link; counting off cycles of the on-off 38 kHz pulse.