text:
How are PCB's programmed?
So recently I have been looking into prototyping my arduino project and there are a lot of tutorials online on how to take your Arduino and using a software such as Eagle to make a PCB layout but I was wondering how you would get the Arduino program onto that PCB. Surely in large scale circuit manufacturing they wouldn't have a usb attached so that they upload a program into each and every one of their circuits?

Large scale manufacturing doesn't involve arduino boards, as this would be too costly. They, however, can use the same microcontroller (Atmega 328). And usually they program with ISP programmers, so it does not require a FTDI chip or any usb/serial converters. And it also doesn't require a (usb-programmer) bootloader.

This belongs back on EESE where it was originally asked - "Arduino" is effectively nothing more than an example in this generic question.

I don' t find this question that generic; it is AVR oriented since the issue is how to program series of AVR, compared with programming one AVR with Arduino.

why not?
Well ok ... they might not connect a USB to each one as there are faster ways - flyingProbe/PogoPins on a "bed of nails"
http://en.wikipedia.org/wiki/In-circuit_test

This type of temporary connection speeds up testing & pre-programming considerably.
Each card that is made has to go through some form of test process at the end (flying probe or manual).
https://learn.sparkfun.com/tutorials/electronics-assembly

On boards that require programming or calibration, additional steps
  are taken to load code and verify the output.

For commercial products where very large quantities are produced, a microcontroller will be "mask programmed" - the (well-debugged) program will be built into the microcontroller as part of the IC production process.
For smaller quantities, the microcontroller may be programmed in a special fixture before being installed on the PC board.  Also, most current microcontrollers have "In System Programming (ISP)" capability, which typically requires a 6 - 10 pin connector on the board, and a special programmer to plug into that board.
I think it is highly unlikely that an Arduino-based program would be used in any commercial product.

Atmel doesn't mask-program AVRs, but will preflash an image you provide to them.

Actually, they generally do load a program into each and every one of their devices individually.  They can do a lot more than that as well.  Ever heard of something called JTAG?  For large circuit boards, most of the large ICs are connected to a JTAG scan chain.  Once the board is assembled, they connect a JTAG cable to the scan chain.  Special test software controls the scan chain through the JTAG cable, possibly connected to the control computer via USB.  The software can take control over the I/O pins on the ICs on the scan chain and set test patterns to check for opens or shorts.  It can also perform more complex testing in concert with external test equipment, even including temporarily loading special diagnostic firmware.  Once the test passes, the computer can then initialize ROMs, load firmware, set serial numbers, etc.
This is done one board at a time.  Often, special test and/or programming jigs are built that allow boards to be connected and disconnected quickly, and usually multiple jigs are used in parallel for higher throughput.
For some chips, they can be programmed before installation either with mask ROM or with a standalone programmer.  This is done when volumes are large and testing is not required, or if the devices must be programmed for the automated testing to work correctly.

cheers Brandan :)
I would suggest for you to make your own programmer. Then you will know a lot about programming and so on. If you want to program a chip on pcb, you have to have output pins of ISP. Throw these pins you will pump your code to Atmega chip.
Software Khazama is "old" and tested one. It really works :) AVR studio is also good one
Hardware USBasp There are ready pcb layouts in eagle. Building your own HW will be a bit more expensive than buying one, but if we count in experience it will be priceless :)
Also you can use bootloader. Check in google there are plenty of tutorials.


text:
avrdude: stk500v2_ReceiveMessage(): timeout with ADDAC VCC
I am getting the above error message uploading the ADDAC VCC, and the only thing that's changed I think is the patch is bigger.
Is there a fix for this or will I have to send it back? Hope my formatting is OK
Binary sketch size: 12,330 bytes (of a 258,048 byte maximum)
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cwiring -P/dev/ttyUSB0 -b115200 -D -Uflash:w:/tmp/build953252908946386724.tmp/comps.cpp.hex:i
avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]

avrdude: Version 6.0.1, compiled on Oct 21 2013 at 17:07:18
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/luke/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: wiring_open(): releasing DTR/RTS
avrdude: wiring_open(): asserting DTR/RTS
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]

As a first step in tracking this down, you should enable the "Verbose Upload" option in the Arduino preferences. That will give you considerably more output to let you know whether the upload is failing right away, or in the middle of communication.
Depending on your board, you might want to try hitting the RESET button on your board just before starting the upload, in order to force the boot loader to run.

Your log is showing that communication is failing right away (avrdude never gets a proper response). This can mean that

the VCC is not resetting
there is no bootloader installed
there is some other defect

You can test case is by manually hitting the reset switch around the time that avrdude starts. If the necessary pins are available, you can exclude case 2 by installing a new boot loader with a programmer, which also tests scenario 3 a bit.

source: Stack Exchange

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

sort: votes


text:
Best Header for Arduino Nano
I would like to be able to create permanent projects with my arduino Nano but be able to remove the nano in order to use it in other projects. The arduino Nano has 30 pins so I would be looking for some kind of female 30 pin header. Most of the headers that I found like that are too narrow because they are for IC's. Any ideas?

@Dwayne's answer is useful. The key seems to be looking at "board to board connectors which 'expect' a larger pin insert. At Digikey a good solution MAY be CES 50 way 1 row

Typically, dual row connectors with some space between them are referred to as "sockets" for "Dual Inline Package" (DIP) IC's, and other things having similar form factors.   Connectors intended for wiring harnesses and board stacking are typically the ones called "headers".  For an odd spacing, you simply buy two single row ones, and place them on your board appropriately.

The Nano boards that I have used all have pins on 0.1" (2.54mm) spacing.  There are single-row female connectors that are designed to accept 0.025" square pins.  One example is Samtec 32 position female header but there are many others.
Note that these female headers are available to accept either 0.018" round or 0.025" square pins.  My great preference is for the 0.018" round pins but those are less common in hobby circles.
The really huge advantage of the smaller round pins is that you can safely insert them into solderless breadboards without damaging the contacts in the breadboard.  But you would want to standardize on one style or the other.

I use the female headers from the original Nano manufacturer: http://gravitech.us/2015feheanas.html

You've already got a lot of really good answers here but I thought I would offer another product suggestion.  I purchased some of the 12 pin versions of these https://www.pololu.com/product/1031 for some recent projects.

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


text:
Why RTU bridge timeout even though answer is received?
I'm testing the following code as a bridge between https://sourceforge.net/projects/qmodmaster/ and https://pypi.org/project/pyModSlave/.
As hardware, I'm using a NodeMCU 1.0 and a USB/TTL converter.
The Modbus library is https://github.com/emelianov/modbus-esp8266.
#include <ESP8266WiFi.h>

#include <ModbusTCP.h>
#include <ModbusRTU.h>

#include <SoftwareSerial.h>
#include <StreamBuf.h>

#define BSIZE 1024

const unsigned long baudrate = 19200;
const unsigned long chtimeus = (8 + 3) * 1000000 / baudrate;

ModbusRTU rtu;
ModbusTCP tcp;

IPAddress srcIp;

SoftwareSerial debug_serial(D1, D2);

uint8_t serialw_rtur[BSIZE];
uint8_t serialr_rtuw[BSIZE];

StreamBuf serialw_rtur_sb(serialw_rtur, BSIZE);
StreamBuf serialr_rtuw_sb(serialr_rtuw, BSIZE);

DuplexBuf modbus_db(&serialw_rtur_sb, &serialr_rtuw_sb);
DuplexBuf serial_db(&serialr_rtuw_sb, &serialw_rtur_sb);

uint8_t com_buf[BSIZE];
uint8_t log_buf[BSIZE];

StreamBuf com_sbuf(com_buf, BSIZE);
StreamBuf log_sbuf(log_buf, BSIZE);

uint16_t transRunning = 0;
uint8_t slaveRunning = 0;

bool cbRtuTrans(Modbus::ResultCode event, uint16_t transactionId, void* data) {
  if (event != Modbus::EX_SUCCESS) {
    debug_serial.printf("modbusRTU transaction result: %02X\n\r", event);
    transRunning = 0;
  }
  return true;
}

Modbus::ResultCode cbTcpRaw(uint8_t* data, uint8_t len, void* custom) {
  auto src = (Modbus::frame_arg_t*) custom;

  debug_serial.print("received a TCP request from ");
  debug_serial.print(IPAddress(src->ipaddr));
  debug_serial.printf("-> Fn: %02X, len: %d\n\r", data[0], len);

  if (transRunning) {
    tcp.setTransactionId(src->transactionId);
    tcp.errorResponce(IPAddress(src->ipaddr), (Modbus::FunctionCode)data[0], Modbus::EX_SLAVE_DEVICE_BUSY);
    return Modbus::EX_SLAVE_DEVICE_BUSY;
  }

  rtu.rawRequest(src->unitId, data, len, cbRtuTrans);

  if (!src->unitId) {
    tcp.setTransactionId(src->transactionId);
    tcp.errorResponce(IPAddress(src->ipaddr), (Modbus::FunctionCode)data[0], Modbus::EX_ACKNOWLEDGE);

    transRunning = 0;
    slaveRunning = 0;
    return Modbus::EX_ACKNOWLEDGE;
  }

  srcIp = IPAddress(src->ipaddr);

  slaveRunning = src->unitId;

  transRunning = src->transactionId;

  return Modbus::EX_SUCCESS;

}

Modbus::ResultCode cbRtuRaw(uint8_t* data, uint8_t len, void* custom) {
  auto src = (Modbus::frame_arg_t*)custom;

  debug_serial.printf("received RTU response from %d-> Fn: %02X, len: %d\n\r", src->slaveId, data[0], len);

  tcp.setTransactionId(transRunning);
  uint16_t succeed = tcp.rawResponce(srcIp, data, len, slaveRunning);
  if (!succeed) {
    debug_serial.print("failed to");
  }

  debug_serial.print("respond to TCP: ");
  debug_serial.println(srcIp);

  transRunning = 0;
  slaveRunning = 0;
  return Modbus::EX_PASSTHROUGH;
}

void print_log(const char *msg) {
  debug_serial.print(msg);
  debug_serial.print(": ");
  while(log_sbuf.available()) {
    debug_serial.print(log_sbuf.read(), HEX);
    debug_serial.print(' ');
  }
  debug_serial.println();
}

void process_from_to(Stream *from_s, Stream *to_s, unsigned delay_us = 0) {
  while(from_s->available()) {

    char c = from_s->read();

    com_sbuf.write(c);
    log_sbuf.write(c);

    if(delay_us != 0)
      delayMicroseconds(delay_us);

  }

  while(com_sbuf.available())
    to_s->write(com_sbuf.read());
}

void setup() {
  Serial.begin(baudrate, SERIAL_8E1);
  debug_serial.begin(baudrate, SWSERIAL_8E1);

  WiFi.begin("<SSID>", "<PASSWORD>");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    debug_serial.print(".");
  }

  debug_serial.println("");
  debug_serial.println("IP address: ");
  debug_serial.println(WiFi.localIP());

  tcp.server();
  tcp.onRaw(cbTcpRaw);

  rtu.begin((Stream*)&modbus_db);
  rtu.master();
  rtu.onRaw(cbRtuRaw);
}

void loop() {
  rtu.task();
  tcp.task();
  yield();

  if(Serial.available()) {

    process_from_to(&Serial, &serial_db, chtimeus << 1);

    print_log("received response from RTU");

  }

  if(serial_db.available()) {

    process_from_to(&serial_db, &Serial);

    print_log("sent request to RTU");

  }

}

qModMaster has the following configs:

Modbus Mode: TCP
Slave Addr: 1
Scan Rate: 5 s
Function Code: 0x03
Start Address: 0x00
Register Number: 10
Slave IP: my ESP's IP in the network
Slave Port: 502

pyModSlave has the following configs:

Modbus Mode: RTU
Slave Address: 1
SimCycle: 5 s
Port: my ESP's Serial's USB port
Baudrate: 19200
Data Bits: 8
Stop Bits: 1
Parity: None

I've already tried using hard and soft Serial, baudrates of 9600 and 19200 and powering the board with a regulated supply @5V - 1A.
Both programs work normally when I communicate them directly with the ESP, either reading from the RTU slave or receiving reads from the TCP client.
When I use ESP as a bridge, the RTU slave receives the request normally and responds correctly in <5ms, but the timeout occurs.
An external monitor (a Uno with the Rx of a SoftwareSerial connected to the NodeMCU hardware Rx pin) shows that the correct data reaches the ESP:
rtu monitor:
[RTU]>Rx > 18:21:37:626 - 01 03 00 00 00 0A C5 CD
[RTU]>Tx > 18:21:37:626 - 01 03 14 9D AC D8 0D 61 1A 29 7B 0E 7D 19 15 62 01 C2 F1 9E CF 41 C6 3C D4
[RTU]>Rx > 18:21:47:674 - 01 03 00 00 00 0A C5 CD
[RTU]>Tx > 18:21:47:675 - 01 03 14 A7 EE 7E F2 5D 43 66 D7 4B 73 3A 0A D2 B6 23 BB F0 E4 AB D0 CD 9E
[RTU]>Rx > 18:21:57:590 - 01 03 00 00 00 0A C5 CD
[RTU]>Tx > 18:21:57:590 - 01 03 14 D0 31 DC 14 E7 A2 84 49 C6 3A 1D 13 BD 7E DD DF E1 C7 02 89 F0 80
[RTU]>Rx > 18:22:07:638 - 01 03 00 00 00 0A C5 CD
[RTU]>Tx > 18:22:07:639 - 01 03 14 71 26 FE 5B 12 23 A7 F4 39 0A 55 12 F9 E4 63 27 90 0C 18 11 00 51
[RTU]>Rx > 18:22:17:682 - 01 03 00 00 00 0A C5 CD
[RTU]>Tx > 18:22:17:683 - 01 03 14 1C 9D A1 68 11 71 A4 96 1D BF D4 C3 86 B1 B2 42 68 C4 72 BD C6 A3
[RTU]>Rx > 18:22:27:722 - 01 03 00 00 00 0A C5 CD
[RTU]>Tx > 18:22:27:724 - 01 03 14 93 6B 28 A4 F2 DD 3D E1 C3 29 61 82 EF CC E3 37 99 AA 32 04 3A 56

external monitor:
response: 1 3 14 9D AC D8 D 61 1A 29 7B E 7D 19 15 62 1 C2 F1 9E CF 41 C6 3C D4
response: 1 3 14 A7 EE 7E F2 5D 43 66 D7 4B 73 3A A D2 B6 23 BB F0 E4 AB D0 CD 9E
response: 1 3 14 D0 31 DC 14 E7 A2 84 49 C6 3A 1D 13 BD 7E DD DF E1 C7 2 89 F0 80
response: 1 3 14 71 26 FE 5B 12 23 A7 F4 39 A 55 12 F9 E4 63 27 90 C 18 11 0 51
response: 1 3 14 1C 9D A1 68 11 71 A4 96 1D BF D4 C3 86 B1 B2 42 68 C4 72 BD C6 A3
response: 1 3 14 93 6B 28 A4 F2 DD 3D E1 C3 29 61 82 EF CC E3 37 99 AA 32 4 3A 56

bridge monitor:
received a TCP request from 192.168.1.12-> Fn: 03, len: 5
sent request to RTU: 1 3 0 0 0 A C5 CD
received response from RTU: 1 20 51 C6 C3 D 58 A3 69 39 7D 46 91 5 C2 7C F6 41 1C A2
received a TCP request from 192.168.1.12-> Fn: 03, len: 5
modbusRTU transaction result: E4

received a TCP request from 192.168.1.12-> Fn: 03, len: 5
sent request to RTU: 1 3 0 0 0 A C5 CD
received response from RTU: 1 20 D1 73 7E BE 35 99 D7 A9 E9 A 3A DB DA F0 DE D D7 9E

received a TCP request from 192.168.1.12-> Fn: 03, len: 5
modbusRTU transaction result: E4

received a TCP request from 192.168.1.12-> Fn: 03, len: 5
sent request to RTU: 1 3 0 0 0 A C5 CD
received response from RTU: 1 20 11 17 E2 14 9E 23 49 9C EA 13 6F 75 DF 78 9C 89 80
received a TCP request from 192.168.1.12-> Fn: 03, len: 5
modbusRTU transaction result: E4

received a TCP request from 192.168.1.12-> Fn: 03, len: 5
sent request to RTU: 1 3 0 0 0 A C5 CD
received response from RTU: 1 20 51 99 FE 2B 34 3A F4 4E A1 95 94 E4 AC 12 C6 18 44 51
received a TCP request from 192.168.1.12-> Fn: 03, len: 5
modbusRTU transaction result: E4

received a TCP request from 192.168.1.12-> Fn: 03, len: 5
sent request to RTU: 1 3 0 0 0 A C5 CD
received response from RTU: 1 20 11 D4 A1 2B 14 91 96 47 A3 C3 58 93 42 8B 72 6F DC FF
received a TCP request from 192.168.1.12-> Fn: 03, len: 5
modbusRTU transaction result: E4

received a TCP request from 192.168.1.12-> Fn: 03, len: 5
sent request to RTU: 1 3 0 0 0 A C5 CD
received response from RTU: 1 20 D1 B6 A1 A4 BE D7 A C3 4A 9 EF 6E 37 66 35 22 3A F5
received a TCP request from 192.168.1.12-> Fn: 03, len: 5
modbusRTU transaction result: E4

tcp monitor
[TCP]>Tx > 18:21:37:517 - 00  16  00  00  00  06  01  03  00  00  00  0A
Sys > 18:21:38:031 - Error : Timeout
[TCP]>Tx > 18:21:42:523 - 00  17  00  00  00  06  01  03  00  00  00  0A
[TCP]>Rx > 18:21:42:649 - 00  17  00  00  00  03  FF  83  06
Sys > 18:21:42:649 - Error : Slave device or server is busy
[TCP]>Tx > 18:21:47:524 - 00  18  00  00  00  06  01  03  00  00  00  0A
Sys > 18:21:48:039 - Error : Timeout
[TCP]>Tx > 18:21:52:525 - 00  19  00  00  00  06  01  03  00  00  00  0A
[TCP]>Rx > 18:21:52:684 - 00  19  00  00  00  03  FF  83  06
Sys > 18:21:52:684 - Error : Slave device or server is busy
[TCP]>Tx > 18:21:57:521 - 00  1A  00  00  00  06  01  03  00  00  00  0A
Sys > 18:21:58:027 - Error : Timeout
[TCP]>Tx > 18:22:02:536 - 00  1B  00  00  00  06  01  03  00  00  00  0A
[TCP]>Rx > 18:22:02:595 - 00  1B  00  00  00  03  FF  83  06
Sys > 18:22:02:595 - Error : Slave device or server is busy
[TCP]>Tx > 18:22:07:543 - 00  1C  00  00  00  06  01  03  00  00  00  0A
Sys > 18:22:08:044 - Error : Timeout
[TCP]>Tx > 18:22:12:539 - 00  1D  00  00  00  06  01  03  00  00  00  0A
[TCP]>Rx > 18:22:12:633 - 00  1D  00  00  00  03  FF  83  06
Sys > 18:22:12:633 - Error : Slave device or server is busy
[TCP]>Tx > 18:22:17:542 - 00  1E  00  00  00  06  01  03  00  00  00  0A
Sys > 18:22:18:047 - Error : Timeout
[TCP]>Tx > 18:22:22:531 - 00  1F  00  00  00  06  01  03  00  00  00  0A
[TCP]>Rx > 18:22:22:577 - 00  1F  00  00  00  03  FF  83  06
Sys > 18:22:22:577 - Error : Slave device or server is busy
[TCP]>Tx > 18:22:27:536 - 00  20  00  00  00  06  01  03  00  00  00  0A
Sys > 18:22:28:041 - Error : Timeout
[TCP]>Tx > 18:22:32:534 - 00  21  00  00  00  06  01  03  00  00  00  0A
[TCP]>Rx > 18:22:32:595 - 00  21  00  00  00  03  FF  83  06
Sys > 18:22:32:595 - Error : Slave device or server is busy

Please, any hint on what to test or what else to investigate? Thanks.

You think that you were receiving something via TCP, but if you look at "received response" from the log, it is totally rubbish and just doesn't make any sense. While the data from RTU has the correct data format and CRC.

No idea where you get the Modbus library from, so can't comment anything whether the library could handle both TCP and RTU simultaneously. One thing about your code is that if  it received error or busy there is no re-send or waitWhileBusy mechanism, and your code didn't really handle any Modbus Exception, you simply went straight to print the buffer and thinking that's what you received...

Thank you for the feedback. I've edited the question to inform the used library (https://github.com/emelianov/modbus-esp8266) and provide clearer debug messages.

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


text:
How Do I Get Started With ATtiny85 in 2024?
I recently purchase a ATtiny85 from ebay https://www.ebay.co.uk/itm/375425498292 as I wanted to make a diy volume controller for my computer, but its become apparent that's its more difficult than its supposed to be programming this board,
I managed to download drivers from GitHub as the main  http://digistump.com/ site has disappeared and is no longer working,
I found the drivers here: https://github.com/SpenceKonde/ATTinyCore/blob/v2.0.0-devThis-is-the-head-submit-PRs-against-this/Installation.md as well as here: https://github.com/digistump/DigistumpArduino/releases/download/1.6.7/Digistump.Drivers.zip
I installed them and I have it show up in my device manager:

For the Arduino IDE I'm running the version 2.3.2 as of today, Ive added the following package json files:
I had to upload the package.json file to a gist so I could use it https://gist.githubusercontent.com/MrJoshFisher/5704ae7e640a7ea1cec135647397f979/raw/74eabc3f644a770f91f5815f2f5d9f6b1430ad49/package_drazzy.com_index.json
The only version I can find that works of "ÄTTinyCore by Spence Konde" is version 1.3.2 as every version after that fails to download and doesnt work.
So after ive done that, I opened the example Blink file assigned the Pin as from the documentation I found on the Attiny85, and I got the following errors:
"A programmer is required to upload" - Short answer had to click Upload Sketch with Programmer "Arduino as ISP" also Tried "USBTIny" but end up getting another error "avrdude: Error: Could not find USBtiny device (0x1781/0xc9f)"
I'm running windows 11
I've watched several videos, tried multiple different solutions but it all seems to be varying things which could be the issue, so not 100% on what solution actually works,
So I am asking here in case anyone had a working setup.
Cheers

it's not digitastump.com ... you can use archive.org to look at archived pages

Thanks @jsotola for reminding me of the Wayback machine; the archived page gives a 302 but redirects to the github file I've noted in my answer.

These 'ATtiny85 boards' are the generic name for a project known as DigiSpark. (Source: I backed the Kickstarter for the DigiSpark ~10 years ago, so I did use them many years ago; the following is mostly from memory).
The original DigiStump (creators of the ATtiny85-based DigiSpark) website appears to have disappeared. So the board profile at http://digistump.com/package_digistump_index.json is no longer available.
Fortunately it is also in DigiStump's github repository at https://github.com/digistump
A URL that can be added to the additional boards URL is: https://raw.githubusercontent.com/digistump/arduino-boards-index/master/package_digistump_index.json
You will probably want to use the Digispark (Default - 16.5mhz) profile.
To upload the sketch, unplug the board, Press Ctrl-U and when prompted, plug the board back into the computer; this is how the bootloader is recognised.

I've just tested this and it all works as expected. The onboard LED is connected to pin 1 (on the board I have, which appears the same as OP's link except it is blue instead of black).

Are you using any specific programmer?

Finally Got it working cheers, added the json, found the package managed to get a blink working!

To clarify, for anyone else that may see this question: The programmer (for the DigiSpark board profile) is effectively the bootloader on the DigiSpark itself and no separate hardware is needed. The  Spence Konde board profile noted by OP will need separate programmer hardware.

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


text:
Arduino uno and ESP8266
Scenario :

I want to connect ESP8266 to Raspberry-pi's wifi network.
Arduino Uno is connected to ESP8266
Raspberry-pi will send a signal (1/0) to ESP8266, when its 1 Arduino will turn on/off a Relay.
I do not have a USB to UART Serial module

So my question is how to complete this task? Is it a feasible one?
I had been looking for many websites, almost all are using USB to UART Serial module to burn firmware to ESP8266.

You can use the USB-to-Serial adapter of the Arduino UNO, it has one on-board (ATmega16U2). Check the schematic of the UNO to understand what's going on.
First, upload an empty sketch to the UNO's ATmega328P, to make sure that it doesn't use the UART.
Connect the TX pin of the ATmega16U2 (i.e. the RX pin of the Arduino, digital pin 0) to the RX pin of the ESP8266. Connect a 2kΩ resistor between the ESP's RX pin. Together with the 1kΩ resistor on the ATmega16U2's TX line (on the Arduino), this creates a voltage divider that acts as a level shifter from 5V to 3.3V.
Connect the RX pin of the ATmega16U2 (i.e. the TX pin of the Arduino, digital pin 1) to the TX pin of the ESP8266.
Connect the grounds together as well.
In the Arduino IDE, select the ESP8266 under Tools > Board. Then enter programming mode on the ESP:

Bring reset low
Bring GPIO0 low
Bring reset high
Bring GPIO0 high

Then upload your sketch to the ESP.
I recommend adding simple push buttons and pull-up resistors:

(The ESP-01 has GPIO15 shorted to ground internally, so you don't have to worry about that. If you were using an ESP-## module that breaks out this pin, you need an external pull-down resistor.)
Keep in mind that you will also need a decent 3.3V power source, and some decoupling capacitors.
A Beginner's Guide to the ESP8266


text:
ESP8266 Web Server Crash + Arduino IDE
I am working on HTTP GET Request. I have created ESP wifi as web server. It creates a access point with IP address : 192.168.4.1
When my android app is connected to web server, it sends values every 50ms on 192.168.4.1/R"VALUE". Value is integer type (0~1023). Example :- 192.168.4.1/R546
However, it is working fine when I send values every 1s, but esp crashes, when IP is hit every 5ms second. I have captured the crash detail on serial monitor. Attaching the file and code as well. Kindly help.
#include <ESP8266WiFi.h>
#include <EEPROM.h>
#include <ESP8266WebServer.h>

#define RED_LED     12

WiFiServer server(80); //Initialize the server on Port 80

char myTestUrl[100];

void setup()
{

  EEPROM.begin(512);
  Serial.begin(9600); //Start communication between the ESP8266-12E and the monitor window

  WiFi.mode(WIFI_AP); //Our ESP8266-12E is an AccessPoint
  WiFi.softAP("LED_Downlight1", "12345678"); // Provide the (SSID, password); .
  server.begin(); // Start the HTTP Server

  IPAddress HTTPS_ServerIP = WiFi.softAPIP(); // Obtain the IP of the Server
  Serial.print("Server IP is: "); // Print the IP to the monitor window
  Serial.println(HTTPS_ServerIP);
}

void loop()
{
  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }

  String request = client.readStringUntil('\r');
  //Serial.print(request);

  request.toCharArray(myTestUrl, 100);

  char *Red = strstr(myTestUrl, "/R");
  if (Red)
  {
    int RedValue  = atoi(Red + 2);
    analogWrite(RED_LED, RedValue);
    Serial.print("Red: ");
    Serial.print(" ");
    Serial.print(RedValue);
    Serial.print("\n");

    int SetRedValue = (RedValue / 4);
    EEPROM.write(0, SetRedValue);

    EEPROM.commit();

    Serial.print("Red Memory Write :");
    Serial.print(" ");
    Serial.print(SetRedValue);
    Serial.print("\n \n");

  }
}

Exception(29) = A store referenced a page mapped with an attribute that does not permit stores - information from this page - personally I wouldn't be using EEPROM like that

So what is the best way to use EEPROM? How can I improve my code? Any Suggestion or sketch would be useful.

One reason you may get the error is that writing to EEPROM is exceptionally slow (compared to other memory operations) and I wouldn't use EEPROM to store data like that for two reasons. 1) you never read it, so why store it. 2) EEPROM has limited write cycles, write many times a second, you will reach (permanent) failure point sooner rather than later

I've worked with ESP8266 to create a centralized network over which different devices could communicate. In my first iteration I used an ESP8266 as an AP and let other ESP8266s connect to it. This didn't work for longer than 5 minutes. I suspected the ESP8266 couldn't handle many connections for a long period of time and bought an USB WiFi router. Now, I connected all ESP8266 to the WiFi router, including the ESP8266 that I set up as server. And it worked.
In other words: the ESP8266 isn't strong enough to be an AP and communicate a lot of data at the same time. Instead, you'd rather like your ESP connect to an existing wireless network with other devices and let those devices connect to the IP of the ESP.


text:
how do i get data from the website? using arduino uno and esp8266
i have hosted a website on the 000webhost. And i have simply written a line in paragraph tags in html file( means i have created a html file..)
so i want to know to know how i get data that data in html file on the serial moniter through esp8266.
i have written a code in the arduino ide which is....
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"www.tcpss.000webhostapp.com\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /index.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

and the response on the serial moniter is
AT+CIPMUX=1

OK

AT+CIPSTART=4,"TCP","www.tcpss.000webhostapp.com",80

4,CONNEC
AT+CIPSEND=4,28

OK
>
Recv 28 bytes

SEND OK

+IPD,4,412:HTTP/1.1 400 Bad Request
Date: Thu, 27 May 2021 18:07:45 GMT
Content-Type: text/html
Content-Length: 154
Connection: close
Server: awex
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-ID: 2eaf3c737a5348270ebe7873cab10088

<title>400 Bad Request</title>

400 Bad Request

openresty

4,CLOSED

what does it mean?
thanks in advance.......

You need to provide a full HTTP request, not just the "GET" line. You must at the very least include the Host: header, otherwise the web server has no clue which website you want to access.


text:
SD card initialize and fails when date changed
i am making a project using Arduino Uno that display data on 7 seg display which stored in SD card as day by day. when i make power ON to device then SD card initialization done & data shows correct as per date. Then after when i change the date SD card failed i.e. "show error opening database.txt" .
How can i overcome with this?
" When debugging my SD Card I had a software error that would put the
card into a state that required the microSD card to be powered down and then
powered up to work. It would work until the software error and then not
work again until the power was cycled. "

what software error?


text:
Serial connection between arduino and processing doesn't work; Port busy
I'm trying to connect arduino and processing via serial. Whenever I run the processing sketch I get the following error in Processing:
RuntimeException: Error opening serial port COM26: Port busy
Could not run the sketch (Target VM failed to initialize).

Below is the arduino sketch and processing code, which I "borrowed" from here, to try to programmatically find the correct serial port to connect to.
Arduino:
int var;

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

void loop() {
  if (Serial.available()) {
    var = Serial.read();
  }
  Serial.println(var);
  delay(100);
}

Processing:
import processing.serial.*;

Serial ser_port;                // for serial port
PFont fnt;                      // for font
int num_ports;
boolean device_detected = false;
String[] port_list;
String detected_port = "";

void setup() {
  size(400, 200);                         // size of application window
  background(0);                          // black background
  fnt = createFont("Arial", 16, true);    // font displayed in window

  println(Serial.list());

  // get the number of detected serial ports
  num_ports = Serial.list().length;
  // save the current list of serial ports
  port_list = new String[num_ports];
  for (int i = 0; i < num_ports; i++) {
    port_list[i] = Serial.list()[i];
  }
}

void draw()
{
  background(0);
  // display instructions to user
  textFont(fnt, 14);
  text("1. Arduino or serial device must be unplugged.", 20, 30);
  text("   (unplug device and restart this application if not)", 20, 50);
  text("2. Plug the Arduino or serial device into a USB port.", 20, 80);

  // see if Arduino or serial device was plugged in
  if ((Serial.list().length > num_ports) && !device_detected) {
    device_detected = true;
    // determine which port the device was plugged into
    boolean str_match = false;
    if (num_ports == 0) {
      detected_port = Serial.list()[0];
    } else {
      // go through the current port list
      for (int i = 0; i < Serial.list().length; i++) {
        // go through the saved port list
        for (int j = 0; j < num_ports; j++) {
          if (Serial.list()[i].equals(port_list[j])) {
            break;
          }
          if (j == (num_ports - 1)) {
            str_match = true;
            detected_port = Serial.list()[i];
          }
        }
      }
    }
  }
  // calculate and display serial port name
  if (device_detected) {
    text("Device detected:", 20, 110);
    textFont(fnt, 18);
    text(detected_port, 20, 150);
    ser_port = new Serial(this, detected_port, 9600);
  }
}

I am a newbie at this, so not sure what I'm doing wrong. Would appreciate any help :)

Have you checked manually if COM26 is actually the COM port of your Arduino? Does the communication work with the Serial Monitor?

You should probably set detected port when it's found rather than doing it after the loop if nothing else, and I'd recommend getting the serial list only once before the loop instead of three times. This might not solve the problem, but it's certainly more deterministic.

The port it's finding is the correct one. However, I haven't been able to make the communication work. It's saying the port is busy. I'm using an Arduino nano every. @DaveNewton You're saying I should set the serial port, directly after finding it, rather than wait to do it in the if device detected function? For the 2nd point, I'm not sure the code would work if I only check once, since I won't be able to programmatically find the com port the Arduino is on, if I only check once.

And can you connect with the Serial Monitor to that port? Is there some other program open that uses that port?

I tried a simple app, where I manually set the port. Processing is not giving me any errors and supposed to be writing to the Arduino. And if I try to open the serial monitor, while the app is running it's saying the port is busy. However, the variable in the Arduino sketch is not updating.

The question meant can you connect to the Arduino with anything else not while the program is running, e.g., does it work at all. My point about detection is that as soon as there’s a not-matching serial port in the loop you can stop checking—you know the index of the newly-plugged device’s serial port.

The IDE connects with it as normal. Processing does not work as expected. Not sure with what else to try? Re: detection - I see, I'll try to simplify the code.

I tried your Processing sketch, and it does detect and try to connect to the serial port, but fails for some reason.
Processing "code" can include a try catch block to help you diagnose the issue. Using this modified sketch, you can print the errors to the console window.
import processing.serial.*;

Serial ser_port;                // for serial port
PFont fnt;                      // for font
int num_ports;
boolean device_detected = false;
String[] port_list;
String detected_port = "";

void setup() {
  size(400, 200);                         // size of application window
  background(0);                          // black background
  fnt = createFont("Arial", 16, true);    // font displayed in window

  println(Serial.list());

  // get the number of detected serial ports
  num_ports = Serial.list().length;
  // save the current list of serial ports
  port_list = new String[num_ports];
  for (int i = 0; i < num_ports; i++) {
    port_list[i] = Serial.list()[i];
  }
}

void draw()
{
  background(0);
  // display instructions to user
  textFont(fnt, 14);
  text("1. Arduino or serial device must be unplugged.", 20, 30);
  text("   (unplug device and restart this application if not)", 20, 50);
  text("2. Plug the Arduino or serial device into a USB port.", 20, 80);

  // see if Arduino or serial device was plugged in
  if ((Serial.list().length > num_ports) && !device_detected) {
    device_detected = true;
    // determine which port the device was plugged into
    boolean str_match = false;
    if (num_ports == 0) {
      detected_port = Serial.list()[0];
    } else {
      // go through the current port list
      for (int i = 0; i < Serial.list().length; i++) {
        // go through the saved port list
        for (int j = 0; j < num_ports; j++) {
          if (Serial.list()[i].equals(port_list[j])) {
            break;
          }
          if (j == (num_ports - 1)) {
            str_match = true;
            detected_port = Serial.list()[i];
          }
        }
      }
    }
  }
  else{
    text("else", 20, 110);
  }
  // calculate and display serial port name
  if (device_detected) {
    text("Device detected:", 20, 110);
    textFont(fnt, 18);
    text(detected_port, 20, 150);
    try{
      ser_port = new Serial(this, detected_port, 9600);
    }
    catch(Exception e){
      // Print detailed error information to the console.
      System.err.println(e);
      e.printStackTrace();
    }
  }
  else{
    text("Device NOT detected:", 20, 140);
  }
}

These are the errors I get on my computer using a Arduino Uno.
    at processing.serial.Serial.<init>(Unknown Source)
    at processing.serial.Serial.<init>(Unknown Source)
    at sketch_211210a.draw(sketch_211210a.java:85)
    at processing.core.PApplet.handleDraw(PApplet.java:2475)
    at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1547)
    at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:313)
java.lang.RuntimeException: Error opening serial port /dev/tty.wchusbserial620: Port busy
java.lang.RuntimeException: Error opening serial port /dev/tty.wchusbserial620: Port busy

Another issue is with this part of the code: if (device_detected). The draw() function is like the Arduino loop() function in that it keeps looping through the code. It is repeatedly trying to make a new serial connection to the same port, which MAY explain why the Port busy error message is repeated in the console error messages.
Using Processing IDE 3.5.3, there is a errors tab at the bottom of the console window. I am getting 2 errors there which don't seem to be involved with the port connection issue.
If you install the controlP5 library in the Processing IDE, you can use this port testing sketch to see the Port ID change every time you create a new connection with it. I suspect your sketch may connect to the Arduino the first time through the draw() function, then it keeps trying to connect to the same port which is busy.
// Serial port(s) connection tester. Processing version 3.5.3.
// For a list of all the ScrollableList Controller methods available,
// use: "ControlP5.printPublicMethodsFor(ScrollableList.class);"
// to print the entire list of the 165 functions to the console.
import controlP5.*;
import java.util.*;
import processing.serial.*;

ControlP5 cp5;
Serial myPort;
Textlabel outputWindowLine1, outputWindowLine2;
String portName;

void setup(){

  size(500, 431);

  // Use a font larger than the default "6px".
  ControlFont font = new ControlFont(createFont("Verdana", 14));

  // ALL CAPS is the default font for the control. Why?
  Label.setUpperCaseDefault(false);

  // Configure a controlP5 ScrollableList.
  cp5 = new ControlP5(this);
  cp5.addScrollableList("dropdown")
    .setPosition(0, 50)
    .setSize(500, 400)
    .setBarHeight(50)
    .setItemHeight(30)
    .setFont(font)
    .addItems(GetSerialPortList())
    .setType(ScrollableList.LIST)
    .setLabel("--- Click on a port name to try and connect to it ---")
    ;

  outputWindowLine1 = cp5.addTextlabel("outputWindowLine1Label")
    .setText("The list of port names is \"scrollable\".")
    .setPosition(0, 0)
    .setColorValue(0)
    .setFont(font)
    ;

  outputWindowLine2 = cp5.addTextlabel("outputWindowLine2Label")
    .setText("Press any character on the keyboard to reload the list.")
    .setPosition(0, 25)
    .setColorValue(0)
    .setFont(font)
    ;
}

void draw(){
  background(255);
}

// User selects a drop down item. Works like a JavaScript onChange()
// event, except you can click on the same item multiple times, this
// code will execute again on each mouse "click" of the same item.
void dropdown(int n){

  // Create a serial connection and send some
  // chars to the "USB to Serial Converter".
  try{

    // Get the port name.
    portName = Serial.list()[n];

    // If you don't do this, you can't re-connect to the same port again.
    // Re-connecting to the same port gives you a new "myPort ID" and may
    // take a few seconds.
    if(myPort != null){
      myPort.clear();
      myPort.stop();
    }

    // Create a Serial Port connection.
    myPort = new Serial(this, portName, 9600);

    // User message.
    outputWindowLine1.setText("Connected to portName: " + portName);
    outputWindowLine2.setText("myPort = " + myPort);

  }
  catch(Exception e){

    // User message.
    outputWindowLine1.setText("Error connecting to portName: " + portName);
    outputWindowLine2.setText("");

    // Print detailed error information to the console.
    System.err.println(e);
    e.printStackTrace();
  }
}

// Refresh the dropdown list of serial port names.
void keyPressed(){
  cp5.get(ScrollableList.class, "dropdown").setItems(GetSerialPortList());
  outputWindowLine1.setText("Serial port list refreshed!");
  outputWindowLine2.setText("");
}

// Get a List of the serial port names.
List GetSerialPortList(){
  List serialPortList = Arrays.asList(Serial.list());
  return serialPortList;
}

thank you very much for your detailed response. I'll take the time tomorrow to go through it, and digest. And I will post on here again. Have a good evening.

I've decided to make a new post, since the error seems to be more basic/something else, and it feels like it would be more harm than good to try to edit this post.


text:
Interfacing Arduino Uno with OV7670 (with FIFO)?
I need help with interfacing ov7670 to Aduino Uno. I know there is a lot of literature available but the problem is that all this literature is for ov7670 without FIFO. I have Ov7670 with FIFO and its a 22-pin image sensor. I haven't been able to relate the available tutorials to my module. Any help in this regard is appreciated. (I need Wire Configuration as well as Code to get images).
Kind Regards,


text:
Reading quadrature encoder
I am using an encoder motor for one of my projects and i was reading encoder values manually through Arduino. It was working fine when i turned it slowly, but whenever i would rotate it at some higher speed, data input to the arduino would stop. I am using the encoder at 4 x.
Can somebody help me with some code to read the data from encoder faster.
    int pulses, A_SIG=0, B_SIG=1;

void setup(){
  attachInterrupt(0, A_RISE, RISING);
  attachInterrupt(1, B_RISE, RISING);
  Serial.begin(115200);
}//setup

void loop(){

}

void A_RISE(){
 detachInterrupt(0);
 A_SIG=1;

 if(B_SIG==0)
  pulses++;//moving forward
 if(B_SIG==1)
  pulses--;//moving reverse
 Serial.println(pulses);
 attachInterrupt(0, A_FALL, FALLING);
}

void A_FALL(){
  detachInterrupt(0);
 A_SIG=0;

 if(B_SIG==1)
    pulses++;//moving forward
 if(B_SIG==0)
     pulses--;//moving reverse
 Serial.println(pulses);
 attachInterrupt(0, A_RISE, RISING);
}

void B_RISE(){
  detachInterrupt(1);
  B_SIG=1;

  if(A_SIG==1)
     pulses++;//moving forward
  if(A_SIG==0)
      pulses--;//moving reverse
  Serial.println(pulses);
  attachInterrupt(1, B_FALL, FALLING);
}

 void B_FALL(){
    detachInterrupt(1);
    B_SIG=0;

    if(A_SIG==0)
       pulses++;//moving forward
    if(A_SIG==1)
       pulses--;//moving reverse
    Serial.println(pulses);
    attachInterrupt(1, B_RISE, RISING);
}

Show the code that currently works (when motor turns slowly) so that we can infer on WHY it does not work when motor turns faster, and HOW to make it run better. Arduino.SE is not a site to have ALL the code done for you!

Never Serial.print() from inside an interrupt service routine. Instead, have loop() print pulses periodically. Also, there is no need to detachInterrupt() if you are attaching a new interrupt.

I built a measuring bench using a glass slide (intended for DRO) with quadrature output. I found the Arduino was easily overwhelmed and would miss beats. I also tried implementing a D flip flop to halve the resolution of the slide. Ultimately, I put a LS7166 IC in the prototyping area of the freeduino eleven I was using and then performed a PORT read on D0-D7.


text:
WDT & Software RESET in ESP8266 + Arduino IDE
I am working on ESP8266 in Arduino IDE. I want to know how to Software RESET the ESP8266. Any sketch/example would be useful. Moreover, how to initialise WDT in ESP8266.
Kindly help!

Software reset in ESP8266 is achieved using ESP.reset()
as per WDT, the other answer has info on that, i.e. software WDT is cleared using yield() - hardware WDT is not accessible through software


text:
100 hz Square Wave of 50% duty cycle in digital pin 3 and verifying with pin 4
I am stuck on this for a while, I am trying to generate a 100 hz square wave with 50% duty cycle in pin 3 and trying to verify it with wire at pin 4; I am getting 64000 but not 100 in serial monitor.

#define LEDPIN 3

uint16_t val2= pulseIn(4, HIGH);

ISR(TIMER1_COMPA_vect) { digitalWrite(LEDPIN, !digitalRead(LEDPIN)); }
void setup() {
Serial.begin(9600);
pinMode(LEDPIN, OUTPUT);
// initialize Timer1 (the 16-bit timer) using channel A output compare
noInterrupts(); // disable global interrupts
// TIMER 1 for interrupt frequency 100 Hz:
cli(); // stop interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
TCNT1 = 0; // initialize counter value to 0
// set compare match register for 100 Hz increments
OCR1A = 19999; // = 16000000 / (8 * 100) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei(); // allow interrupts
//TCCR1A = 0; // Timer/Counter Control Register 1A
//TCCR1B = 0; // (both control registers need to be configured)
//// set compare match register to desired timer count:
//OCR1A = 15624; // Output Compare Register 1A (i.e., for channel A)
//TCCR1B |= (1 << WGM12); // CTC (Clear Timer on Compare Match) mode
//TCCR1B |= (1 << CS10); // for 1,024 prescaler; UNO has a 16 MHz clock
//TCCR1B |= (1 << CS12);
//TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable global interrupts:
}
void loop() {
uint16_t val = OCR1A/8;

ICR1 = val -1;
OCR1A = val/2 - 1 ; // 50% duty cycle for pin 3
//OCR1B = val/2 - 1 ; // 50% duty cycle for pin 4
//uint16_t val2= pulseIn(4, HIGH);
Serial.print(val2);
delay(1000);
Serial.print("\n");

}

You wrote:
uint16_t val2 = pulseIn(4, HIGH);

It makes no sense to call this here, as the timer has not been
initialized. You probably cannot expect anything but a timeout in this
context.
noInterrupts();
cli();

These two are synonyms. No need to repeat yourself. Actually, no need to
block interrupts at all.
sei();
interrupts();

Ditto.
OCR1A = 19999; // = 16000000 / (8 * 100) - 1

This is supposed to fire interrupts at 100 Hz. But if you want a
100 Hz output signal, you should fire the interrupts at 200 Hz
(two interrupts per cycle). Thus:
OCR1A = 9999; // = (16 MHz / 8) / (2 * 100 Hz) - 1

Then,
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

This is configuring Timer 1 for an external clock source. If you
want ÷8 prescaler, you should only set bit CS11. Check the datasheet.
uint16_t val = OCR1A/8;
ICR1 = val -1;
OCR1A = val/2 - 1 ; // 50% duty cycle for pin 3

This doesn't make any sense to me. Why are you setting ICR1? Why are
you changing OCR1A although it was already configured in setup()?
You can remove all this. Here is the loop() I used for testing:
void loop() {
    Serial.println(pulseIn(3, HIGH));
    delay(1000);
}

And it repeatedly printed 4955, which is quite close to the expected
value (namely 5000).

Thanks for your help.

TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10); is divide by 8.  It is shifting a couple zeros.  It is like TCCR1B |= (0b010 << CS10); but I like the 0b010<<CS10 format better if you are trying to document the three clock select bits.


text:
SD Card Mount Failed with Waveshare ESP32 using Arduino IDE
I'm currently working on a project using an ESP32 (the Waveshare ESP32 Driver Board), and I am trying to read data from an SD card, but consistently getting a "SD Card Mount Failed" error. I am using the Adafruit SD card reader breakout board and the Arduino IDE.
Here's how I've wired the SD card reader to the ESP32
SD card     ESP32
-------     -----
3.3V        3.3V
GND         GND
CLK         pin 18 (SCK)
DO          pin 19 (MISO)
DI          pin 23 (MOSI)
CS          pin 5 (SS)

And here's the relevant code I'm using to setup and test the SD card:
#define SCK  18
#define MISO  19
#define MOSI  23
#define CS  5

int setup_sd_card() {

  SPIClass spi = SPIClass(VSPI);
  spi.begin(SCK, MISO, MOSI, CS);

  if (!SD.begin(CS,spi,80000000)) {
    Serial.println("ERROR: SD Card Mount Failed");
    return -1;
  }
  uint8_t cardType = SD.cardType();

  if(cardType == CARD_NONE){
    Serial.println("ERROR: No SD card attached");
    return -1;
  }

  // Code to print out SD card details...

  return 1;
}

I've triple-checked my wiring but the code always fails at if (!SD.begin(CS,spi,80000000)). I've tried 3 different SD cards of different sizes, all formatted to FAT32 (64GB, 256GB, 1024GB)
Could the issue be related to the ESP32 not being a stock one because it has some hardware for driving an e-paper screen? Here is the schematic: https://www.waveshare.com/w/upload/8/80/E-Paper_ESP32_Driver_Board_Schematic.pdf

Can anyone suggest what might be the issue or what else I could try to debug this problem? Any help would be greatly appreciated.

The Waveshare esp32 appears to use the following SPI pins for the screen. P13:  spi clk; P14:  spi mosi; P15:  cs (not  shared). For clk, miso and mosi you should use the same pins. Try printing out the existing values of clk, miso and mosi without (re-) defining them. Only the cs pin is unique to the peripheral. The remaining SPI pins are a shared bus.

I moved the SPIClass declaration to a global variable and changed the frequency down to 4 from 80 but I'm getting the same result. Thanks for the suggestion.

I also printed out the existing values of MOSI/MISO/SCK/SS after deleting my redefinition of them and they are:
MOSI: 23
MISO: 19
SCK: 18
SS: 5
; I can try using the same SPI pins the screen uses and see if that works. I'll update this when I know.

There are at least two problems with your code.
First I think you have a typo in the frequency. Default frequency is 4 MHz, but your parameter in begin is 80 MHz, which I doubt will work.
You initialize the spi object on the stack in the function and then supply it to the SD instance. The spi object on stack will be removed when the function ends and the SD object will crash. It has to be an allocation on heap as SPIClass* spi = new SPIClass(VSPI); or a global variable SPIClass spi(VSPI);.
And since you use the default pins of VSPI you can use just spi.begin() without the pin numbers.

The issue turned out to be a faulty SD card.
I had tried other SD cards but must have used incorrect wiring for them.
EDIT: Here is the updated code:
#define CS        5
#define SCK       18
#define MOSI      23
#define MISO      19

SPIClass spi(VSPI);

int setup_sd_card() {
  spi.begin(SCK, MISO, MOSI, CS);

  if (!SD.begin(CS,spi,4000000)) {
    Serial.println("ERROR: SD Card Mount Failed");
    delay(1000);
    return -1;
  }
  Serial.println("Finished initializing SD card. Getting card type...");

  uint8_t cardType = SD.cardType();

  if(cardType == CARD_NONE){
    Serial.println("ERROR: No SD card attached");
    delay(1000);
    return -1;
  }

  Serial.print("SD Card Type: ");
  if (cardType == CARD_MMC){
    Serial.println("MMC");
  } else if(cardType == CARD_SD){
    Serial.println("SDSC");
  } else if(cardType == CARD_SDHC){
    Serial.println("SDHC");
  } else {
    Serial.println("UNKNOWN");
  }
  Serial.printf("Total space: %lluMB\n", SD.totalBytes() / (1024 * 1024));
  Serial.printf("Used space: %lluMB\n", SD.usedBytes() / (1024 * 1024));

  Serial.println("SUCCESS! (SD CARD)");

  return 1;
}

does it work with the code as it is in the Question?

I just edited my answer to add the code that works. It's the same as above with the two suggestions given in the comments.

so it doesn't begin at 80 mega? what about 8 mega?


text:
How to control a DSP-G1 programmatically/electronically?
I want to generate music/sounds for a video game I am making with my son (using an Arduino Mega and a 240x320 LCD graphical display). I have a basic understanding of the MIDI protocol. I've been a computer programmer for over 30 years. I read the MIDI implementation in the DSP-G1 manual, but I don't understand how to go from this to sending the right signals from the dev board to the chip pins.
Everything I find is about connecting a physical MIDI device. Can anyone possibly provide or point me to information on how to control the DSP-G1 programmatically/electronically? I think I need some hardware or software to serialize MIDI protocol bytes into a sequence of voltage changes, but all my searching leads me to info about a physical device.

You've got the wrong side of the circuit, you want a midi out circuit.

@ChrisStratton No, he wants to know how to replace this circuit when not using the electrical MIDI protocol.

@CL. that would be off topic for an Arduino site and also wouldn't really make any sense, since an Arduino could readily be made to drive that with a transistor.  Much better to plug into the gear by the existing connector than to modify it.

The purpose of the MIDI output circuit is to convert the TTL signal into a 5 mA current.
The purpose of the MIDI input circuit is to convert the current back into a TTL signal.
If the Arduino and the DSP-G1 are part of the same circuit (and share the ground), you can omit these conversions, and connect the Arduino's TX directly to the LPC810's RX, without any other components needed. (The LPC810 requires a 3.3 V power supply, but its RX pin is 5 V tolerant.)
MIDI was designed to work with most microcontrollers, so it uses standard UART signals at 31250 baud. The only configuration you need is:
Serial.begin(31250);

Yes, you understand what I am trying to do. Sometimes a simple thing is harder to find than a more complex one.  So to confirm my understanding, I need to use the Serial methods, in particular Serial.begin(31250), followed by a series of Serial.write() calls to send a stream of bytes the same as I would write to a file, per the MIDI file format, e.g., https://www.csie.ntu.edu.tw/~r92092/ref/midi/

And it seems this will automatically go to TX0 (pin 1) on an UNO. Any need to do anything with pinMode()? What if I wanted to use TX1 on a MEGA?   Thanks for your help!

And I would have no need of the optocoupler, correct?

What is sent over a MIDI cable is not a MIDI file, but only the actual MIDI events/messages. There are no timestamps; bytes are sent in real time. See the actual MIDI specification.

Serial goes to the first UART; the others are Serial1, Serial2, etc.

I'm supposed to avoid comments like "thanks" so... ahem... I appreciate your reply. It makes so much sense in hindsight that the chip would act on my MIDI commands in real time -- I wouldn't expect it to do buffering, so what else could it do? And, yes, I went back to https://www.arduino.cc/reference/en/language/functions/communication/serial/ and it does tell about Serial1, etc.; I must have skimmed over that part before. Good stuff to know. Your guidance has given me enough confidence to part with $25 and try this thing out!


text:
Matching the blink of an LED to midi music
I have a function that plays a song and lights an LED corresponding to the note that is being played. when the same note is played consecutively(i.e E in bar 6) instead of the LED turning on and off for each time the note is played the LED appears to remain lit. how do i get the LED to go no and off for these notes to better synchronize with the music being played? The delay of 414 is being used as quarter notes etc.
void songlist (int song){
if (song==1){
songpage=1;
playpage=0;
mainpage=0;
tonepage=0;
lcd.clear();
lcd.setCursor(4,0);
lcd.print("ListeningTo:");// Print a message to the LCD.
lcd.setCursor(1, 1);
lcd.print(menuP1);
//Plays Mary Had a Little Lamb
//Bar 1
 noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x3E,100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3C, 100); //Quarter note: C
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[2], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[2], HIGH);
noteOff(0x90, 0x3C, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 2
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Half note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(828);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

//Bar 3
noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3E, 100); //Half note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(828);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 4
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x43, 100); //Quarter note: G
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x43, 0);

noteOn(0x90, 0x43, 100); //Half note: G
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[4], LOW);
delay(828);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x43, 0);

//Bar5
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3C, 100); //Quarter note: C
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[2], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[2], HIGH);
noteOff(0x90, 0x3C, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 6
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

//Bar 7
noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 8
noteOn(0x90, 0x3C, 100); //Whole note: C
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[2], LOW);
delay(1656);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[2], HIGH);
noteOn(0x90, 0x3C, 0x00); //"Silent" note that makes sure the note stops playing.
delay(2000);
//End song
}
}

First, write a helper function so that you do not have so much repeated code, and call it for each note:
void playNote(int midi, int row, int col, int len)
{
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    noteOn(0x90, midi, 0x00);
}

...
//Bar 1
playNote(0x40, 3, 1, 414); //Quarter note: E
playNote(0x3e, 2, 4, 414); //Quarter note: D
...

Then, change it so that the note-off command and the LED switching can be done at different times:
void playNote(int midi, int row, int col, int len, bool short_led = false)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOn(0x90, midi, 0x00);
}

can you explain the use of the bool short  led?

wouldn't a second delay effect the timing of the notes?

Set short_led to make the LED light for a short time. The sum of len1 and len2 is always the same as len.

when i try to add a back button in the songlist function it dosent work

if (songpage==1){
if (BackState==HIGH){//leaving song
posP=0;
Page=2;
Play(posP);
}
}

i want to be able to go back once the song starts playing to stop the song.

The back button has nothing to do with this question.


text:
Arduino on battery getting unstable if temperature falls
i am building an outdoor sensor with a combination of a custom Arduino board and a battery (+solar charging). I experience strange behavior when the temperature falls below a certain value (i can reproduce it by putting it in the freezer), regardless which type of battery i am using. The custom Arduino runs without power-regulation, straight from the 3.7volts the battery can provide.
How can i prevent this to happen? I guess a little heating would be not really a solution as i am trying to consume as less energy as possible.
Would a (step up) regulator possibly help? Any other ideas?
---Update---
Thanks to your comments here i figured out, that the AVR 328p should not be operated below a voltage of 3.7v if run at 16Mhz. As i am running with a 3.7v LiPo Battery that could easily explain my problem i guess. My first try to decrease the processor speed to 8Mhz with a Prescaler worked, but the GSM Fona does not seem to like it. So i would like to try something in between like 10Mhz or 12Mhz. As the prescaler does not support this, my question is: can i just use another crystal or would i have to modify something in the code/bootloader as well?

Lithium chemistries may not like cold, so consider something else.  Also make sure you clock is in spec for the voltage and that your brown out fuses aren't set high.

AFAIK all battery chemistries have problems with cold: Capacity drops, current delivery drops, and internal resistance increases, so the voltage over your device drops. Not sure if a step up regulator would help, since the battery may still be too current limited in the cold. Perhaps an EE question? Not an expert, but I imagine a combination of more batteries and a regulator would help.

As others have mentioned, most batteries have problems at low temperatures. In very cold conditions I used to keep batteries next to the body. You could test this by running in the freezer with the battery outside.

In theory you could need to adjust the capacitors on the crystal, in practice it is likely to just work, especially if you can find the specs of the original and order something similar.  But figure out how low the voltage is really dropping if loaded when cold - and consider if rising impedance may be a better model than dropping nominal voltage.

see instructions for 12Mhz bootloader here: http://ceptimus.co.uk/?p=102

To answer your modified question:
Running the ATmega328p at 16Mhz with 3.7v is out of spec - see this EESE answer for reference or the ATmega datasheet - so the obvious solution would be to lower its speed to 8Mhz.
But since you also mentioned that there is an additional GSM breakout board involved (Adafruit Fona), which expects UART (in auto-baud mode) Rx/Tx connection, it might not be that trivial. Further exploration of the Fona library's source code reveals that it has several hard-coded delays (see Adafruit_FONA.cpp::begin, for example), but its core seems to be implemented inside the Adafruit_FONA::readline method, which uses an underlying Stream, which in turns comes from a Software/Hardware serial object, as shown in the FONAtest.ino example that comes with the library.
From my experience, Software/Hardware serial should work fine on 8Mhz, except maybe when using high baud rates, which is solvable.
The hard-coded delays doesn't look like they should cause actual damage except for delay, but you could cut them in half just to see if you can make the library work.
Additional aspect that you should consider is the comment from Adafruit's Fona product page, regarding pin Vio:

This is the pin that you MUST drive with an external voltage from
  3V-5V to set the logic level converter

So, despite that from the datasheet, the Fona seems to have a voltage regulator, you might still want to consider adding a decoupling capacitor between Vcc and Gnd of your battery, to  mitigate transient current draws from any component in your circuit.

Actual GSM (even in comparison to its more modern replacements) involves quite high current, I could easily see the first transmit attempt triggering a brown out when the battery is cold.

@Chris that's a very good point

Excellent hint Omer - i also had checked the library for delays etc. and cut them in half - but i didn't have the baud-rate in mind. Instead of 4800 i am now initializing Fona with 9600baud and everything seems to work fine so far, it is running since hours now.

When using battery, always use a step-up converter, something like LTC3525 or NCP1402. A direct connection of unregulated battery voltage to an analog input can give you a good information on the remaining capacity while the step-up converter still provides stable 3.3V for operation.

No.  This is throwing expense and inefficiency in a direction far removed from the problem, which is simply that the chosen cell won't deliver useful energy.

I beg to differ. A step-up converter assures the microcontroller to work until the very end of battery capacity and enables reporting low-battery status. Assuming the battery is providing accurate voltage is energy efficient (about 15% more efficient) but far from reliable.

A converter can't obtain energy which isn't there.  Additionally, over discharging rechargeable lithium cells prevents their reliable recharging.

True, but the microcontroller is rather sensitive to low voltage when running on higher frequencies and that seems to be the problem with Stephan's outdoor sensor in cold environment. That's why I think the converter might be useful. As you have already pointed out in your comment, reducing the frequency actually enables the chip to run on much lower voltage so this could be an alternative way to go. Though you can not rely on reference voltage any more if it is not regulated, but this is another story.

It's most likely that the cold weather is messing with your batteries. I don't know what battery types you've tried, but this site says that Lithium batteries (Not Li Ion, but standard single use, expensive, lithiums) hold up well in very cold and very hot environments. For rechargeable batteries the site recommends NiMH batteries. Of course, we all know that lead acid batteries hold up well in cold (Or else our cars wouldn't start!), so those are also a viable option. Lead acids can be purchased in somewhat small forms, but they may still be too big for your purposes.
For the other part of your question, yes a regulator will help. It's rarely acceptable to run directly off a battery without a regulator. Since your application is low power you'll want to use an efficient switching regulator (Search for modules, not individual chips). Remember that a battery's output changes based on its charge level, temperature, current draw, and other things I'm likely forgetting. Using a regulator mitigates these effects as regulators are less affected by temperature and current draw than the battery that supplies it (Hopefully).
So to summarize: Use Lithium batteries, or NiMH if you need to recharge, or Lead Acid if you need a ton of capacity and size isn't a limit. Then get a switching regulator module. Best of luck with your project!

No, it is quite normal to run processors such as the ATmega off unregulated batteries whose useful curves fall within their input range.  Please review the specs before making recommendations.


text:
The Arduino Sketch does not save in Arduino folder location
I have just installed Arduino on Mac OS. The Arduino folder is created under Documents. But whenever I save the sketch it gets stored in some ghost location and gives an error, the same name already exits. Upon finding the location of file. It gets stored under this directory(Hidden).
/private/var/folders/_v/nbrwcsh51wd2k07kfhy9vhjm0000gn/T/untitled1010592992.tmp/sketch_sep28a

How can I move this location to my documents folder. In Arduino preferences, I have also changed the location of sketch, still it does save in above location.

I appreciate this is a issue with the Arduino IDE, but you might get more help on a Mac forum.

Hi @CodeGorilla, I am afraid that goes a bit beyond the IDE - I am experiencing the same issue with arduino-cli

Download the latest IDE from Arduino.cc
Drag your Arduino application icon to the trash.
Open up terminal and type rm -r ~/Library/Arduino15
Delete the Arduino folder in your Documents folder for good measure
Drag the newly downloaded Arduino application to your application folder and see how it goes from a clean install.

Failing that PlatformIO IMO is a much better IDE for developing on these platforms : http://platformio.org/

isn't the "Arduino folder in your Documents folder" the place where OP might have saved his precious projects?


text:
Parse HTTP Request Arduino
I am sending a HTTP Request to my WiFi module http://192.168.4.1/STA/ID=HelloWorld/Pass=Testin123
How can I parse above string in Arduino. First I need to check for STA, if it exists, continue to scan the string. Put Value of ID, in this case HelloWorld should be store in String data type SSID and Value of Pass, in this case Testin123 should be store in String data type Pass.
How can achieve above using ARDUINO code! Please help.

Are you sure you don't need to parse GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1, as that is what's send in the http request?

I would use strtok() using / as the token separator.

@Gerben Exactly that is!

Your incoming string, as Gerben has mentioned, will actually be more like:
GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1

My personal preferred method is to use strtok() to split the string up.  I'd use a two-pass method for this.
First split the string up into three parts - one GET, one the request, and the third the request type (though you don't need to use that for anything).  Assume the string is in C string incoming:
char *get = strtok(incoming, " ");
char *request = strtok(NULL, " ");
char *rtype = strtok(NULL, " ");

The request is now pointed to by the *request pointer and the string has been sliced up in-place.  So now you can do something similar with the request, this time splitting on / instead of space:
String SSID;
String Pass;

if (request != NULL) {
    char *part = strtok(request, "/");

    bool seenSTA = false;
    while (part) { // While there is a section to process...

        if (seenSTA) {
            if (!strncmp(part, "ID=", 3)) { // We have the ID
                SSID = String(part + 3);
            } else if (!strncmp(part, "Pass=", 5)) { // We have the password
                Pass = String(part + 5);
            }
        } else if (!strcmp(part, "STA")) {
            seenSTA = true;
        }

        part = strtok(NULL, "/");
    }
}

I thought Strings are evil :D

@TisteAndii they are, which is why I do it all as C strings and then finally convert it to String which Anuj wants (supposedly).

@Majenko What about STA part? How to check that?

The same way as the others, but you don't need to specify the length since it's the entire string you are looking for. if (!strcmp(part, "STA")) { ... whatever here ... }

@Majenko I tried this but It can't find STA in entire link. Always showing Not found. Here is ArduinoCode

You can't nest like that. You get exactly ONE part of the string each pass through the while. If you want to only look for specific things if you have seen STA then you have to remember the fact that you have seen STA in an earlier pass.

@Majenko What actually I need to do is, confirm the presence of STA in string. If it is not present, do not enter into loop. If it exits, search for ID and Pass. It should only be single loop process. No need of while loop. Also using while() loop in arduino void loop() is not preferred, it crashes the program.

There is absolutely nothing wrong with using while on any platform. If it takes longer than the watchdog timeout then kick the dog. I have told you what you need to do. What part of it don't you understand?

I have enhanced my example to show you explicitly how to implement it.

@Majenko It worked well. Sorry for bothering you everywhere! I was really confused. It works well now. I understand the whole thing as well.


text:
esptool.py error Cannot configure port, something went wrong. PermissionError(13, 'A device attached to the system is not functioning.', None, 31)
When trying to upload my firmware to an ESP8266 board using Arduino IDE 2.2.1 I get
A fatal esptool.py error occurred: Cannot configure port, something went wrong. Original message: PermissionError(13, 'A device attached to the system is not functioning.', None, 31)

All of my research says that this is a CH340 driver problem, this is not the case. I did try reinstalling the driver. I use Termite as a Serial Monitor which communicates with my ESP8266 just fine. I can use the Arduino Web Editor and upload to the serial port through the Arduino Create with no issue, this has to be an Arduino specific issue are there any fixes for this?

try another version of the Arduino IDE

Same here, exactly the same problem. I did uninstall and update the driver and it still throws this error.


text:
Problem with Bing generated code for automated chicken coop door
Glenn from Sweden here. I was wondering if some kind soul could help me out here.
My partner bought a cheap chinese knock-off automatic chicken coop door that operates based on sunlight. Link to the actual chicken coop door In the morning the door opens and at the evening the door closes. It does this (from my humble understanding) with a  LDR, a 5v dc motor and a small circuit board. The main problem is that the door opens way to early (about 07:00 am) with the risk that predators may snatch the chickens and there is no way to regulate the opening/closing times.
What I would like is the following:
I would like the door to open at 10:00am and close at 21:00pm every day of the week using the existing 5v motor. I do have some 28BYJ-48 step motors and A3967 driver boards I bought 10+ years ago, but then I would have to start modify physical things to get it to fit. I rather not do that if it’s possible to use the original parts.
Now, coding is way over my head. Some people can draw beautiful things with paints and brushes, others can not. I can get some LED's to flash but I just can’t wrap my head around ”advanced” coding like this project. That is why I, out of desperation, tried to get Bing A.I. to write the code for me. I can compile the code without any errors, but it doesn’t work IRL. The motor does not start at the specified time, and sometimes the motor starts to spin out of the blue but doesn’t stop spinning. I have installed ”Time (1.6.1) by Michael Margolis” in the Arduino Library Manager to get the timer function to work. Is that the problem?
I must mention here that the three leads from the SN754410 originally was routed to pins 7,8,9 on the Arduino, but since it didn't work I tried switching them to 3,5,6 in case it had something to do with the analog output?
With the original electronics the door opens and closes mechanical fine, but I don’t understand how the ”brain” knows when to stop the motor so it doesn’t start to crunch the gear on the motor. There are no microswitches at the end points or anything…
I added the red and green LED's (got Bing to include them in the code) just to be able to see when the door opens/closes if dark outside).
I understand a Fritzing layout is preferable so I did my best to create one. Its my first time so please bear that in mind.

    // Include the Time library
#include <TimeLib.h>

// Define the pins for the motor controller
#define ENA 6
#define IN1 5
#define IN2 3

// Define the pins for the LEDs
#define GREEN_LED 10
#define RED_LED 11

// Define the times for the motor actions
#define START_TIME 1825 // 10:25 AM in 24-hour format
#define END_TIME 1925 // 21:25 PM in 24-hour format
#define DURATION 20 // 20 seconds

// Define a variable to store the current time
int currentTime;

// Define a variable to store the motor state
int motorState;

// Define the motor states
#define STOPPED 0
#define CLOCKWISE 1
#define COUNTERCLOCKWISE 2

void setup() {

  setSyncProvider(getTime);

  // Set the motor pins as outputs
  pinMode(ENA, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);

  // Set the LED pins as outputs
  pinMode(GREEN_LED, OUTPUT);
  pinMode(RED_LED, OUTPUT);

  // Stop the motor and turn off the LEDs initially
  stopMotor();
  turnOffLEDs();

  // Set the time to sync with the computer's time
  setTime(17,27,10,7,10,2023); // hour,minute,second,day,month,year
}

void loop() {
  // Get the current time in HHMM format
  currentTime = hour() * 100 + minute();

  // Check if the current time matches the start time or the end time
  if (currentTime == START_TIME || currentTime == END_TIME) {
    // Check the motor state and switch it accordingly
    switch (motorState) {
      case STOPPED:
        // Start the motor clockwise and turn on the green LED
        startMotor(CLOCKWISE);
        turnOnLED(GREEN_LED);
        break;
      case CLOCKWISE:
        // Stop the motor and start it counterclockwise after DURATION seconds and switch the LEDs accordingly
        stopMotor();
        turnOffLED(GREEN_LED);
        delay(DURATION * 1000);
        startMotor(COUNTERCLOCKWISE);
        turnOnLED(RED_LED);
        break;
      case COUNTERCLOCKWISE:
        // Stop the motor and start it clockwise after DURATION seconds and switch the LEDs accordingly
        stopMotor();
        turnOffLED(RED_LED);
        delay(DURATION * 1000);
        startMotor(CLOCKWISE);
        turnOnLED(GREEN_LED);
        break;
    }
  }
}

// A function to stop the motor
void stopMotor() {
  // Set the enable pin to low
  digitalWrite(ENA, LOW);

  // Set the motor state to stopped
  motorState = STOPPED;
}

// A function to start the motor in a given direction
void startMotor(int direction) {
  // Set the enable pin to high
  digitalWrite(ENA, HIGH);

  // Set the input pins according to the direction
  if (direction == CLOCKWISE) {
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    motorState = CLOCKWISE;
  }
  else if (direction == COUNTERCLOCKWISE) {
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, HIGH);
    motorState = COUNTERCLOCKWISE;
  }
}

// A function to turn on a given LED pin
void turnOnLED(int ledPin) {
  // Set the LED pin to high
  digitalWrite(ledPin, HIGH);
}

// A function to turn off a given LED pin
void turnOffLED(int ledPin) {
  // Set the LED pin to low
  digitalWrite(ledPin, LOW);
}

// A function to turn off both LEDs
void turnOffLEDs() {
  // Turn off both LED pins
  turnOffLED(GREEN_LED);
  turnOffLED(RED_LED);
}
  // A function that gets the time from the computer
time_t getTime() {
  // Check if there is serial data available
  if (Serial.available()) {
    // Read the serial data and convert it to a time_t value
    time_t t = Serial.parseInt();
    // Return the time value if it is valid
    if (t >= 946684800) { // Check if the value is after 1 Jan 2000
      return t;
    }
  }
  // Return a zero value if there is no valid time
  return 0;
}

The code in the switch makes no sense to me.   It instantly starts and stops the motor with no time for the motor to do anything.

there is no such time as 21:00 PM ... it's either 21:00 or 9 PM

start by writing simple code that runs the motor for 500 ms, stops the motor and quits ... expand to alternating directions

it may be simpler to cover the LDR and then shorting it with a relay

Thanks for your input. I'll try looking for someone who can write the code for me instead. Been sitting the whole weekend with this now.

I'm wondering if you hadn't considered the idea of manipulating the light sensor with an LED instead of playing around in the guts of this thing.

Try to decrease the sensitivity of the LDR by placing white translucent plastic or paper over the lense. This will not be exact.

Never ever accept random code you found by a search engine, especially if AI is involved. To extend, in the context of ChatGPT and similar projects, this is true for any "information" encoded in perfectly worded AI answers. These AI hallucinate, their only feature is perfect small talk. AI is not our friend, always check what it claims.

timeage: looking into your idea right now :) I was so caught up in the idea I had to control the motor that I couldn't think of anything else. This simple trick is so much easier. Great tip!

@Glenn You're probably better off asking about some of this in a forum or discord/irc/chat which handles vagueness and uncertainty and (in the case of chat) a moving target better than stack exchange, where they're designed to have back-and-forth exchanges with potentially multiple people. What jsotola and gil mentioned are similar thoughts on the same axis with various tradeoffs between in control/reliability and invasiveness/effort. But only so much of this has to do with your code, motor drivers, and potentially not the UNO you're using either.

@timeage Is that a subtle way to say get the heck out of this forum? ;-P Anyway you guys (especially timeage) pointed me in the right direction and i'm grateful for that (got a working prototype now but I will buy one of those RTC's as originally suggested by @chrisl) As a newbie its darn hard to know where to turn to get help. Tried to register on Arduino.cc and post my question in the forum, turns out to be near impossible to get that far. So where does one turn? Thanks again everybody. You've been very helpful and I feel I now have the goal in reach.

@Glenn LOL, no. What I'm getting at is the "this forum" thing. It's a Q&A site. It works a little differently from a forum. There's at least one subreddit for Arduino, discord server, IRC channel, and as you mentioned the official forum. All of them designed for something like dialogue, which can help if you're a bit lost. If you fall in with a good crowd, people just help each other out with stuff. It doesn't matter quite so much if things evolve as you go.

@timeage Man i'm getting old... I actually had to look up the meaning of subreddit (and i'm still a bit confused). I'll try to find a forum then XD

Using generative AI is only really helpful, if you have enough knowledge to work further with the generated code. Current LLMs are not as plug and play as many believe them to be.
Timemages idea of covering the LDR with an LED in your control seems very reasonable. Then you don't need to hassle with the motors. Try taping one if your LEDs to the sensor and use a blink code to test that. You might need a brighter LED, depending on the LDR. Just make sure to use a transistor in low side switch configuration, if the needed current for the LED is greater than 20mA, which is the maximum continous current for a digital output pin (small bipolar transistors are very cheap; you will find much information online when searching for something like arduino transistor low side switch).
Then about the time keeping: The Arduino itself is not good at keeping time accurately over a longer span. Due to manufacturing differences and temperature clock drift your time will be very much off after some days. For this you need a RTC (Real Time Clock). It has a very precise internal clock, so it can keep time accurately over long timestamps. You can buy ready to use RTC modules which also include a battery backup, so that the clock doesn't loose time on powerloss. Often these modules are build with the DS3231. There are also libraries for this RTC, for example this one. Look at the provided alarm example, because that is what you want (code triggering on specific times of the day). Use that example as starting point and make the LED turn on and off at these alarms. That are only small changes to the existing example code.

I'd never thought to use a LED with the LDR as I don't understand how this will work. Do you mean the LED would act like the sun and therefore could be controlled precisely with on/off times? As I'm writing this I guess that is what you mean. Hey, that's pretty clever and yet so simple! As I'm new to electronics, what is the most power efficient way I can achieve this? Do I use a Arduino Nano, or is there an even easier way?

(I can no longer edit my last comment) So I tried timeage's solution to use an LED to simulate the sun and it worked like a charm! "HIGH" for one minute, then "LOW" for one minute and so on just to try it out. Now, for the door to remain open between 10:00 to 21:00 the LED would have to be set to "HIGH" for 9 hours. How do I do this practically? Is there a better solution than using let's say an Arduino Nano? I mean, I would have to power the Nano which draws extra power from the batteries. Is there a small chip or something that can be programmed to control the LED instead?

LDR = Light dependent Resistor (Eller ljus beroende resistor). A Arduino (independent on model) has a clock that will drift and needs to be adjusted. You could use a more precise clock module, a RTC (Real Time Clock) of if you have WiFi/internet and uses an ESP6266 or ESP32 then you can use NTP. And lastly something is a Arduino,.