There is only a very slight chance that you meet the holdDuration >= 4000 condition in the while loop. Only when holdDuration will be exactly 4000 the while loop will be executed AND the subsequent test in the if statement will pass.

The serial print commands can easily take long enough to have millis() jump from a number less than 4000 to a number higher than 4000 in a single pass of the while loop.

To prove this assumption, increase the while test to holdDuration <= 4100 and see if the intermittent effect goes away.


analogWrite deals with PWM pins, those are digital pins. See https://www.arduino.cc/en/Reference/AnalogWrite

So connect the LED to one of the PWM pins and change the sketch accordingly. On the Uno those are pins 3, 5, 6, 9, 10, and 11.

The analog pins A0 - A5 are input pins. The value is read using the analogRead(pin) function.


Regarding 1, it's true that EEPROM has limited write cycles. Mostly it can be much more, but it's only guaranteed upto that number, so I can imagine you don't want taking the risk to be lucky.

Regarding 2, other solutions could be external SRAM, which can be much more than just 1 KB, but also adds some extra components, thus cost and more important power. When that SRAM is full (can be many KBs), you can transfer it to the SD card.

Another (added) improvement you might think of (if you did not already) is data compression (trying to store the 50 bits in less bits), but this will cost some 'computing' power.


Passing messages across computers and/or microcontrollers with different architectures can be a real pain (endianness...). So do not fall into NIH / reinventing the wheel traps but keep standing on the shoulders of giants! Several message serialization protocols exist.

BSON
MessagePack
Protocol Buffers
CBOR (Concise Binary Object Representation)
...

Several implementations of such protocols exist (even for Arduino).

I suggest to have a look in a search engine for such protocols and add Arduino.

I've found:

BSON

ardubson

MessagePack

msgpack-mcu
arduino_msgpack
MsgPacketizer
msgpack-arduino
ArduinoJSON serializeMsgPack / deserializeMsgPack

Protocol Buffers

nanopb

CBOR

Arduino-Cbor

...

PS: You might read https://scottlocklin.wordpress.com/2017/04/02/please-stop-writing-new-serialization-protocols/
and have a look at https://xkcd.com/927/
Just choose a giant compatible with your requirements ;-)

https://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats may help


Error 101 Server Did Not Report Size from OTA Upgrade framework via git hub

The ESP8266httpUpdate library wants to know in advance how large the file is before it starts downloading it.  It wants to know this so it can tell, before trying to download (and program), whether or not there's enough space for it. If the size of the file isn't provided by the server it will report the error that you are seeing.
The size of the file is provided by the web server by means of the Content-Length HTTP response header read by HTTPClient.  This header is received in advance of the file content.
Your main code appears to contain a correct link to raw .bin file,
#define URL_fw_Bin "https://raw.githubusercontent.com/programmer131/otaFiles/master/firmware.bin", and reports the following headers:
cache-control: max-age=300
content-security-policy: default-src 'none'; style-src 'unsafe-inline'; sandbox
content-type: application/octet-stream
etag: "b2ecfb5dc91587c089acdaace446b0d7b00863c9f42dffb36c7983c103d3a98a"
strict-transport-security: max-age=31536000
x-content-type-options: nosniff
x-frame-options: deny
x-xss-protection: 1; mode=block
via: 1.1 varnish (Varnish/6.0), 1.1 varnish
x-github-request-id: 8728:2B67:9AFD3:AD0EC:6008FCFF
accept-ranges: bytes
date: Thu, 21 Jan 2021 04:03:32 GMT
x-served-by: cache-bos4651-BOS
x-cache: MISS, HIT
x-cache-hits: 0, 1
x-timer: S1611201812.154162,VS0,VE1
vary: Authorization,Accept-Encoding
access-control-allow-origin: *
x-fastly-request-id: bfc9702929b91be55d7aa040465a230436918e01
expires: Thu, 21 Jan 2021 04:08:32 GMT
source-age: 20
content-length: 270016

The content-length: 270016 at the bottom shows that this should work.  But your changed code that uses #define URL_fw_Bin "https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay_ino_esp8285.bin is to the HTML page for downloading the file, which does not report Content-length, for me anyway, but then it's the wrong URL anyway.
Regarding the "101 error", it's -101 (negative) defined here, and like they said, it is not an HTTP status code,  it is just a value used by the ESP8266httpUpdate library.


Tone() conflicts with IRremote library (multiple definition of `__vector_7')

Exactly as @MichelKeijzers wrote the issue is caused by "IRremote" using same timer as "Tone" and the solution to this problem is a little dirty.

Since Tone is included in ArduinoCore (and compiled) we can't easilly modify it so the only thing that worked for me is to modify boarddefs.h file of IRremote library. Since it's code is easilly available after downloading it using "Library Manager" included in ArduinoIDE.

In my tests I used ATmega328P settings.

Edit C:\Users\youruser\Documents\Arduino\libraries\IRremote\boarddefs.h and look for your processor number.

For ATmega328 the definition is #define IR_USE_TIMER2

I simply changed it to use #define IR_USE_TIMER1

And compilation was successfull.

Sketch uses 2746 bytes (8%) of program storage space. Maximum is 30720 bytes.
Global variables use 242 bytes (11%) of dynamic memory, leaving 1806 bytes for local variables. Maximum is 2048 bytes.

My code:

#include "IRremote.h"

#define NOTE_C5  523
#define NOTE_E6  1319

int melody[] = {NOTE_C5, NOTE_E6};

void setup() {}

void loop() {
  for (int thisNote = 0; thisNote < 2; thisNote++) {
    tone(3, melody[thisNote], 300);
  }
}


Download https://github.com/RobTillaart/Arduino/archive/master.zip
Copy the Arduino-master/libraries/DHTstable subfolder of the downloaded file to the libraries subfolder of your sketchbook folder. You can find the location of your sketchbook folder at File > Preferences > Sketchbook location in the Arduino IDE.
Change the first line of your sketch from:

#include <DHT.h>

to:

#include <dht.h>

Now when you try to compile the sketch you will still encounter many errors. However, these are caused by a paucity of semicolons, not by the DHT library, and thus off-topic for this question.


Your best bet would probably be to interface with a colorimeter.  There is a tutorial for an open source colorimeter here:

http://www.appropedia.org/Open-source_colorimeter

IORodeo also sells a shield:

http://www.iorodeo.com/colorimeter

Vernier sells a colorimeter that may be suitable for your project & Sparkfun sells a shield to interface with Vernier sensors.

If a colorimeter doesn't work you would have to use an electrode, which is pretty expensive and has a shelf life.


The link you provide looks rather old and I don't think it applies to UNO Revision 3 as it has more pins than on the diagram you show.

I suggest you rather take a look at this Arduino UNO link which contains uptodate information about the UNO; in there you will see that for R3, the "power rail" has been extended and has the following pins, left to right:

1 unlabeled pin (can't remember what it is)
1 IOREF pin (used by shields to know if they should operate as 3.3V or 5V devices)
3.3V regulated output
5V regulated output
2 GND pins
Vin pin: this pin can be used in 2 different ways:

either as a voltage supply input (instead of using the power plug or the USB); the input voltage should be in 7-12V range and will be regulated internally (by the board circuits) to 5V
or an output supply voltage (if you plugged voltage supply through the power plug or the USB plug) that is a "copy" of the voltage input through the power plug or USB plug (not regulated yet)


Looking for a cheap small arduino ish board

I'd suggest investigating the ESP32.

It's not only a far more powerful chip than any normal Arduino, but it has both WiFI and Bluetooth Low Energy, all on the one chip.

It's available as surface mount modules, similar to the ESP8266, and there are a number of small development boards that have been created around it as well.


You will need several things.

First I assume that the power supply is a 12V power supply. If it isn't, better to get one (3.5m of leds can be 4.2A, so even a 12V 5A supply is fine). Note: you didn't specify the led size, so the current can vary a lot. But a standard one is a 60 leds/m 5050 leds, which means 60mA/5cm, or 4.2A for a 3.5m strip.

Anyway you will need a 12V power supply to power both the strips and the arduino (through the Vin pin).

You will then need a way to control the leds from the arduino. Since the required current is too high for the arduino, you will need to put a transistor. I tend to prefer nMOS over NPN, but just because of the way I learned them. Anyway just get a low-side transistor (either an nMOS or an NPN) capable of handling the required amount of current (at least a couple amperes, better if they are >5A) and the proper circuit to turn them on. Usually you will just need one or two resistors. You will need to connect the +12V to the plus terminal of the leds, the drain (or collector) of the transistor to the ground pin of the led you want to control, the source (or emitter) of the transistor to ground and the gate (or base) of the transistor to the arduino through the proper circuit.

Then the remote controller. You did not specify what kind of remote controller you want to use, but usually you can cope with a IR receiver (e.g. the TSOP382 or any other) and the proper decoding. A lot of remote controllers are already mapped in the library IRremote; you just have to read the value it provides; inside the arduino you will need to save the codes for the commands (you will have to train it first) and then simply compare.

This is a generic answer, because you did not provide any details. If, implementing this, you encounter any problem open a specific question with what you did up to that point.


I ended up deleting my copy of RTCZero and installing a new one via the Arduino IDE library manager. This solved the issue.

The difference between my local copy and the upstream one is in the standbyMode() function. I had the following PR merged into my local copy of this function:
https://github.com/arduino-libraries/RTCZero/pull/46/files

After I installed the clean copy I went and replaced the standbyMode() function's content with the following:
https://github.com/arduino-libraries/ArduinoLowPower/blob/892594adbccf45b198fc067ea994048c76523936/src/samd/ArduinoLowPower.cpp#L18


Interfacing TRRS headphone to Arduino Uno

TRRS relates to the style of the jack plug used: Tip Ring Ring Sleeve. You still need to amplify the signal with a microphone preamp the same as your electret (in fact it will be an electret in there anyway).

And then the Arduino cannot process human speech. You may be able to use a voice recognition module to get it to respond to specific commands, but the Arduino by itself has no hope of even thinking about it.


Unintended reaction: Sketch makes LEDs turn on and of randomly/LEDs don't react

Your code has a serious bug here:

if(button == HIGH){

    digitalWrite(act_pin[j], HIGH);

    j = j+1;

    button = LOW;
}

You increment j without any boundary so it will have the following cycling values:

0, 1, 2, 3 ... 32767, -32768, -32767 ... -1, 0 ...

Hence, quickly act_pin[j] will return garbage...

The solution is easy, you must limit j to [0,1,2,3,4], just replace the j = j + 1 line as follows:

j = (j + 1) % 5;

% is the modulo integral operation that will give you the reminder of dividing j by 5, which is always strictly less than 5, and it cycles as you want.


You can use shift registers to control the relays. This will only use 3 pins and allow you to use the xbee.

For the RGB LEDs you can use the TLC5940 to control 16 channels, so you will need two, giving you 32 channels. This is a PWM chip with serial interface.

Considering you will be using the board linked. It is driven by transistors, so you can use the shift registers.

For the power supply, if you will be operating all of the relays at the same time it will draw about 650 mA (9x72mA), you will need a separate 5V power supply for the relay board, as I believe drawing that much current will heat the board and regulator a lot. If one at a time it will not draw too much, so its possible you can run it all off the Arduino.

A forum post of someone running 360 relays with shift registers.


Waking Raspberry Pi on time schedule using Sleepy Pi

I have the same problem and  I just saw that they fixed a bug in a library used by SleepyPi

More specific, the RTC library file DS1374RTC.cpp reads since March: '2015
(which is after the question was asked)

  Releases
    ========
    V1_0 - 10 Aug 2013 - Initial release
    V1_1 - 11 Mar 2015 - Mod:    Added "ackAlarm" and "ackRTCOSF" functions to aid Alarm use
  - Bugfix: Changed the way the "SetAlarm(tmElements_t   &tm)" was updating the Alarm time. It wasn't mapping correctly

They also added a new example to wake up the Pi: WakePeriodicallySimple.ino


On the Uno, why does VIN require 7-12 volts and the USB only 5 volts?

USB's Vcc pin is assumed to be a stable, 5v supply, and is directly connected to the 5v bus on the Arduino board with no further regulation. Vin is assumed to be an unknown and unregulated voltage in the range of 7-12 volts.

The 7v minimum is a requirement of the design of the on-board voltage regulator which needs the 2v "head room" to maintain its output at 5v. A 5v power supply could be designed with a larger input range, even including voltages less than 5v, but the simple design used on the board covers a range of sources at a lower cost than a higher-performance power supply.


What happens is:

You send a pulse of 10 ms with TTL signal. This is the first line in the picture below.
Than you call pulseIn. This waits for the echo pulse.
The echo pulse will become high when reflected. This happens internally in the module. This is the second line.
The echo pulse will stay high depending on the time it took to be echoed back and makes a pin high (echo pin). This is the third line.
Than your pulseIn command returns with the time (of the echo pin length).


Is it possible to program/flash ESP8266MOD(07) With Arduino UNO

Yes you can.

Take a look at this detailed guide.

The most important thing to keep in mind is that you have to connect from the ATmega16U2's perspective, so you have to swap RX and TX:

You'll probably want some buttons to facilitate the flashing process:


How to connect accelerometer, GPS, microphone and a GSM module to a Arduino?

It depends.

If you are a beginner, do it in steps:

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

The key is to split up your (for a beginner) big project into smaller easier to handle projects.

If you want to add an LCD, depends fully on YOUR requirements; we don't know exactly what you want. If you send all data via WIFI in principle the receiver can display it, but maybe you have a good reason to display it on a display.


Can do I make an Arduino program that can decipher telephone touch tones?

It is possible to decode DTMF tones with only a few common external components. The trick is to turn the analog audio into a digital signal, and then check the timing between the leading and trailing edges in order to figure out which tone is present.

First, create a 1.1V bias using a voltage divider. This bias will connect to both a capacitor that is coupling the audio, as well as one of the analog inputs. Note that phone lines have high voltages on them at times, and you must have both isolation and voltage clamping in place before connecting a device to one.

Second, enable the analog comparator in the MCU. See the "Analog Comparator" section of the MCU datasheet for details. Configure the non-inverting input to connect to the internal bandgap reference, the inverting input to connect to the analog input chosen earlier, and the output to connect to the input capture facility.

Third, configure the input capture facility in the MCU. See the "16-bit Timer/Counter1 with PWM" section of the datasheet, with particular emphasis on the "Input Capture Unit" subsection. Note that there is no way to trigger the input capture on "any" edge, therefore you will need to either flip the capture edge select bit each time, or you will need to detect the tone from only one set of edges. Also note that you will need to use the overflow interrupt to increment your explicit "high bytes" counter in case the edges to be detected appear on opposite sides of the overflow.

Now that all that is done, all that remains is to compare the timing detected by the input capture with your internal table of timings and select the appropriate tone from that. But that's the easy part.


How to get number of available pins in code?

It is quite easy actually:

Serial.print("number of digital pins: ");
Serial.println(NUM_DIGITAL_PINS);
Serial.print("number of analog inputs: ");
Serial.println(NUM_ANALOG_INPUTS);

Note that these are compile-time constants defined as macros in a file
named pins_arduino.h. There is one such file for every board supported
by the Arduino environment. Just to take Curt J. Sampson's example, if
someone “made a board with an MCU with 100 digital IO pins available,
yet if only ten of these are brought out to pins on the board”, then the
macros would tell you you have 10 digital pins. Assuming of course that
you installed the proper support package for that particular board.


I've been looking at the same problem, and there is a lot of new stuff now that may still count as a DIY project, but cut out a lot of the leg-work.

On kickstarter there are a lot of new boards that can make it easy:
Here is a ready to go GPS tracking band:
https://www.kickstarter.com/projects/blipperbands/blipper-bands-safety-wherever-you-go?ref=nav_search

Spark-IO has a board that gives you 20,000 messages per month, so you could use it instead of a cellphone to send out the data.
https://store.particle.io/?product=particle-electron

U-Blox makes gps higher-end consumer GPS units that are used in autonomous drones.
There are also a lot of instructables that show how to do the GPS datalogging with while building a drone. These would be small enough and light enough to use while cycling.


How to change the topic_name string to PROGMEM?

My take on this is that you cannot save more memory on topic-name nor msg parameters. Their memory usage is already optimized.

The const keyword in the constructor declaration Publisher( const char * topic_name, Msg * msg, ... just tells the compiler that the parameter won't be changed throughout their life cycle. But their values will be defined at run-time during object creation when you issue something like this:

Publisher pb = new Publisher("topic", "message", ...);

So, they cannot be put into flash memory if they are not there already. But if the strings you pass on to the constructor are already in flash, then you're already saving those bits of RAM.

Finally, I just wanted to warn you not to modify 3rd party lib code extensively without comprehensive testing, like you are trying to do. You'll start to get strange behavior in your code. The slightest and simplest of changes may have unforeseen consequences.


Ethernet Shield - Multiple simultaneous connections cause TCP reset

I have received a request from the OP to move this to Network Engineering because it got no answers. I'm going to decline this for the moment because I doubt they will be familiar with the Arduino Ethernet shields.

The low-cost shields have a known limit on the number of connections they can handle simultaneously (no doubt limited by available RAM). From the page Arduino Ethernet Shield 2 we learn:

  It supports up to eight simultaneous socket connections.

You don't seem to be getting that, which makes me wonder if it is a code issue. It might help to post your code. If you make code that "blocks" while handling the first connection you may not accept the other ones in a timely way, leading to a reset.

Please post a Minimal, Complete, and Verifiable example.

I did a post about a tiny web server for the Arduino which uses a state machine to handle incoming data without blocking.

You may also be able to help yourself by using the HTTP header that requests that the connection be kept open, eg.

Connection: keep-alive

That might stop the client opening new connections in quick succession.


Parsing sd card file to polymorphic objects

There is no such thing as serialization/deserialization in C++. You can read the data values from an object, and you can write data values to an object, as long as you either expose the properties as public, or create "getter" and "setter" member functions.

It is then up to you to store and retrieve that data in whatever form you like.

You could store the raw RAM data that corresponds to an object, however if there are any pointers in that object they will be stored as just that - a pointer - which will be meaningless when reloaded. So it's better to store the data values manually.

How you store the data depends on what the data is. Yes, you can use JSON format if you so choose - it has good abstraction for storing strings, escaping special characters, etc. So it would be quite convenient - however, it's quite a heavyweight arrangement. A lighter method would be to store binary data directly, but that is inflexible and can't easily store different types of data in different ways for different objects.

CSV format is quick and easy to parse, but you have to manually deal with things like commas in data strings, etc.


Is it harmful to write to unused bits in PORT registers?

If the pins have no connection to the outside world (i.e., they don't have any actual pin associated with them on the SAM3X chip) then writing to the PORT (or indeed any other register associated with them) will have no effect whatsoever.

If they have a pin but that pin is not connected to anything, then there will be little effect.  There may be slightly increase current draw as the pin switches on/off, or you enable/disable the internal pullup resistor, but that's all.

If the pin exists and is connected to something on the board - maybe a button or LED, then you will basically be providing an output to that item.  If it's an LED it will flash.  However, if it's a button, and you provide an output opposite of its active state (i.e., provide a HIGH when it normally connects to ground when you press it) and that button lacks any current limiting resistance, then you could risk burning out that IO pin if the button gets pressed.

If the pin just goes straight to a header, then as long as nothing gets connected to that header then there will be no effect other than as detailed in the "pin present on the chip but not connected".


Is it possible to receive a 9 bit protocol on the Arduino Uno with Arduino?

If you want to set the UART to 9-bit mode, you will have to set the
UCSZ02 bit of the _ucsrb register to 1 in
HardwareSerial::begin().
For example:

void HardwareSerial::begin(unsigned long baud, byte config)
{
  // Mostly unchanged... but by the end:
  sbi(*_ucsrb, RXCIE0);
  cbi(*_ucsrb, UDRIE0);
  sbi(*_ucsrb, UCSZ02);  // set 9-bit data mode
}

Notice that you do not need to modify the Arduino core library for this:
you could set that bit in your setup(), right after calling
Serial.begin().

Then, in the HardwareSerial::_rx_complete_irq() interrupt
handler,
you will have to read the 9th bit as the RXB80 bit in UCSR0B, before
reading the low byte from _udr (emphasis in the datasheet). For
example, you could replace the line unsigned char c = *_udr; by:

bool is_address = UCSR0B & _BV(RXB80);  // read 9th bit first
unsigned char c = *_udr;                // then the other bits
if (is_address) {
  do_something_with_address(c);
  return;
}

where do_something_with_address() is the stuff you wanted to do in
another interrupt (no need for that, you are already in interrupt
context).

It is worth noting that, with an Arduino Uno, you will not be able to do
all this while sending data to the PC. This is because the communication
with the PC uses the only UART of the ATmega328P.


What software is available for use with AVRISP and USBASP on ATMega48, 328, 2560?

Almost everyone uses either AVRDUDE (directly or indirectly, e.g. via the Arduino IDE) or the upload capability in Atmel Studio. I cannot speak for AS, but AVRDUDE does require options to tell it which programmer and device to use. WinAVR includes AVRDUDE, but is not strictly required as Win32 downloads are available at the AVRDUDE site.


The TX and RX pins are connected directly to the USB to UART adaptor embedded in the board (an ATMega16U2 on the Uno R3, or a CH340G on a cheap Chinese clone). Anything that goes through the USB also goes through those pins.

You can also, if you must, use SoftwareSerial to get serial on any other pair of pins of your choice.


You should be able to create your own board definition with a custom boards.txt file as per https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification. As I see there are several usb features in the leonardo's definition. I would hope that the compiles inclusion of the 4K is based off of these flags and not the processor type.

Where the boards.txt would use the upload, bootloader sections from the Leonardo and the build from the uno.

This is all assuming the core library build does not use processor specific flags to include USB functions.

If you get such working. post back, I am sure others would be interested in such.

I recently ran into this 4K used limitation on a library demo that actually maxed out the UNO and had to put in a

#if !defined(__AVR_ATmega32U4__)
...

around a large chunk of extra features in the sketch to fit on the Leonardo.

I had assume (wrong) that this 4K was because I still included Serial.print which when over the USB's CDC on the Leo. But I see after a memory dump of an empty sketch they are still there.

C:\Users\mflaga\AppData\Local\Temp\build8958339595868119500.tmp>avr-objdump -d sketch_feb13a.cpp.elf > sketch_feb13a.cpp.elf.lst

Which makes sense. As the Leonardo still requires the USB-CDC client (the 4K) as to detect the 1200 Baud connect from AVR-DUDE as to stroke the remote reboot.

Hence making a custom boards.txt without USB in the build, also needs to have

leonardo.upload.use_1200bps_touch=true

removed.

Once loaded on the target, this would require the upload to be synchronized with a manual reset of the target. As the ability to remote reboot is lost.


Will Arduino Pro Mini 3.3V run at half the speed of 5V version?

If the board is running at half the speed (8MHz instead of 16MHz) then everything that isn't based on real time (i.e., millis(), delay() etc) will run at half the speed. It will all take twice as long to do everything.


Some findings:

Your for loop iterates over 71 results, but your array has only the length 70.
You may overwrite variables in the memory behind the array.
You can use else instead of else if (i >= 70 * 0.1) because it is just the negation of the if (i < 70 * 0.1). In the else case (i >= 70 * 0.1) is always true.

What is the type of myVariable? If you assign incompatible types (signage or length) an over- or underflow can happen. 32767 = 2^15 - 1 = 0b0011111111111111 (14 bits on) that looks pretty much like an underflow and a conversion of incompatible types.

EDIT:

By a second read of your question I saw another possibility of failure:

You copy the bytes of a two byte signed integer into 2 bytes and send it to matlab.

byte dataOut[2] = {
  highByte( LOG_myVariable ),
  lowByte( LOG_myVariable )
 };

Let's say you have a negative number in LOG_myVariable. In Memory this is represented with a one in the highest bit (MSBit) and the complementary bit string plus one (two's complement: See Wikipedia).

An Example:

16 bit signed int -1 is represented as 0b1111111111111111 you split it in two bytes 0b11111111 and 0b11111111. The you send it to Matlab.

Now it depends on how Matlab interprets the bytes. Are that unsigned int8 or signed int8? you combine the bytes like so:

 myVariableMATLAB = 256 * dataOut(1) + dataOut(2);

If Matlab interprets the bytes as unsigned  you get 256*(-1) + (-1) == -257 but that's not -1. And if it interprets the bytes unsigned it gets 256*255+255 == 65535 which is also not -1. I bet there is a negative number that gives you 32767.


Problems with green TWI (I2C) port on Arduino Braccio Shield

I fear we have a colloring issue. Your green is my blue ;-).
I have looked into the data sheet of the level shifter IC and TI only describes scenarios with a higher voltage on the right side and a lower voltage on the left side. Also the allowed voltage translations do not contain 5V to 5V. So I would say in equal voltage scenario the Level shifter may not work.
Answers

Q1: The TWI port is always used with 5V (not ~3V). The Arduino that is supposed to use the shield might be a 3.6V version (like a DUE or M0). Perhaps the TWI port is only intended for this use case: A low voltage arduino with a 5V device. I admit: This should be noted in the documentation. So perhaps Braccio shields work outside the specification and may works under normal circumstances. But meanwhile I begin to understand why they are out of busines ;-).

Supplement: the SCL and SCL signals are routed to two pairs of header pins as they are connected to different pins on different Arduinos. On a UNO you can not use A4 and A5 for analog as they are used for I2C for example. Do you use A4 A5 in any way? Or did you connect the second I2C pin pair in the power header when you had used the TWI connector? (rhetoric question ;-) of cause I will change the answer if you give me more information ;-) )

Q2: The 220k resistor is necessary as it limits the current through the chip if VRef1 is lower than VRef2. Removing it with 0 Ohms would be a bad idea. As long as 5V is used on both sides, nothing would happen. But if Vref1 is 3.6Volts, you would waste energy and perhaps the chip would take part at a grill fest.

Q3: Most I2C devices breakout boards already use their own pullup resistors. So lowering the pullups is not the best idea. -> too high current with LOW signals as the devices pull ups and the braccio pull ups are set in parallel.
-- There is a chance, that the resistors are too large for devices that don't use their own pull ups, but at a 100kHz bus speed I don't think, this could cause an issue.

BTW: You do not need to exchange the pull ups, if you insist to try out different values. Just use parallel resistors to lower the resistance (10K || 10K -> 5K) [|| means connected in parallel] (R || Rp -> (R*Rp) / (R+Rp))


Burning the Bootloader on Adafruit Feather 32u4

"Burn Bootloader" only works if you have a programmer connected to the device. The onboard bootloader in your Feather cannot change the fuses, even though the process may indicate it has done so.

You would have to connect an ICSP (In-Circuit Serial Programmer) to the correct pins (MOSI, MISO, SCK, RESET, VCC, GND). You can use another Arduino as a programmer by uploading a specific sketch to the Arduino to make it an Arduino as ISP.

The normal bootloader on an Arduino emulates this kind of device to allow programming by serial/USB port, but it has limitations. The ICSP process is the native way to get a program onto the AVR chip, and is the only way to set fuses.

EDIT:

This AVR USB Bootloader Datasheet states on page 3:

  • Boot Reset Fuse The Boot Reset Fuse (BOOTRST) can be programmed so
  that the Reset Vector points to the Boot Flash section start address
  after reset. Once the user code is loaded, a bootloader command
  (“start application”) can start executing the application code. Note
  that the fuses cannot be changed by the MCU itself. This means that
  once the Boot Reset Fuse is programmed, the Reset Vector will always
  point to the Bootloader Reset and the fuse can only be changed through
  the serial or parallel programming interface. The BOOTRST fuse is not
  active in the default factory configuration.

That document also references AVR282: “USB Firmware Upgrade for AT90USB” (Note, I could not find this on the Atmel website.) This document details the FLIP program, at Atmel tool for uploading firmware over the USB DFU interface and setting configuration settings, etc.

This doc has a FAQ section which states:

  Can I modify the fuse bits using Flip? • No, Flip cannot modify the fuse bits. To modify the fuse bit you can use either the JTAG ICE
  MKII, the AVRISP MKII, or parallel programming

So, while this may not be a definitive answer, it appears at this time that "burning fuses" cannot be done over USB on the 32u4. If that's not the case, I'm sure the site would welcome the new info.


What you can do is:

Read character by character and copy it to a temporary buffer of the maximum length of one line.
When you parsed an end of line symbol, you start parsing the (complete) line in the buffer.
In this line parsing (preferably a separate function), you parse the line, using string to type conversion functions, like atoi (string to an inter) etc. Also you can use the C function strtok to split the string based on a symbol (e.g. comma).
After parsing the line, clear the buffer (you already processed it), and continue filling the buffer again until it is full.
Don't forget to check for end of file.


Strange behavior from uint32_t, acting like signed int (Nano clone)

%d expects a signed int. %u expects an unsigned int. Insert the l modifier to expect a long in each of those cases. So you need a format code of %lu to print a uint32_t.
The following code:
#include <Arduino.h>

void setup()
{
    uint32_t x=110000;
    char buf[50];

   // Open console
   Serial.begin(115200);

    sprintf(buf, "%%d: %d\n", x);       Serial.print(buf);
    sprintf(buf, "%%u: %u\n", x);       Serial.print(buf);
    sprintf(buf, "%%ld: %ld\n", x); Serial.print(buf);
    sprintf(buf, "%%lu: %lu\n", x); Serial.print(buf);
}

void loop() {
   ;
}

prints this:
%d: -21072
%u: 44464
%ld: 110000
%lu: 110000


How do I make a toggleable Infrared motion detection module

Consider using a state machine with 4 states.  Currently you only have 2 states.  One where "bool1" is TRUE and another when "bool1" is FALSE.  The 4 states needed are:

When the LED is OFF & the PIR is NOT-ACTIVE.
When the LED is OFF & the PIR is ACTIVE.
When the LED is ON and the PIR is ACTIVE.
When the LED is ON and the PIR is NOT-ACTIVE.

As you travel between these 4 states, you will find you only want to turn the LED ON when traveling between states 2 & 3.  And you will only want to turn the LED OFF when traveling between states 4 & 1.


I am trying to read input from 5th PIN of PORT B?

There seem to be several, separate issues in your question.

One is a simple matter of language. In English, “1st” is an abbreviation
for “first”, which is an ordinal adjective applied to an item in a list
meaning that there is no other item before it in that list. In the same
vein, “5th” means “fifth”, which applies to the item that has exactly
four items before it. For instance, the list of pins of port B is {PB0,
PB1, PB2, PB3, PB4, PB5}. PB0 is the first in the list, and PB4 is the
fifth. The fact the first item bears the number 0 makes this confusing.
Thus, I recommend avoiding ordinal adjectives altogether and instead
calling the pins by their names, like “digital 13” (Arduino naming) or
“PB5” (AVR naming).

The second issue, and probably your main concern, is about the floating
input pin. You cannot expect a reliable reading from a floating input. I
will not try to explain why, as the issue has been discussed ad nauseam
here and elsewhere. Just do a Web search. The simplest solution is to
use the built-in pull-up resistor and externally connect a push button
between the pin and ground. You will read LOW whenever the button is
pressed:

void setup() {
    pinMode(13, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    if (digitalRead(13) == HIGH)
        Serial.println("HIGH");
    else
        Serial.println("LOW");
}

The last point is about going bare metal and learning how to use the I/O
registers directly. A small warning first: you have to keep in mind that
this is board-specific. You tagged your question with both “arduino-uno”
and “arduino-mega”, but these boards have different pin mappings
(digital 13 is PB7 on the Mega). The general way of using the DDRx,
PORTx and PINx registers is the same across all AVR chips, but is not
portable to Arduinos based on a different architecture.

So let's assume this is intended to work only on an Uno, Nano, or
other board based on an ATmega328P.
Judging from the example code you show, you seem to
already understand pretty well how these registers work. There is no
problem in your code, beside the fact that it requires an external
pull-up. If you want to enable the internal pull-up, you have to set the
appropriate bit in PORTB. This can seem confusing, as the same register
is used for pull-up control (when the pin is in input mode) and for
output control (when the pin is an output). Essentially, each GPIO pin
has four distinct electrical states which are controlled by to I/O bits:

│ DDRxn │ PORTxn │ state        │
├───────┼────────┼──────────────┤
│   0   │    0   │ INPUT        │
│   0   │    1   │ INPUT_PULLUP │
│   1   │    0   │ OUTPUT LOW   │
│   1   │    1   │ OUTPUT HIGH  │
└───────┴────────┴──────────────┘

The example program above can be translated to low-level AVR style as
follows:

void setup() {
    DDRB &= ~_BV(PB5);  // input mode
    PORTB |= _BV(PB5);  // enable pullup
    Serial.begin(9600);
}

void loop() {
    if (PINB & _BV(PB5))
        Serial.println("HIGH");
    else
        Serial.println("LOW");
}


Looks like a smartwatch but only has a gps tracker and password

So basically what you want is a GPS-Receiver(-Shield), a SIM900(-Shield), a Fingerprint-Sensor, a Battery-Pack and a micro-controller. (And of course some kind of server)

Have you made some research for the parts you want to use and considered their size and power consumption? Sounds completely feasible but your Arduino Prototype will look like it fits into a lunch-box. The idea is a good one and worth trying. (albeit I don't know what the password/fingerprint is good for).

But you will have trouble to shrink it into the size of a smartwatch.


What would be the best way to sense the tank level of a 1000L water tank?

There are some ultrasonic sensors that are specifically designed for this very application. I have used something simlar as a water level sensor, and they seem to be reliable. The sensor that I used was from MaxBotix, and had a range of up to 5m, resolution of 1mm, and both analog and serial data output. Interfacing it with an Arduino was very easy.

Have a look at This article for details


analogWrite causes value from IR receiver to change

Because IRremote uses timer 2 by default, and the PWM output on pin 11 is generated via OC2A. Either edit IRremoteInt.h to use timer 1, use a pin on timer 1 for PWM, or frob OCR2A directly instead.


esp32 http client response only 200 didn't receive the data after that

A 200 response doesn't guarantee that your payload will actually contain any data. It depends on the server. The server might determine to respond with a 200 code but still not return any JSON code for your request.
I am not at all sure, but the server may be rejecting your request because it doesn't like your user agent. I have seen my own ESP8266 supply ESP8266HTTPClient as its user agent for HTTP requests. You can see from the source code of the HttpClient class that this is the default:
HTTPClient::HTTPClient()
    : _client(nullptr), _userAgent(F("ESP8266HTTPClient"))
{
// etc...
}

You might consider setting the user agent for your http client object:
http.setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0");

If you'd like to investigate a bit more, you might use curl from the command line (this works on linux) to emulate the http request being formulated by your ESP device:
curl -vA "ESP8266HTTPClient" http://jsonplaceholder.typicode.com/comments?id=10

On my linux machine, this returns all the HTTP header information, followed by some JSON for the url you've specified in your code:
[
  {
    "postId": 2,
    "id": 10,
    "name": "eaque et deleniti atque tenetur ut quo ut",
    "email": "REDACTED@EXAMPLE.COM",
    "body": "voluptate iusto quis nobis reprehenderit ipsum amet nulla\nquia quas dolores velit et non\naut quia necessitatibus\nnostrum quaerat nulla et accusamus nisi facilis"
  }
]

Maybe try that with the other url and see what comes out?
You might also modify your post with the Serial output of your sketch to provide more detail.


Easy way to upload sketches using MIDI (without RX pin removed)

To allow the bootloader on the Arduino MCU to communicate with the USB chip, the TXD/RXD pins are connected:

These connections have 1 kΩ resistors so that the signals of the USB chip do not interfere with your own hardware too much. However, this means that your own hardware can easily override those signals.

In this case, your MIDI hardware actively drives the RXD line to a high level.

You is no way to work around this in software.
You could try to replace the optocoupler's pull-up resistor (270 Ω) with a 10 kΩ resistor, which would make the USB controller's signals ten times stronger than the MIDI ones, but this might make the signal edges too slow.
To reliably prevent conflicts, you have to add a disable function to the MIDI receiver, or power it down, or disconnect it.


How to connect a phone's camera to an Arduino?

That video shows a Bluetooth connection between the smartphone and the Arduino.

(A USB connection between the smartphone and the Arduino might be better in some ways).

details

If you want more information after watching a video like this, click the "show more" button underneath the video to see the details.
Those details clearly say "The Nexus S device connects to the IOIO board via Bluetooth, and uses the smartphone's camera in conjunction with OpenCV and the external IR sensors to control the vehicle."
Those details also include a link to
"Android Based Robotics".

The OpenCV image processing software runs on the smartphone. In this autonomous application, the image data never leaves the smartphone. The software on the smartphone reduces the image data to two integers -- the X,Y pixel location of the center of the green ball.

The Arduino and the Bluetooth link can easily handle a few integers at over 200 Hz. Neither one is suitable for handling live video data.

The Arduino could probably act as the controller.
The camera could send the X,Y pixel location of the green ball to the Arduino; while the Arduino collects all the other sensor data; then the Arduino could use that to decide what to do; then send the appropriate control signals to the motor drivers.

However, in this autonomous toy car it appears that the the smart phone acts as a controller.
The Arduino collects all the other sensor data, forwards that data to the smartphone; then software on the smart phone takes that data and the X,Y pixel location of the green ball; then the smartphone decides what motors need to turn; then the smartphone sends the appropriate commands to the Arduino, and the Arduino demultiplexes those commands to the motor drivers.

For even more details on building robots using smartphones and Arduino, see

"Android Based Robotics" ( http://www.socsci.uci.edu/~jkrichma/ABR/ ).
The Tinkernut video
"DIY Smartphone Controlled RC Car" ( https://www.youtube.com/watch?v=xsJ7176fLNw )
goes into more details of how to connect a smartphone to an Arduino via Bluetooth.
Android Based Robotics: ground robot manual
( https://groups.google.com/forum/#!topic/android-based-robotics/_H8Zmvbxx-M )
"Simple RC car for beginners (Android control via Bluetooth)"
( http://solderer.tv/cxemcar/ ) ( via http://english.cxem.net/ ).
Communicate with Your Arduino Through Android (using USB cable)
ArduinoCommander:
"Control your Arduino board from your Android device over Bluetooth, Ethernet or USB"


How to make the motor car move left-forward / left-backward/ right-forward/ right-backward

Regarding the pins - I wanted to find out the physical (hardware) connections.

Pending an updated answer I presume the EA and EB will set the speed for two motors and EN2/EN3 and EN4/EN5 control the direction of the motors. If that's the case you could make the car turn sideways but changing the speed of only one of the motors. For example:

void forwardLeft(void) {
  analogWrite(EA,128); //speed 0 - 255
  analogWrite(EB,255); //speed 0 - 255
  digitalWrite(EN2,LOW);
  digitalWrite(EN3,HIGH);
  digitalWrite(EN4,LOW);
  digitalWrite(EN5,HIGH);
}

I assume that EA is the left motor and EB is the right motor. This will make the right one rotate twice as fast as the left one so the car should go forward, but also turn left. If you keep this running the car should end up going in a circle. By making the 128 lower you will change how fast the car is turning.

The other functions should be similar.

Caveat emptor - of course this will mean nothing if the beginning assumptions are incorrect.

EDIT
Can't figure out why it doesn't work without having the thing in my hands. Have not found a schematic for that board, but intuitively it should work as described above.

Things you can do to try to figure out - try different numbers instead of 128, the speed of the motors might not vary linearly with the voltage. What you need to obtain is to have one motor go twice as fast as the other one and in the same direction. That should turn the car around.


Connecting a Long Stem Thermometer to an Arduino to automate the recording of temperature in an experiment

Interfacing with a temperature sensor such as the DS18B20 (https://www.sparkfun.com/products/11050) would be much simpler than trying to interface with a thermometer with unknown internals.

Theoretically, yes, you can use the thermometer you posted, but it won't be simple. The only way to know what you would have to do to interface with it is to open it up and see what's inside. You would still have to calibrate it though to make any sense of the readings you get from it.


Syncing/taking external clock for SPI on Arduino Due

For your external source to be an SPI bus master, it has to be the only one generating the clock signal. Yet, calling SPI.transfer() also generates a clock signal from the Arduino; both devices are attempting to drive the clock line simultaneously, hence your problems.

You have to bit-bang this or manipulate the SAM registers yourself to configure it as a slave; the SPI library doesn't support slave mode.
In order to bit-bang, you'll have to define your own MOSI, SCK, SS (and MISO, if you'll be writing to the master) pins and do all the sampling yourself with digitalRead(); there are no registers to be read from since you aren't using the SAM's SPI peripheral.

Since your SPI mode is MODE 1, it means the clock idle polarity is LOW, and that data is sampled on the falling edge. To bit-bang with digitalRead(), it is necessary that the SCK frequency be below 50 kHz (digitalRead() takes about 4us), taking overhead into account. You should use direct port manipulation, if you need a higher frequency. If you'll be blocking till you've read data, and assuming that the external source always sends data in byte units, then a basic algorithm:

Create a byte array to hold all the expected bytes
Define a byte variable (curr_byte, maybe) for holding each byte received
Wait till the SS pin goes LOW
Clear curr_byte to zero
Wait till SCK goes HIGH
Wait till SCK goes LOW
Read the bit on the MOSI line and shift it into curr_byte
If you've received up to 8 bits so far, save curr_byte to the byte array; if SS is still LOW, go to step 4, else exit this loop. But if you haven't received a complete byte yet, go to step 5.

After you leave the loop, you can then confirm the bytes you've received with Serial. If the external device can send data with any number of bits, then you should always check the SS line after you shift in a bit, to determine if the Due has been deselected or not i.e. if there are any more incoming bits.


Here's how to create the new mapped range with a dead zone. I used Servo.write() which specifies the position in degrees because I couldn't understand what microsecond timings you need, but it should be easy to change it back. I've also added some debug statements to print val as the joystick is moved.
#include <Servo.h>

// Constants for servo angles in degrees.
const int SERVO_MIN = 0;
const int SERVO_MID = 90;
const int SERVO_MAX = 180;

// Constants for raw ADC values of joystick positions.
const int ANALOGUE_MIN = 0;
const int ANALOGUE_MID = 512;
const int ANALOGUE_MAX = 1023;
const int ANALOGUE_THRESHOLD = 100;

Servo esc;

void setup()
{
  esc.attach(9);         // Specify the esc signal pin as D9.
  esc.write(SERVO_MID);  // Move servo to mid position in degrees.
  Serial.begin(115200);
  Serial.println();
  Serial.println("Servo Test");
}

void loop()
{
  static int old_val = -1;   // Initialise to invalid value.
  int val = analogRead(A0);  // Read input from analogue pin A0.

  // Process val if it has changed.
  if (val != old_val)
  {
    old_val = val;
    Serial.print(val);
    Serial.print(", ");

    // Create the dead zone as per Majenko's algorithm.
    val -= ANALOGUE_MID;
    int direction = val < 0 ? -1 : +1;
    val = abs(val);
    val -= ANALOGUE_THRESHOLD;
    if (val < 0) val = 0;

    // Create a new mapped range with a dead zone.
    val *= direction;
    val += ANALOGUE_MID;
    Serial.print(val);
    Serial.print(", ");
    val = map(val, ANALOGUE_MIN + ANALOGUE_THRESHOLD, ANALOGUE_MAX - ANALOGUE_THRESHOLD, SERVO_MIN, SERVO_MAX);
    Serial.println(val);

    // Move servo to new angle in degrees.
    esc.write(val);
  }
}


HC-SR04 ultrasonic sensor: How to check voltage on the ECHO pin

You have your leads backwards. But that doesn't matter, since there's nothing to measure. You'll only see a voltage (and even then only a brief pulse) when an echo is actually received.

You would need an oscilloscope to be able to read that voltage.


Can someone explain how to program i2C communications without using the library?

The AVR microcontrollers that Arduino uses have built-in hardware support for the said protocols.

That means that you don't have to write program to control the transmission/reception process but you only need to configure the appropriate registers and the hardware will initiate transfer and inform you when it's done.  I suggest you carefully read the datasheet of the microcontroller you are using with your Arduino and you should find all the information there.  It even has code examples, so you can actually copy-paste functions and use them in your program, here is one of the examples:

void SPI_MasterInit(void)
{
    /* Set MOSI and SCK output, all others input */
    DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
    /* Enable SPI, Master, set clock rate fck/16 */
    SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}

void SPI_MasterTransmit(char cData)
{
    /* Start transmission */
    SPDR = cData;
    /* Wait for transmission complete */
    while(!(SPSR & (1<<SPIF)));
}

The keywords with the capital letters are usually register and bit names: you can look them up in the datasheet.


Activate a DC motor for a fixed amount of time

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
boolean motorRunning = false;
unsigned long motorStartMillis;
unsigned long motorRunMillis = 180000;

void setup() {
   Serial.begin(9600);           // set up Serial library at 9600 bps
   AFMS.begin();  // create with the default frequency 1.6KHz
}

void loop() {
  IOvalue = 1000

  if (IOvalue = 1000) {
    //this is the motor I wish to run for 3 min
    myMotor->setSpeed(25);
    myMotor->run(FORWARD);
    motorStartMillis = millis();
    motorRunning = true;
  }

  // check if motor is running and time-to-run has elapsed
  if( motorRunning && (millis()-motorStartMillis > motorRunMillis) )
  {
    myMotor->setSpeed(0);
    myMotor->run(RELEASE);
    motorRunning = false;
  }
}


Try the following

Double-check the LCD soldering
Double-check your wiring
Ensure that the pins you are using for your LCD are not assigned to some other function. This caused jumbled, random characters here.


Sounds like you broke your fuses.

You may be able to enter programming mode by applying an external clock signal to the clock in pin (use another Arduino to generate it).  If that doesn't work then the only way to fix it is with a "High Voltage Programmer".

Nick Gammon has a very good tutorial here: http://www.gammon.com.au/forum/?id=12898


Using Air Quality Sensors like MQ135 to sense dust particles

The MQ sensors can not be used to sense dust particles. They are Electrochemical gas sensors which are sensitive for certain gasses. They are not sensitive for dust particles. Dust is not a gas, but tiny solid particles.


Digital input pin voltage treshold (voltage to register 1 or 0)

The titles of the graphs are actually saying what happens: the hysteresis.

In other words:

if the input level is high (greater than 2.6V), it will be considered high through the hysteresis area (until it goes below 2.2V)
if the input level is low (below 2.2V), it will be considered low through the hysteresis area (until it goes above 2.6V)

According to the description you gave, this should work for your case.
In case it doesn't, you have to condition it until the values you want to consider 0 and 1 are respectively below 2.2V and above 2.6V, with a safety margin, for good measure (say 30%).

The hysteresis is meant to prevent noise from causing unwanted spurious transitions: without safety margin, it should be greater than 0.4V.

You can dimension the safety margin to meet your needs.

But, for the sake of completeness, I'll say that it might be preferable to have a timer to trigger periodic sampling with the ADC.

If you know the maximum frequency at which every input can vary, you can sample it at twice that frequency and be sure that you will not miss anything. Again, this is theory, I would probably make it 4 times, to allow for unforeseen variations.

This works as long as the conversion time of the ADC is shorter than the maximum combined frequency at which you need to read the values.

The GPIOs, of course, are faster, but might require additional circuitry for the conditioning I mentioned earlier.


I Had a similar problem with a different display, It looks like you are printing the value without clearing the display so all the numbers print on top of each other creating those squares. try adding lcd.clear() in the loop to clear the display before it prints another value.


Interfacing unusual 4 digits 7 segments display

This display seems to have 32 addressable LEDs controlled by only
7 pins. Judging from this fact, and from the provided pinout table, it
looks like a Charlieplexed matrix.
A typical way to drive this kind of matrix is by looping over the
cathodes. You pull one cathode pin LOW, and then pull HIGH all the
anodes of the LEDs you want to shine which are connected to this
particular cathode. Wait a few milliseconds, then move to the next
cathode. It is important that all pins that are not involved in lighting
an LED remain in INPUT mode.
For example, let's say you want to light all the segments of the first
digit (display an “8”) while keeping everything else off. You first pull
pin 1 LOW (first cathode) and pull HIGH pins 2–5 (segments F, G, C
and D). Let that shine for a few milliseconds, then put everything to
high impedance (pins to INPUT) and move to the next cathode: pin 2
goes LOW and pin 1 (segment A) goes HIGH. And so on until you have
done all the cathodes.
For the coding part, I would suggest using a 7×7 matrix of booleans
telling whether a particular segment is meant to be lit. The indices of
the array would be row = cathode number and column = anode number. The
array would have the same structure as the pinout table you posted,
except for the fact that the lines and columns would have indices
ranging 0–6 instead of 1–7. This should make it easy to handle
refreshing the display.
Drawing the digits is a bit trickier than with traditional 7-segment
displays, as for each segment you will have to find its coordinates in
the matrix (cathode number and anode number). For this, I would use a
“mapping matrix” that stores the mapping (digit number, segment number)
→ (cathode number, anode number).
Below is a tentative, and untested, implementation of these strategies.
Note that I did not write a function to output a digit, but that should
be easy to implement on top of the set_segment() function defined
here. Besides, the question of how to draw a digit once you know how to
control individual segments is the standard 7-segment problem, for which
you should be able to find many tutorials.
Note that this code assumes you drive the display directly, using no
iterface other than current-limiting resistors. This carries the risk of
either overloading the cathode outputs or having the display be too dim,
depending on the current-limiting resistors. You may want to use
transistors for the cathodes, in which case you would have a set of
cathode pins different from the set of anode pins.
// Arduino pins connected to the display.
const uint8_t display_pins[7] = {2, 3, 4, 5, 6, 7, 8};

// Which segments are lit. Each segment is located in this matrix at
// the coordinates [cathode][anode].
bool segment_lit[7][7];

// Coordinates in the matrix above where a segment can be found.
struct SegmentCoordinates {
    uint8_t cathode;
    uint8_t anode;
};

// segments[digit][segment] gives the coordinates of
// any segment (0 = A) of any digit (0 = 1st digit).
const SegmentCoordinates segments[4][7] = {
// seg: A      B        C       D      E        F       G
    {{1, 0}, {2, 0}, {0, 3}, {0, 4}, {3, 0}, {0, 1}, {0, 2}},
    {{2, 1}, {3, 1}, {1, 4}, {5, 1}, {4, 1}, {1, 2}, {1, 3}},
    {{3, 4}, {4, 2}, {4, 3}, {0, 5}, {2, 5}, {2, 3}, {2, 4}},
    {{5, 6}, {6, 5}, {5, 4}, {3, 5}, {5, 3}, {4, 5}, {6, 4}}
};

// Turn a segment OFF (lit = false) or ON (lit = true).
void set_segment(uint8_t digit, uint8_t segment, bool lit) {
    SegmentCoordinates coordinates = segments[digit][segment];
    segment_lit[coordinates.cathode][coordinates.anode] = lit;
}

void setup(){}

void loop() {
    static uint8_t cathode;  // currently used cathode

    // Set the current cathode to OUTPUT LOW.
    digitalWrite(display_pins[cathode], LOW);
    pinMode(display_pins[cathode], OUTPUT);

    // Set the relevant anodes to OUTPUT HIGH.
    for (int anode = 0; anode < 7; anode++) {
        if (segment_lit[cathode][anode]) {
            digitalWrite(display_pins[anode], HIGH);
            pinMode(display_pins[anode], OUTPUT);
        }
    }

    // Let that shine for a while.
    delay(10);

    // Turn off everything.
    for (int pin = 0; pin < 7; pin++) {
        pinMode(display_pins[pin], INPUT);
    }

    // Move to the next cathode.
    if (++cathode >= 7) cathode = 0;
}

I used delay() here for simplicity. In production code you would
handdle the timings with millis() in a non-blocking fashion, in the
spirit of the “Blink without delay” tutorial.


Memory usage in AnalogBinLogger of SdFat library

how will a file-reader differentiate between a 10-bit value taking 2
  bytes and two 8-bit values?

The file AnalogBinLogger.h, which comes with the example sketch you
mentioned, contains the following:

// First block of file.
struct metadata_t {
  unsigned long  adcFrequency;     // ADC clock frequency
  unsigned long  cpuFrequency;     // CPU clock frequency
  unsigned long  sampleInterval;   // Sample interval in CPU cycles.
  unsigned long  recordEightBits;  // Size of ADC values, nonzero for 8-bits.
  unsigned long  pinCount;         // Number of analog pins in a sample.
  unsigned long  pinNumber[123];   // List of pin numbers in a sample.
};

Thus, the file reader just needs to be aware of the format of this first
block, and read the recordEightBits field in order to know whether
this is 8-bit data or not.

  Is SdFat's buffer also in SRAM?

Yes, that's the only sensible place you could have a data buffer. It's
allocated on the stack, only during the execution of the
logData() function.


Problem updating Arduino WiFi Shield's Firmware

I cant comment because of reputation... You've already upgraded the firmware. Just when you try upgrading again your wifi device is rebooting itself because of upgrading before.


Serial communication PC to Arduino using C and send via NRF

Working with serial in C on Linux is not as simple as opening a file and reading from it (though in some circumstances that can work).

You should open the file using open() not fopen(), then use tcgetattr() and tcsetattr() etc to configure the port.

For example:

#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>

struct termios oldsettings, newsettings;
int fd;

// This signal handler will close the port cleanly leaving
// it in the same state it started in
void sighandler(int sig) {
    if (sig == SIGINT) {
        if (fd >= 0) {
            // Restore the settings to original
            tcsetattr(fd, TCSANOW, &oldsettings);

            // Close the port
            close(fd);

            printf("Program teminated. Thank you for playing.\n");
            // Exit the program
            exit(0);
        }
    }
}

int main(int argc, char *argv) {

    // Trap CTRL-C to close the port properly
    signal(SIGINT, &sighandler);

    fd = open("/dev/ttyACM0", O_RDWR);
    if (fd < 0) {
        fprintf(stderr, "Error opening serial port: %s\n", strerror(errno));
        return 10;
    }

    // Save the settings
    tcgetattr(fd, &oldsettings);
    // Grab the current settings again to modify
    tcgetattr(fd, &newsettings);

    // Set the baud rate
    cfsetispeed(&newsettings, B9600);
    cfsetospeed(&newsettings, B9600);

    // Make it a raw port
    cfmakeraw(&newsettings);

    // Apply the settings
    tcsetattr(fd, TCSANOW, &newsettings);

    char c;
    printf("Press CTRL-C to terminate\n");

    while (read(fd, &c, 1) == 1) {
        printf("Got character 0x%02x\n", c);
    }

    fprintf(stderr, "Reception terminated: %s\n", strerror(errno));

    return 0;
}

No one ever said programming C was easy. It makes you appreciate just how much work the Arduino API does behind the scenes for you...

Also you need to be aware that the Arduino resets (if you use an Uno, Mega, or other board with a separate USB interface chip) when you open the serial port. You need to wait about 2 seconds after opening the port before you ever send anything, or whatever you send will be completely ignored.  You can do that with:

sleep(2);

after you have opened and configured the port.


How to add the Wiring S board to Arduino IDE v.1.6.2?

There are two things I do; I use the Serial.print(F("string/n")); which prints the data from flash rather then copying it to ram.  Keep as many of your variables local as possible, that will save ram.  This is done by defining then in the function, the added advantage nothing outside the function can change them.

Global and Static variables are the first things loaded into SRAM. They push the start of the heap upward toward the stack and they will occupy this space for all eternity.

Variables created in functions, are dynamically allocated objects and data. Unlike Global and Static variables, these variables can be de-allocated to free up space at function exit. But Every function call creates a stack frame that makes the stack grow toward the heap. This data is usable within the function, but the space is 100% reclaimed when the function exits!


Using Arduino audio to control an LED light

The Due or Tre may have enough power for this. The Yún may be able to offload it to the more powerful CPU. Every other Arduino will struggle with it.


Your question doesn't specify speed, cost, accuracy, or size, and it skimps on electrical and physical details (referring merely to 50–100 resistors and “a lot of cables”) so perhaps can't be properly answered.

ADC's (analog-digital converters) typically are high-impedance devices that measure voltages.  A resistor may be measured in many ways, a few of which are:

Place a known voltage across it; measure current through it
Drive a known current through it; measure voltage across it
Drive some current through it; measure both voltage and current using four-terminal sensing
Measure how long it takes a given capacitor to charge to a trip point, using a known voltage through the resistor under test
Use known resistances to null a Kelvin bridge

For some of the techniques listed above, measurement accuracy is little affected by multiplexer resistance; others might need to use a low-resistance MUX made with relays instead of a MUX ic like the 74HC4067.  Some of the techniques are suitable for wide ranges of resistance, others not; and some for high accuracy, others not.

Suggested Approach

Anyhow, those comments aside, circuits like the following might do the job.  If you have eight analog inputs on your Arduino, you could use up to eight multiplexers to measure up to 128 resistors.

In Figures 1 and 2 above, Rx is a typical unknown resistance, and Rs is a known standard resistor.  Both figures represent voltage divider circuits.

Effect of multiplexer transmission gate resistance

Let Rm denote multiplexer transmission gate resistance.  Rm is unimportant if the circuit of Figure 1 is used because Rm is tiny compared to the input impedance of a unity-gain follower op amp stage.

Rm might or might not be important if the circuit of Figure 2 is used. (a) If Rm differs somewhat from one multiplexer channel to another, Figure 2 may be unsuitable because calibration will be cumbersome.  (b) If Rm is comparable to Rx, Figure 2 is unlikely to produce high-accuracy results.

Whether unity-gain followers are necessary

Whether you need unity-gain followers depends mostly on the size of resistors you are measuring.  Arduino analog inputs are high-impedance (10⁸Ω, but with about 14pF capacitance to Vcc/2).  Atmel suggests analog source impedances of 10KΩ or less for best results.  [See (1,2,3) for additional discussion.]  Briefly:  If Rs+Rx is likely to exceed 20-40KΩ and you wish to measure quickly, use unity-gain followers.

Resistance Formulas

Let Vt be the voltage at the lower end of Rs in either figure.  Vt is the voltage that will be measured at an analog input Aj.

In Figure 1, because Vt = Vcc·Rx/(Rx+Rs), we have Rx = Vt·Rs/(Vcc-Vt).

For the circuit in Figure 2, an additional resistance Rm is in series with Rx, so Vt = Vcc·(Rx+Rm)/(Rx+Rm+Rs), whence Rx = Vt·Rs/(Vcc-Vt)-Rm.  If Rs and Rx are large (eg 40KΩ and 10KΩ) then ignoring Rm may cause only a fraction of a percent of error.  But if Rm is comparable to either of Rs or Rx, either use the circuit of Figure 1 or devote some inputs of each multiplexer to use as calibration inputs.

Analog input reference voltage

If Vcc is 5 V and we choose Rs four times as large as the largest resistance value that you intend to measure, then Vt will be between 0 and 1 V.  You can use an analogReference() call like analogReference(INTERNAL) [or analogReference(INTERNAL1V1) on a Mega] to set the analog reference voltage at 1.1 V, to maximize accuracy of measurement and to minimize the amount of current required through Rx.

Advantages of Figure 2

Unless Rm is a problem (as discussed above) the following advantages of Figure 2 suggest its use:

Lower power requirements:  In Figure 1, all the resistors under test always have current going through them.  In Figure 2, only 1/16 of the resistors are powered at any given time.  Also, by raising \EN to shut down the 4067's (or 74HC4067's if used) all the resistors can be powered off.
Less wiring and fewer parts:  At most eight Rs parts are needed, rather than one Rs per Rx.  Each Rx connects to ground and to one mux input, rather than to ground and to the junction of a mux input with an Rs.

Cable Note

For either figure, seven or eight wires run from the Arduino to each 4067 subcircuit.  One wire from each subcircuit carries Vt back to an analog input.  The other wires connect to all subcircuits in parallel: four channel select lines (A, B, C, D in figures, or S0-S4 in datasheets); Vcc; ground; and \EN unless that line is wired to ground.  Each 4067 subcircuit should have a bypass capacitor, eg 10-100 nF, from Vcc to ground.  Boards like the “Geeetech CD74HC4067 Analog Digital MUX Breakout Board” shown below (about $5 on ebay) might be used, or you could design a custom board and have it made at OSHPark or Seeedstudio.


Ethernet shield connected to local network, not to internet

Find a server that doesn't automatically switch modes to https as google does.  If you put 64.233.187.99/search?q=arduino%20HTTP/1.0   in your browser you'll see that it switches to https.

If make the same request via the wget terminal app it fails.

--2020-01-17 11:42:26--  http://64.233.187.99/search?q=arduino%20HTTP/1.0
Connecting to 64.233.187.99:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: http://www.google.com/search?q=arduino%20HTTP/1.0 [following]
--2020-01-17 11:42:26--  http://www.google.com/search?q=arduino%20HTTP/1.0
Resolving www.google.com... 172.217.4.132, 2607:f8b0:4007:80c::2004
Connecting to www.google.com|172.217.4.132|:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2020-01-17 11:42:28 ERROR 403: Forbidden.

There should also be an error returned to the client object which you can print out for debugging the conection.

Change your code to print out the return value of the client.connect call like so

void loop() {
      int result = client.connect(server, 80);
      if (x) {
        Serial.println("connected");
        client.println("GET /search?q=arduino HTTP/1.0");
        client.println();
      } else {
        Serial.println("connection failed");
        Serial.println(x);  // print out the error
      }
    }

One last thing, you set your dns server to 8.8.8.8 which should generally be set to your gateway / router of 192.168.1.1.


Is it possible to detect host usb device connected to arduino? and how?

You can't, using stock firmware. And with custom firmware it's still very difficult.

The USB communication chip on the Uno has no out-of-band means of telling the main MCU that it is connected to a host. You might be able to rewrite the communication firmware on the R3 to tell the main MCU over serial that it is connected, but the firmware on the main MCU will need to be written in such a manner that it will anticipate this.

If you want this to work then you should consider using one that has a native USB connection, such as the Leonardo. You will then be able to query the USB facility directly to know whether or not you are connected to a host.


The ADC for the accelerometer is 16 bit, yes. Also the data being sent out is in 16 bit format.

But what you are confusing is resolution and range.

The accelerometer can be programmed to have a sensitivity of 2g, 4g, 8g or 16g.  With it set to the least sensitive, that is 2g, the full range of -32768 to +32767 would equate to ±2g.

That's fine when you're measuring G-forces of up to 2g, but when all you are sensing is tilt then there is only 1g - the 1g the Earth exerts on it.

That 1g is half the 2g range, which is -16384 to +16363.  So round that up and give a little extra headroom to your calculations, and you get -17000 to +17000. It gives enough range in your calculations to give the full ±1g range "plus a little bit".


Power Arduino with 12V while using Serial Communication over USB

How to power an Arduino
Arduino can manage multiple power inputs at the same time while fully operational (incluide Serial - USB connection to the PC).

JAPAN JACK socket: an external source (a power supply, usually) must be connected to this socket, with the positive pole going to the central part of the jack, and the value must be ranging between 6 V and 20 V, even though the range recommended by the manufacturer is 7÷12 V, thus it is not advisable to use voltages that are lower than 7 V or greater than 12 V, if not in the case of a real need; 6 V may not guarantee a proper stabilization on the part of the regulator, it is in fact needed to consider the voltage fall of the protection diode, placed in series at the regulator’s input (whose purpose is to preserve the board from destruction in the case of polarity inversion on the jack); while values above 12 V would create an excessively high drop-out (an electric potential difference between the regulator’s input and output) that would cause a pointless overheating of the regulator, even with low levels of current draw.


Storing and sequencing output value (arduino)

I'm still not entirely sure what you want to achieve, but maybe this will help:
You have a global variable int weight, and in int Sampling() you create another int weight = scale.get_units() which you give a value.
That second variable is only accessible inside of Sampling(). If you want to use it elsewhere for storing or in other functions, change:
int weight = scale.get_units();
to
weight = scale.get_units();
and you can then use weight wherever you like in your code, also in servo10gr() and servo20gr().
You don't need to store a sequence of weights to drive the servos; you can just use the current weight immediately to drive a servo and then get a new weight.
If, however, you want or need to keep a list of weights for some reason, there's a bit more work to be done.
There are better ways of going about this, but let's see first if this solves your problem.


Problem with Software Serial: no response

SoftwareSerial cannot transmit and receive at the same time.  So even if you connected pin 8 to 9 with a wire, your sketch will not receive what was transmitted.  That's a guess without your wiring diagram.

NeoSWSerial can simultaneously transmit and receive.  It is a drop-in replacement for SoftwareSerial.

However, AltSoftSerial is even better, and it only works on pins 8 & 9.  Use that instead!

This answer compares all 4 serial types, including HardwareSerial.


What does an arduino sketch translate to before compilation?

The Arduino core libraries (which are nothing more than a bunch of C/C++ files - there is no such thing as the "Arduino" programming language), are compiled along with your source code. These files include all of the initialisation routines and function definitions for things like digitalWrite and so forth.

There is a main.cpp file that gets compiled which is pretty much nothing more than:

#include "Arduino.h"

int main(void) {
    //Initialise timers and things (internal)
    init();
    //Your initialisation stuff (setup)
    setup();
    //Loop forever
    for (;;) {
        //Calling your loop function
        loop();
    }
}

In terms of what your .ino file becomes, it is basically just copied to a temporary build directory and renamed to .cpp. There are some minor changes made, which is basically to just copy all of the function declarations and place them at the top of the file.

This process is actually why if you use your own header file which has some typedef in it which you then use in a function call, the code will break because the declarations get added above the #include statements meaning the custom type is used before it is defined.

If you go to the preferences you can tell it to enable verbosity during compilation. This will actually show you exactly what is being compiled. It will also give you the path to the temporary build directory in which you will find the .cpp file with the same name as your .ino file.


Digital output from one nano to digital input of another.

Yes, you can. As you noted, you do need to connect the grounds of both Arduinos.

For some extra protection you could put a resistor between the output and the input. For example a 1kOhm. That way, if you accidentally set both pins as outputs, or plug the wire in the incorrect pin, you won’t get a dead-short.


I would also check out RFDuino.

Basically it's a finger-tip sized, Arduino compatible, wireless enabled microcontroller, low cost enough to leave in all of your projects.

The RFduino runs Arduino code and can do everything an Arduino can.


Specific formatting of floats and converting them to an array of chars

Normally sprintf() would be the solution - however the sprintf() in the AVR LIBC is a cutdown version with no floating point support.

Instead you have to use dtostrf() to get the job done:

dtostrf(val, 6, 4, buffer);

The numbers there are the maximum width of the string (note: you need to take into account any minus sign in that value), and the number of decimal places (6,4 would give you room for "0.0000" but not "-0.0000"). Make sure your buffer is bigger by one byte than your text, since you have to have the trailing NULL character in there to terminate it.

Another (nasty) way would be to go via String (although I would never recommend using String for anything, ever):

String s(val, 4);
const char *buf = s.c_str(); // this points to the internal char buffer.


Simon Says Project - Can't go from random lights to user input

void play() {
  while (correct == 1) {
    showPattern();
    int correct = userInput();
  }
}

Why do you create a new variable called correct and put the value form userInput in that?  Why don't you put the return from userInput into the variable named correct that you already have?  Two variables with the same name in the same scope is NEVER a good idea.  The original correct will never be changed here so this becomes an infinite loop.

Next, look at readOneButton.  It will take the Arduino just a few microseconds to run through that for loop and the whole userInput function.  Unless you are super duper fast at getting that button pressed, it is just going to decide that you didn't press any buttons.  You don't have a case in there for no button pressed, so it is going to return 0.  You should probably wait until the user presses a button before you decide whether he is right or wrong.


Can an Arduino act as a GATT Server (Bluetooth LE)

I got this link here that could be helpful - link at the bottom. It is a tutorial that shows you how to control your Arduino with a custom app on an Android. It uses the MIT app creator, an app that lets you create an app. You program it with there IDE in some Java I believe. You can add button to your app so that is sends a message to your Arduino then program the Arduino to do something when it receives that message. For the Arduino side, you could buy an HC-05 Bluetooth module. It is both an transmitter and receiver. It is quite cheap and very popular so there is many libraries out there. I think this is a good module you should get and I recommend to get them in pairs so you can connect them together with 2 Arduinos.

https://www.youtube.com/watch?v=E-1w7dL3Cps


Is the Serial buffer going from Arduino to PC and from PC to Arduino different?

There shall be separate buffers for Tx and Rx (in Arduino Serial library). The actual buffer size may vary, but shall be around 8-16 bytes and there is also hardware buffer in MCU. Please try to increase serial baudrate, if possible.

UPD: In HardwareSerial.h:

#if (RAMEND < 1000)
#define SERIAL_TX_BUFFER_SIZE 16
#else
#define SERIAL_TX_BUFFER_SIZE 64
#endif

....

unsigned char _rx_buffer[SERIAL_RX_BUFFER_SIZE];
unsigned char _tx_buffer[SERIAL_TX_BUFFER_SIZE];

It seems for Atmega328 the buffers are 16 bytes each

UPD: As Nick pointed, for Atmega328:

#define RAMEND       0x8FF     /* Last On-Chip SRAM Location */

So the buffers are 64 byte each.


How to recover from DHCP Renewal and Rebind failures?

Possible causes:

The DHCP server might be down.
Or it might have lost its state (but I think they try really hard to preserve the list of leases).
Or some other cause which makes the server unavailable/unwilling to renew the lease.

Solutions:

If you can wait, you can retry, but otherwise I'd just say try to obtain a new lease, unless for some reason you really want to stick to the IP from the previous lease.
If you control the server and your network is kinda stable, you could assign a fixed IP to your device configure the server to associate it with the MAC address you gave to your device. In general, when the network setup is really stable, this might be preferable, since other entities on the network will probably cache the IP of your device and use it, should the DNS fail as well (ex: dnsmasquerade works both as dhcp server and dns). Similarly, your device doesn't have to worry anymore of the DHCP lease, because it's permanent.


How to handle a ESP8266 webserver only to the access point?

It is not documented, but you can construct WiFiServer or ESP8266WebServer with IP address. If you use the IP address of the AP, the server will be available only on the SoftAP. If you use the IP address of the station, the server will be available only on STA interface.

#include <ESP8266WiFi.h>

WiFiServer telneServer(23);

void setup() {
  ...
  telneServer = WiFiServer(WiFi.softAPIP(), 23);
//  telneServer = WiFiServer(WiFi.localIP(), 23);
  telneServer.begin();


Your timing seems reasonable.

At a rough guess, without actually compiling it, your code will turn into something along the lines of:

IN R24,PORTD  ;First read   - temp = PORTD     - 1 cycle
ST X+, R24    ;First store  - buffer[0] = temp - 2 cycle
IN R24,PORTD  ;Second read  - temp = PORTD     - 1 cycle
ST X+, R24    ;Second store - buffer[1] = temp - 2 cycle
...

This is indeed the fastest way of reading the port if you want to keep the data. Basically it will do an IO read from PORTD using the IN instruction which takes 1 clock cycle. Then it will perform a store to SRAM using the STS instruction which takes another 2 clock cycles. The store instruction can also post increment the pointer it is using (stored in the R28/R29 X-register pair in my example) for free which saves you time.

So basically that should do 3 clock cycles for every read - one to do the read, and one to do the store, or >5 million reads per second from a 16MHz clock.

There will additionally be a couple of cycles at the beginning to set X-register to point to the buffer. If the buffer is a constant pointer - i.e. the buffer has a fixed address, it will only take two instruction cycles at the beginning to load the address. If it is a non-constant address, it will take up to four as it has to load the address from the SRAM.


How to read the raw data from GY-85 module?

One of the places where the datasheets for the sensors of the GY-85 module can be found is here: https://www.hotmcu.com/gy85-9dof-imu-sensor-module-p-298.html
The following information comes from these datasheets:

Both the HMC5883L and the ADXL345 have internal registers which are numbered consecutively. When reading more than one register they are most efficiently read in the order they are numbered. For each of the three axes both sensors use two 8-bit registers to hold the measured value.

In the HMC5883L the register with the lower number holds the most significant byte (MSB) and the register with the higher number holds the least significant byte (LSB). This means that in a consecutive read the MSB is read first followed bij the LSB. When you combine these two bytes into one 16 bit number (datatype int) you have to shift the MSB-holding byte (the first byte received) 8 places to the left and "OR-in" the LSB-holding byte (the second byte received).
In the ADXL345 the internal numbering is the other way around: the register with the lower number holds the LSB and the register with the higher nummer holds the MSB. When reading, the LSB is red first followed by the MSB. So this time you have to shift the second byte received and "OR-in" the first byte received.

Both sensors give the measured value as a 16-bit 2-complement number, corresponding to datatype int (Arduino Uno). An 16-bit int can hold values from -32,768 to +32,767 but the sensors don't (can't) use this full range:
The ADXL345 has an adjustable range with a maximum of 13 bits (-4096 to +4095).
The HMC5883L has a range of 12 bits (-2048 to +2047).


Does upload using `ICSP`overwrite the bootloader?

Yes.
When you program using ISP you overwrite everything in the chips flash, even the bootloader.

This has some pro's and con's:

Pro: The program starts immediately, meaning it doesn't wait to check if there's any programming coming in before starting your sketch.
Con: You need to use ISP to program your Arduino again or to upload the bootloader again.

Normally there is not really any reason for not having the bootloader present but if you are programming bare Atmel chips without a serial interface this way might be preferable.


How to add toggle button for LCD display text and backlight?

You need to connect the button(s) to available digital inputs of the Arduino. I suggest that you use more than one button based on your description in the question.

The following tutorial describes the circuit needed and the associated code to read that input. All you have to do is duplicate it with a few more buttons on separate (available) digital inputs.

Arduino button tutorial


Trying to print "occur = 1" in an if statement but it wont work

Remove the int from inside the if and else statement. The code would always show 0 because access of occur, which is assigned value 1 or 2 is limited to the if..else statement. So the global occur remains 0 always.

So change it to:

if (Switch == 1){
 Occur = 1;
}
else {
 Occur = 2;
}

This will work.


Decoding IR codes with IR sensor rather than IR receiver module

I had a similar project a few months back and spotted this Arduino Library:

https://github.com/z3t0/Arduino-IRremote

and it is invaluable.

For your instance, you want the RAW Data which you can achieve using an Example included in the Library named: IRrecvDemo.

The wiring is easy and straight forward

  An IR detector/demodulator must be connected to the input RECV_PIN.

Which is 11 by default but you can definitely change it :3

and the other two Legs of the IR detector/demodulator go to the power source.


Arduino and 2 Adafruit Fingerprint modules working together

Yes, you can easily do that. This finger Print sensor works over Serial communication.

You can have multiple Serial devices connected to your Arduino UNO using SoftwareSerial library.

All you have to do is to create multiple instances of Adafruit_Fingerprint initialized with different SoftwareSerial objects. i.e.

// pin #2 is IN from sensor1 (GREEN wire)
// pin #3 is OUT from arduino to sensor1  (WHITE wire)
// pin #8 is IN from sensor2 (GREEN wire)
// pin #9 is OUT from arduino to sensor2  (WHITE wire)
SoftwareSerial mySerial1(2, 3);
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);
SoftwareSerial mySerial2(8, 9);
Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&mySerial2);

Now, you can use finger1 and finger2 for your finger print operations. (previously referenced as only finger)

In order to understand Serial Communication with multiple serial devices, have a look at this Arduino.cc Offical tutorial.

Hope it helps.


Can I use 1-byte datatypes to store digital input?

You receive the data as int, but you store it as byte.

For example, when you call the serial library function to receive a data byte, the library will return either the data or a -1 if a problem has occurred.

The binary value of -1 is a byte 11111111 or int 1111111111111111.

The binary value of 255 is a byte 11111111 or int 0000000011111111.

I think that you can see the problem if you use byte data and the data is 255.

So, if you receive an int -1, then you do not process the data.  Otherwise you cast the int to uint8_t.

You could receive byte data, but then the value of 255 would be undefined.


in you previous question, where I answered, you had no commas or new-lines in the example file content. the parseInt and parseFloat ignores only spaces by default.

remove the commas or read them or ignore them with parseInt parameter SKIP_ALL

km = myFile.parseInt(SKIP_ALL);


Help adding 3 more on/off switches so that I can control 4 LEDs

Use arrays, one for switches, one for leds. I don't see the code for leds in your code.

Note that you need 8 pins (4 for switches, 4 for leds).

Initialize them, e.g.

int switchPins[] = { 2, 3, 4, 5 };

Same for leds

int ledPins[] = {6, 7, 8, 9};

To access them, use a for loop:

for (int iLed = 0; iLed < 4; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

Because 4 might be used a lot, consider them making const or define:

#define NR_OF_LEDS 4

for (int iLed = 0; iLed < NR_OF_LEDS; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

or use the length of the array

for (int iLed = 0; iLed < sizeof(ledPins) / sizeof(int); i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}


declaration of 'varDay' as array of references error

char &varDay[3] is an array of 3 references to type char, not a reference to type char of size 3.
Instead just pass a pointer:
void getDate (char *varDay, char *varMonth, char *varYear, char *varDate, char *dash[2], char *colon[2]) {

Also:
strcpy (varDay, now.day());
strcpy (varMonth, now.month());
strcpy (varYear, now.year());

That won't work. You can't copy a number into a string. now.day() etc need converting to a string first.
It would be better to format your string with snprintf:
snprintf(varDate, 11, "%02d-%02d-%04d", now.day(), now.month(), now.year());


What are these stray resistors on the Arduino Mega schematic?

Those are unused resistors in resistor arrays.  The arrays have 4 resistors side by side in a single package. Not all of the elements are always needed, but they have to be in the schematic anyway since they exist in real life.

Elements A and D of Resistor Network 1 (RN1)
Elements B and C of Resistor Network 2 (RN2)
Element C of Resistor Network 3 (RN3)


Up at the top of your code, you have:

#define START_BUTTON //place code for button // code recieved from start
button
#define STOP_BUTTON //place code for button // code recieved from stop
button

A #define needs 2 parts after it. The first is the new name being created, and the 2nd is the definition of the new name.

You should put the value that you expect for the START_BUTTON condition after the name, such as:

#define START_BUTTON 0x48
#define STOP_BUTTON 0x49

Or whatever your IR remote is sending.

Also, you have one too many closing braces (}) at the end.

      [...]
      case STOP_BUTTON:
           Servo1.write(0);
           delay(200);
           Servo2.write(0);
           delay(200);
           break;
            }  // THIS CLOSES THE SWITCH
     }  // THIS CLOSES THE IF STATEMENT
  }  // THIS CLOSES loop()

  //^servo 2 positions and delays
} // THIS IS NOT CLOSING ANYTHING THAT WAS OPENED


You could use a logic level MOSFET with low RDSon (e.g. IRLZ44) to switch the supply of the HC-05 and use a digital pin to control it.


How I Can Send the status of switch in SMS by Arduino?

Here, Updated Code...

const int switchOneInput = A0; // Switch 1
const int switchTwoInput = A1; // Switch 2

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

void loop()
{
  int switchOneStatus = analogRead(A0);
  int switchTwoStatus = analogRead(A1);

  // When Switch 1 is OFF and Switch 2 is OFF
  if(switchOneStatus < 20 && switchTwoStatus < 20)
  {
    smsOne();
  }

  // When Switch 1 is ON and Switch 2 is OFF
  else if(switchOneStatus > 20 && switchTwoStatus < 20)
  {
    smsTwo();
  }

  // When Switch 1 is OFF and Switch 2 is ON
  else if(switchOneStatus < 20 && switchTwoStatus > 20)
  {
    smsThree();
  }

  // When Switch 1 is ON and Switch 2 is ON
  else if(switchOneStatus > 20 && switchTwoStatus > 20)
  {
    smsFour();
  }

}

void smsOne()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is OFF and Switch 2 is OFF\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsTwo()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is ON and Switch 2 is OFF\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsThree()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is OFF and Switch 2 is ON\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsFour()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is ON and Switch 2 is ON\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}


Unknown USB Device (Device Descriptor Request Failed) - Win 10

SMD soldering is not easy but here is the fix. Continuity achieved!


It is almost certainly a device-driver issue. Since Arduinos are probably a little way down the pecking order for things that Apple is interested in, they probably don't test as extensively as (say) printers.

  How can Arduino make such a sophisticated machine reset?

Device drivers would operate with elevated privileges, because they need to control, well, devices, like hard disks, printers, etc. If one has a programming error (like dereferencing a NULL pointer) then it could crash the whole operating system.

I suggest you look at this page: IDE 1.6.12 released with Sierra support and more

It says there:

  A new version of the Arduino IDE (1.6.12) supporting OSX Sierra is available for download! All OSX users updating to Sierra are invited to also update the IDE to avoid crashes when uploading sketches.

This may or may not help. They seem to be suggesting that the IDE crashes rather than the Mac, but it could be worth trying.

There are some posts on macOS Sierra Usb Serial Crash which seem relevant:

  I need to use a arduino nano and my Mac with mac os sierra is rebooted when i plug in the arduino

It sounds like the CH340 chip set used on clone Arduinos is causing this.

A suggested new device driver fix is at ch340g-ch34g-ch34x-mac-os-x-driver


How to add colour change to the strobe coding?

I guess you want to cycle through a list of defined colors with your strobe effect. For that you can save the colors in a 2-dimensional array and then cycle through the array with a for loop. The 2-dimensional array is then a group of colors, each defined by the 3 numbers for a RGB value. Somewhat like this:
#define NUM_COLORS   5
byte colors[NUM_COLORS][3] = {
    {0xFF, 0, 0},
    {0, 0xFF, 0},
    {0, 0, 0xFF},
    {0xFF, 0xFF, 0},
    {0, 0xFF, 0xFF}
};

void loop(){
    for(int i=0;i<NUM_COLORS;i++){
        Strobe(colors[i][0], colors[i][1], colors[i][2], 10, 50, 1000);
    }
}

Note, that this is not a complete code, but only the interesting parts. You can incorporate this into your code. You can change the number of colors and the colors itself to your liking (I only took some example values, that are easy to recognize).


How can i make my MLX90614ESF scan temperature after the MFRC522 scans the RFID tag?

It appears that you have simply concatenated the code from the RFID tag Sketch and the code from Temperature Sketch together.  This will not work as both programs contain identically named functions. Specifically "setup()" and "loop()".  What you need to do is integrate the code for each "setup()" function into one "setup()" function.  Similarly, you need to do the same with the "loop()" functions.
Assuming you only want to scan the temperature after you have successfully recovered data from the RFID tag, place the Temperature Sketch loop code immediately before the delay in the RFID tag code.


Data from RC522 to firebase real time database

The "UID" of the card is supposed to be unique. Most RFID chips also have blocks of readable/writable space, but some systems do only use the UID from the chip as the complete identifier.

It may be that you come across RFID chips that have utilized random bytes as the UID, in which case there is a chance of duplication. Depending on the number of possible cards to be used in your system, this may or may not be a big worry for you. If it is a big worry, you may want to use the actual memory on the RFID chips to store your user's ID data.

Regarding HEX versus numbers -- Hexadecimal is just one way to represent numbers.
Your code:

Serial.print(buffer[i], HEX);

tells the print command to take the byte at buffer[i] and print its value in Hexadecimal format. You could replace HEX by DEC to see the base-10 (decimal) value instead. The actual bits underneath would be the same -- it's just one way to display/represent the underlying number.

One byte (8 bits) of data can be represented in decimal as the numbers 0 through 255. The same byte can be represented in Hexadecimal as 0x00 through 0xFF. ('0x' is one way to denote that what follows are hexadecimal values.) Each 'digit' in hex represents 4 bits of data (0-15 in decimal), so 2 hex digits can represent 16^2 values (256 decimal), hence 0-255 as the 1-byte range of decimal values.

(That explanation assumes un-signed types.)