Is there a way to keep a program on the Arduino after uploading new sketches?

I'm not familiar with Lego Mindstorm, but I think I understand what you want and I am certain there is a way to do it, but I don't think it will be easy or even practical and I can't tell you exactly how to do it.

I'm pretty certain there will be a way to load a 'module' into memory and then make the program call that address.  I haven't got a clue how you would do it though, sorry.  GCC doesn't have a concept of DLLs like window does, but it does have shared libraries.  Or you might look at just reading a block of memory in.

Other approaches might be to have all the 'programs' as functions within you main program and call them depending on the user's input.  You can only do this if the 'programs' are small enough.

If you can refactor your 'programs' to extract the common code into functions and then have a data file (which could be read at runtime) that called the functions for each of your programming.  Basically  invent your own higher level programming language.  This wouldn't work if your code was very different and you could factor it down to a small enough number of functions.

Would it be possible to just have a number of hex files (compiled programs?) all of which have the common screen/button handler in and then have the special code for the appropriate program.  These could all be stored on an SD card and then loaded into memory by a second Arduino (sounds plausible to me, I'm sure someone will tell me whats wrong with that idea.)

An alternative based on the inverse of the above solution would be to have one Arduino to control the screen/buttons and it programs a second Arduino with the specialist code that is connected to the rest of your kit.


Somehow I got it working. I don't know the cause of the problem but in order to fix it I had to Arduino 1.0 IDE; use this ATtiny support and this Manchester library. Thank you all for your help.


The code works without the display commands. A problem could be that you start with negative pos_y and use it as parameter for drawFastVLine.

Function random returns first parameter if it is a larger value then the second parameter. random(-5, -20) always returns -5.

To have more random random values, you should call randomSeed in setup().

And you can use global array Drop drop[50];.


Is it possible to digitally stop a moving motorbike using an Arduino module?

Assuming that you simply want to stop the engine, Gerben's comment has the answer: Put a relay in series with the ignition. Control the relay with the Arduino.

Opening the relay breaks the circuit. Ignition is now off, and the engine will no longer run.

Of course, the bike can still roll without engine power. If you want to completely immobilize the bike, you need to engage the brakes, or lock the wheels in some other way. And that takes a whole lot more hardware.


Arduino Ethernet Shield Response Process, Time, and Synchronization

I don't have an answer for question 1.

For question 2:

You can add a function to implement an NTP (network time protocol) client.  For example, see the UdpNtpClient article on arduino.cc.  In your setup() or loop() code call the function initially or perhaps hourly or daily to set system time via an NTP time server.  The server's IP address can be hardcoded or otherwise as you like.

For lists of public time servers, see www.ntp.org and pool.ntp.org.

Alternately, you could add a DS1302 or similar clock chip board to your hardware.


Problems returning char array from function, value gets messed up

Your variable decodedString[] is created inside the function, used inside the function - and destroyed inside the function before it returns.

See how your function decodeImage() returns a char *? That's a pointer to a character array, not the whole array - and you can't return a whole array. The pointer is successfully returned all right - but what it is pointing to is overwritten by future calls and future created variables.

This is the perennial problem of C programmers: how to return something created inside the function. You have four choices (each with their own problems):

You can make the variable global - put it outside the function and let anyone access it. Then you don't even need to return the string - it's already accessible.
You can make decodedString a permanent part of the function by making it static:

static char decodedString[64];

  Note that the above two solutions have the same two problems:
  a. There is only one array. That means that if the same function is called again, it will overwrite the results from last time - use it before you lose it!
  b. You can't calculate the length and then use it - it has to be created at the maximum possible size.

You can make the caller pass in the array to fill. Rather than return the array, have another parameter that is the array to fill - and for safety's sake, get them to pass in the size of the array too. You'll have to check that and return an error if it's not big enough - or do something else sensible.
You can allocate the memory from a different area that where it's currently being allocated from. That area is called the "heap" - it's just a heap o' memory that you can request chunks from - and don't forget to give it back!

To request memory from the heap, you call the function malloc and pass in the number of bytes that you want. It returns a pointer to that lump of memory:

char *decodedString = (char *)malloc(decodedLength);

Note that malloc doesn't know what you're going to use the memory for, so you have to tell the compiler - that's what the (char *) before the call to malloc does.

But if you use malloc, at some stage you must give the memory back with a call to free:

free(returnedString);

The function that did the malloc doesn't have to be the function that frees it - any function can, as long as some function does! Otherwise you'll run out of heap.

Another thing that you must NOT do is call free on the same block twice: that will corrupt the heap, since it will mark the same block on the heap twice, and hand it back out twice later, corrupting the data when it is used again.

EDIT

There's a C++ version of malloc / free called new / delete. You use them similarly:

char *decodedString = new char[decodedLength];
...
// And later...
delete [] returnedString;

It looks and behaves similarly to malloc and free, without the ugly (char *) type-cast. Note that since an array was allocated with the new, you need to call the array version of delete by adding the [] as shown.


Attach your voltmeter across the battery, and measure the available voltage when different things are attached; or attach it in series, and measure current draws.  You probably will find that a 9V battery's voltage is under 8 volts when a mix of multiple Arduinos and buzzers is attached.  That voltage may be too low to activate the buzzer.

A powerstream.com web page called 9V Alkaline tests shows how rapidly a 9V battery's voltage drops when heavy currents (more than a few dozen milliamps) are drawn from it, and a batteriesinaflash.com web page includes the following diagram that shows battery voltage quickly falling below 8.5 V in its first minutes of life when 27 mA is drawn from it.

For some models of Arduino, eg the Uno R3, various posts on the web list currents from 25 mA up to 45 mA, depending on LED and sleep settings.  Currents for the Duemilanove from 10 mA up are reported.  The Arduino Micros in your tests probably use a little more current than Pro Mini boards (which have no USB), and although it's unlikely they will use as much or more current than the buzzers, they still may drag the voltage down to a level where the buzzers won't work.

If your system needs to be battery powered, consider using separate batteries for different devices, to avoid problems like you saw.  Alternatively, use heavier-duty batteries, eg good-sized lithium-polymer units.  Also review posts about decreasing Arduino power usage via sleep, disconnecting the power LED, and using large capacitors to buffer power surges.

Edit: Given that voltage measurements show enough voltage being available, the suggested use of capacitors or inductors to isolate circuits may be a good idea.

When adding a capacitor, locate it physically close to the power-using board or component.  For electrolytic  capacitors, attach the capacitor's + terminal to the high side, eg to the +5, +9, or +12 side, and attach its - terminal to ground.

When adding ferrite beads, wrap the supply wire through the bead several times, if there's room.  The picture below illustrates the idea.

An electrolytic capacitor across a circuit acts as a voltage reservoir.  It also gives high-frequency signals an easy path to ground, reducing interference.  A ferrite bead or other inductor impedes high frequency signals, again reducing interference.


The 'best' solution depends on many things, your skill, the performance of the system, and the other tasks it needs to do in the available time. There are some examples of doing data transfer between Processing and the Arduino in the Arduino example programs. So it is worth looking through them.

There seems to be some inconsistencies in your question.

You wrote "It sends the 99.0 data to Arduino", which has a decimal point.

Yet the code is printing an int i.e.

int value = int(red(c1[0]));
myPort.write(value);

Further, the processing code only looks at the red component of c1[0]:

int value = int(red(c1[0]));

so it can only send a sequence of '9'. So that looks like a bug.

There are a few basic strategies to write data that can be easily read. Two popular ways are:

send fixed length messages, or prefix a message with the size of the
data, and have a fixed format of data. For example, use a one byte
count to say how many colours are being sent, then send three bytes,
in the same order, for each colour
use non-data bytes to separate the data. For example use a ','
between R, G or B and '\n' to mark the end of the data. To keep
things simple, never use those values as data values. That is pretty
much how programming languages work. It is much more complex to read
than fixed format data, but can give more flexibility.

Data is often sent as printable characters (e.g. 173 would be three bytes havig the ASCII values '1', '7', '3'). If it is fixed format, it would always be three bytes. For your purposes, I'd probably send each data byte as two hex characters (ASCII '0' to '9' and 'A' to 'F'. This is slightly more complex than pure binary. However it is fixed format, and more importantly it is easier to test by hand using the Arduino serial monitor, you can just type stuff and it is relatively easy to do.

Pure binary data is much more difficult to fully test, and often relies on a piece of software which also needs testing.

Summary: There are a couple of ways, it is hard to say which is best. For simplicity try to make it simple by being fixed format.


Softserial - max speed - loosing characters

This is a classic example of where you choose the wrong chip just because it's the most popular chip around here.

What you want is a dedicated hardware UART just for the GPS that isn't used for your debugging connection.

But, you say, you can't use a Mega because it's too big. And that's true as far as it goes. However, you have blinkered yourself into considering either a Nissan Micra or an 18-wheel juggernaut. You forgot the Ford Focus or the Renault Meganne.

There are other chips besides the (what is too under-specced for you) ATMega328 and the (what is too over-specced for you) ATMega2560. Chips that have other facilities.

Chips like the ATMega32U4 for example.

One hardware UART like the 328, which you can use for the GPS. One USB interface, which you can use for debugging.

And there are boards already with that chip on it - boards like the Arduino Leonardo, or the Arduino Micro.


Using an Atmega8 Chip with an Arduino Uno instead of an atmega328

1) yes the arduino uno can be used with a blanked at mega8 chip with the NG bootloader burned onto it.
You would set the board as NG in the IDE to use the arduino IDE (to upload sketches and so on) with it.

2) A crystal and capacitors is still required -the same values as used for the removed atmega328.

3) The smallest bootloader will leave 7.5kb of program memory left to use on the atmega8.

4) Yes


I don't know how to do the code for an rtc controlling a relay

You will most likely find nobody here, who will write the code for you, since this is not a free code writing service. But I will suggest a good way.

  I just need the relay to trigger every 4h for 5min

The phrase "every x hours" screams for using the modulo operator %. Modulo gives you the rest value of an integer division. See these values:

0 % 4 = 0
1 % 4 = 1
2 % 4 = 2
3 % 4 = 3
4 % 4 = 0
5 % 4 = 1
...
7 % 4 = 3
8 % 4 = 0

You see, the modulo 4 operation gives you zero every 4 hours starting with midnight. So make an if statement based on that

if(hour % 4 == 0 && min == 0)

to switch on and

if(hour % 4 == 0 && min == 5)

to switch off. Just change your code in this way and you are done.


How to access a website running on my localhost(host/server) to Serial Monitor using ESP8266(Client)?

Variable server is a hostname or IP address for TCP connection.
The /LED BLINKING/led blinking.html goes after HTTP GET. Now there is / and it worked for main page of servers.

You need

client.print(String("GET /LED%20BLINKING/led%20blinking.htm") + " HTTP/1.1\r\n" +
             "server: " + server + "\r\n" +
             "Connection: close\r\n" +
             "\r\n"
            );

and you must escape the space


You will see that the Servos have 3 wires [GND, Power, and Data/Signal]. You can connect your external power supply to GND and Power of the servos, and connect the GND and Signal wires from the Servos to the Arduino.

By connecting the Grounds of the Arduino and Servos together, they share the same 0V reference and you will not damage either by powering the Servos from a higher voltage and the Arduino from USB.

It is not necessary to connect the Arduino Vin or barrel jack to the external power supply. Look at the Servos+power supply as one independent unit, and the Arduino+USB/Computer as a separate independent unit, and the only things connected between them should be GND and the servo signal/data wire.


You'll be wasting your time tring to convert the code on a procedure by procedure basis.  Arduino has different libraries, different clocks, different pins, etc.

I suggest you flowchart the code, and then work out which of the Arduino libraries (SPI, LCD, etc.) you can use to achieve the flow.  You'll be able to drop some of the initialisation code probably as Arduino is easier to run "out the box".

There's no quick-and-easy solution here - it's a re-write... as you'll find is often the case migrating code from one MCU to another.


Look at this code:

void setupCredentials(const char *ssid, const char *password,
                      const char *link) {
  int addr = 0;

  EEPROM.begin(512);
  addr = sizeof(int);
  EEPROM.put(addr, ssid);
  delay(10);
  addr += sizeof(st_ssid);
  EEPROM.put(addr, password);
  delay(10);
  addr += sizeof(st_password);
  EEPROM.put(addr, link);
  delay(10);
  EEPROM.commit();

You are calling EEPROM.put(addr, ssid) with ssid being a const char*. A pointer to some memory location. Notice that you only give it a start address and a pointer, not the length of your data.

Have a look at the implementation of the put function:

  template<typename T>
  const T &put(int const address, const T &t) {
    if (address < 0 || address + sizeof(T) > _size)
      return t;
    if (memcmp(_data + address, (const uint8_t*)&t, sizeof(T)) != 0) {
      _dirty = true;
      memcpy(_data + address, (const uint8_t*)&t, sizeof(T));
    }

    return t;
}

What it essentially does is copy your given object const T &t into its internal _databuffer. The size of the data saved is determined by sizeof(T).

In your example t = ssid, T = const char* and sizeof(T) = sizeof(char*) = 4 and addr= sizeof(int) = 4.

What you are doing here is not to save the string that ssid points to in memory but the pointer value of ssid. After you leave the function the data pointed to by ssid will be de-allocated at some point and the memory will be overwritten by something else.

When you do a print directly in the function you are retrieving the pointer value of ssid 3 times and print that value. At that point the data is still there and everything is okay. Then if you print it again after leaving the function you get garbage because the local data is gone after the function call handleSetup is left.

What you want here is to not use a const char* in your second argument to a  EEPROM.put(address, object) call but a char [20], for example. This way the put will work correctly.

Example:

// Assume EEPROM.begin() was called already
void EEPROM_SaveSSID(const int address, const char* str) {
    char ssid_buf[20];
    strncpy(ssid_buf, sizeof(ssid_buf) - 1, str);
    EEPROM.put<char[20]>(address, ssid_buf[0]); //sizeof(ssid_buf) = 20
    //don't forget to EEPROM.commit(); and EEPROM.end()
}

/* read SSID into a pre-allocated buffer */
void EEPROM_ReadSSID(const int address, char ssid_buf[20]) {
    EEPROM.get(address, ssid_buf); //sizeof(ssid_buf) = 20
}

If you do not like the semantics of these C++-templates auto-determining the size of read/write calls, you can always use bytewise read and write calls:

void EEPROM_SaveSSID(const int address, const char* str) {
    for(size_t i = 0; i < strlen(str)) {
        EEPROM.write((int)(address + i), str[i]);
    }
}

/* always read 20 bytes starting from given address into buffer */
void EEPROM_ReadSSID(const int address, char ssid_buf[20]) {
    for(size_t i = 0; i < sizeof(ssid_buf); i++) {
        ssid_buf[i] = EEPROM.read((int)(address + i));
    }
}

See "EEPROM" (actually: Flash-emulated EEPROM) implementation code at https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM.


keypad storing problem (void value not ignored as it ought to be)

Your GetNumber function is defined to return void (nothing) while you use it as if it returns the number typed.

change GetNumber to return a int and the end of it do a atoi using the buffer and return the result.


SIM900 + GPS Module making http rest calls

My question is, will I need a microcontroller for this ?

Yes. There are certain things that you need a "man in the middle" to control. Without a microcontroller, how will you tell it what site to visit? How often to send the HTTP request? How to format the HTTP request? Is there any other thing you need this to do?

People often hope that they can hook up two complex devices that are almost setup to be slaves (like shields, sensors, and outputs) to a microprocessor. Unless the two were specifically designed to work together (or they use a standard, very specific protocol), your chances of building this without a microchip is like trying to build a skyscraper with popsicle sticks. It's possible, but there are cheaper and much easier/more efficient ways to doing that.

Well, they're both SPI/I2C/UART/USB/Serial! Why not? Well, although we're all humans and we use verbal communication as a protocol, do we all understand each other? Not really... For those protocols, they're designed to have a "master" and a "slave." A master would be powerful and have control over all the slaves. Hooking a GSM and GPS shield together is like hooking two slave devices together. It's not going to work out (unless you're aiming for blue smoke...)

tl;dr: you trying to mix two things that don't mix. Buy an Arduino Nano clone for $8 and have your circuit actually work.


I already have a button on my Arduino board, but I don't know what pin number should I use in my code?

The schematic at makeblock.com of the mbot mcore board shows switch S3 feeding pin A7, which is an analog input pin.  Note, there is a deplorable 0.1 μF capacitor in parallel across S3, probably intended as hardware-level debouncing.

Also see the Port wiring mBot mCore board thread at makeblock, where one of the posts says there are multiple versions of the board, and provides reference links.

For example, sample code at
newinnovators.ca's “mblock-to-arduino/button-control” page shows pin 2 being used to sense the button.  You may need to run some tests.


What is the simplest way to "ask" the arduino which input pins are HIGH?

There is a technique, which I used some 40 years ago to test for changes on a set of input pins. This can easily be configured to test serially.

Put a 1 on an output pin say 5. Create an integer e.g. 010000 with a 1 in the appropriate position. Read ALL inputs and XOR with the created integer. If one and only one input is 1 the resultant value will be 0. This is easy to implement in a loop just by shifting the 1 left each time.

The technique works if you can read all inputs into a integer. This was OK for our 32 bits, but could be extended.

It is probably easier to code than explain, but depends on what you have to do to read all inputs.


I'm getting NaN for readings on my DHT22 sensor when using 3v3 pin, but not 5v pin

Sometimes the problem is simply that you didn't properly solder the headers onto the Arduino. You should check to make sure that your solder joints are all good.


Controlling common anode RGB LED with PWM - Can individual colors be done w/o transistors?

As long as each LED in the array uses 20mA or less you can do it directly with the Arduino:

simulate this circuit – Schematic created using CircuitLab

Note that the blue LED will have a higher forward voltage than the red and green ones, hence the lower resistor.

Also note that the PWM will be inverted. Writing 255 to a channel will switch that LED off, while writing 0 will give it full brightness.


The actual WiFi range is highly dependent on many more factors than just the TX power:

The antenna gain, directionality, and orientation of the receiver
The antenna gain, directionality, and orientation of the transmitter
The proximity of radio-reflective objects nearby (metal)
The proximity of radio absorbing objects nearby (humans)
RF Black Magic

In practice, test your situation by running a series of tests at lower and lower power settings until you get an unreliable connection, then bump it up a couple of notches from there.

Do not rely on transmitter power for security, however. You cannot stop someone from pointing a high-gain antenna at your device and communicating with it from a distance farther than 1 meter. TX power reduction should primarily be for energy conservation.


How can I detect which baudrate a virtual COM port is set to?

From looking at the source it appears that on 32u4 based boards Serial  includes extra methods to access the settings from the USB host:

see: https://github.com/arduino/ArduinoCore-avr/blob/b7c607663fecc232e598f2c0acf419ceb0b7078c/cores/arduino/USBAPI.h#L129

From USBAPI.h:

// These return the settings specified by the USB host for the
// serial port. These aren't really used, but are offered here
// in case a sketch wants to act on these settings.
uint32_t baud();
uint8_t stopbits();
uint8_t paritytype();
uint8_t numbits();
bool dtr();
bool rts();


SCLK pulses not seen when using SPI on ESP32

Try to set the pins explicitly to Output
EDITDifferent issues with the test programs indicate that acc. to espressif the pin has to explicitly set to high which is not done by the libs begin method (as of core 1.04)

  digitalWrite(30, HIGH); // turn on pullup resistors
  digitalWrite(xxx, HIGH); // turn on pullup resistors
  pinMode(30, OUTPUT); //VSPI SLCK
  pinMode(XX, OUTPUT); //HSPI SCLK

The ESP32 docs say:

  gpio18 will output low level(because gpio18 is input mode by default).
  If you don’t want this behavior, you should configure gpio18 as output
  mode and set it to hight level before calling

As this is not the issue - the Wroom32 modules v1-3 have a problem with SPI when flashed in certain modes with 80Mhz So try flashing with 40Mhz. I check for my test program in the meantime.

So here is a working test routine:

/* SPI Test routine for Wroom32
Connect the MISO with  the MOSI pin*/
#include<SPI.h>       //Library for SPI

#define SPI_SCK 18 // Serial Clock (Master Output)
#define SPI_MOSI 23 // Master Output,Slave Input
#define SPI_MISO 19 // Master Input, Slave Output
#define SPI_CS 5 // Chip Select, Slave Transmit Enable (active low, Master Output)
#define SS 5

char returnStr[40] = {'\0'};
char returnChr;

void setup () {
  Serial.begin(115200); // Set baud rate to 115200 for usart
  pinMode(SPI_CS, OUTPUT);
  pinMode(SPI_SCK, OUTPUT);
  pinMode(SPI_MOSI, OUTPUT);
  pinMode(SPI_MISO, INPUT);

  digitalWrite(SS, HIGH); // disable Slave Select
  SPI.begin (SPI_SCK, SPI_MISO, SPI_MOSI);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV8); // divide the clock by 8=2 MHz @ESP32
}

void loop () {
  char c;
  digitalWrite(SS, LOW); // enable Slave Select
  /* Send test string in a loop */
  for (const char *p = "SPI TEST! We are online over SPI\n\r" ; (c = *p); p++)  {
    returnChr = SPI.transfer (c);
    Serial.print(c);
    Serial.print(returnChr); // MOSI MISO Link sends echo back
  }
  digitalWrite(SS, HIGH); // disable Slave Select
  delay(500);
}

To measure the signals you have to trigger to the falling edge of SS/CS and set the resolution to 2µs per grid field (round about). I tested on an AIThinker module (ESP32) and everything worked with that sketch.


You will need to allow the use of unverified drivers for this version of the Arduino. Unlike the genuine Arduino this board needs the ch340 and ch341 drivers and because they are not verified you will need to run the following command in order for them to work:

sudo nvram boot-args="kext-dev-mode=1"

I just got a handful of these clones (so cheap) and once I installed the drivers and then set the nvram kernel extensions to dev mode all was OK.


According to tutorial, the shield uses almost all D pins. Free are pins 2 and 13. If servo is not used the pins 9 and 10 are free too. The pin 2 has the extra hole to solder a wire or a single pin header.

All analog pins are free and the shield enables to solder headers for them with additional header rows for 5V and ground for every A pin.

You can use analog pins as digital pins to connect the ultrasonic sensor.

Connection of I2C devices is possible on A4 and A5 pins.

The shield doesn't alow to stack a next shield, because it heats up.


Micro servo is not working with Arduino UNO

You should not power a servo from a USB port.

However, your most glaring problem is that you have entirely mis-wired the connections, such that no wire is going to the correct place.

Servo connections are in the order of Ground - Power - Signal, usually with a dark color for ground and a redder one for power.  Connector shells aren't standardized between brands, but within one there may be keying to prevent reverse installation.

It would appear that on your servo, ground is brown, power red, and signal orange.

Pull out all three wires and start over; also you'd do well to use a dark color for the ground, as you appear to have mixed up the power and ground as well as the signal.


How to call multiple delayed functions using a single millis()

The current structure with multiple if statements and on timestamp variable does only work, if you also check for millis()-then being smaller than the next interval. Otherwise the first if statement will always be executed.
I think it gets easier, when you use only one if statement, but put the intervals in an array. In that if statement you can either use a switch statement to execute the code for the corresponding interval, or use a function pointer. Somewhat like this (untested):
unsigned long then = 0;
unsigned long intervals[4] = {0, 2000, 4000, 6000};
int current_interval_index = 0;

...

void loop(){
    unsigned long now = millis();
    if(now-then >= intervals[current_interval_index]){
        switch(current_interval_index){
            case 0:
                Serial.println("Function 1");
                break;
            case 1:
                Serial.println("Function 2");
                break;
            case 2:
                Serial.println("Function 3");
                break;
            case 3:
                Serial.println("Function 4");
                break;
        }
    then = now;
    current_interval_index = (current_interval_index + 1) % 4; // increment index and wrap it back to zero, if it goes to 4
    }
}

That way you can easily extent for more functions and the intervals are conveniently managed in an array. Note, that the intervals add up here. So function 4 executes after 2s+3s+6s = 11s.


How to pass a string pointer to a function

What you have there are not String objects, but string literals. Their type is const char *

You should avoid using String objects if at all possible. Instead use character arrays.

To get a character array out of a function it is best to create one outside your function and pass it to the function as one of the parameters. The return value of the function can then be a status value indicating if the call worked or not.


Multiple SPI reads slows down read time dramatically

I found the error. Unfortunately I was so busy blaming the code and assuming it was my lack of arduino knowledge that I forgot to check the hardware specs. I thought I was using the maximum external oscillator frequency(f_EOSC) of 300KHz, but in fact was using the 50Hz internal oscillator frequency with an external f_sck from the arduino. This means that the conversions where in fact running at expected times. The thing that threw me off was that the first reading was much faster than the rest. This was most likely because at first read I only had to wait for one channel conversion as the other was already done before I request the data and so the first readings wait time is only as long as a single channels conversion. I would need to implement a 300KHz external clk if I want faster conversion speeds. Thanks for the help for those who tried:)


Is it possible to control a 12v led matrix with an arduino?

You can use ULN2803 driver IC on sink side (cathode), P channel MOSFET on anode/source side of common anode LED matrix. Since you need only 4 sinks you can pair every 2 i/o of ULN2803 so you can drive/sink 1A max load per row. This IC is cheap and widely available.

MOSFET current and speed should match those of ULN2803. You can use BJT instead of MOSFET, but voltage drop on BJT will be higher.

Similar design is here: 8x8 LED matrix


Arduino Mega LED doesn't light as expected

While it is true that your loop is incorrect, the coding error is unlikely to cause the behaviour that you have described.

Please ensure that a current limiting resistor is placed in series with each LED. Since you have 14 LEDs, you will need 14 current limiting resistors. 470 Ohm resistors (or similar) should be adequate for this purpose.

As per the other comments, C++ Arrays start at 0, not 1. The last element is the size of the array minus 1. In your case 14 - 1 = 13. Thus the loop can continue as long as the index is < 14 (or <= 13)

Thus your loops should read:

for(int r=0; r<14; r++ ) {
  digitalWrite(LED[r],HIGH);
  delay(100);
}


How can I connect nodemcu with laptop wifi

Configure and activate the access point mode on NodeMCU. It creates a WiFi network and you can connect to this network with your computer.


Custom Classes - Redefinition of void error

You have bodies for setIcon and setIconColors in both the header file and the cpp file.  You can only have them in one or the other - choose.

Also, as an aside, the way that you are assigning icon data will go out of scope before you use it.  You create a local array variable which you then pass a pointer to to your constructor. That pointer is then saved. But then you go out of scope and the pointer is discarded, and the data will be overwritten.


Arduino (or clone) powered with one or two AA batteries or one CR2032, but still able to give +3.3V or +5V

The modern low voltage versions of a bare ATmega chip can run from either 2xAA or a lithium coin cell - you wouldn't want to use a voltage regulator, as that is not only unnecessary but introduces losses but increases the required input voltage by its dropout meaning your circuit will fail earlier in the discharge curve that in it would without.

Bypassing the regulator on an Arduino Mini style of board is possible.  You probably do not want a board with an on-board USB-serial solution.

You'll need to make sure the clock rate is low enough for operation at the rated voltage (and for sleep efficiency).  This might involve using the fuse for the internal oscillator and ignoring a crystal/resonator that might be present, though if your board was originally intended for 3.3v operation it might be okay.

You will also need to set the brownout detector to the lowest voltage or disable it entirely - this again is in the fuses.

A boost converter to a higher voltage is possible but may not be a good idea, especially from a coin cell.  This is because to supply 1 milliamp at 5v, a boost converter must draw 2 milliamps at 2.5v - and then a bit more, to account for its own losses.  If you go shopping for a boost converter to use, make sure it has an enable, look at the quiescent power consumption when disabled and enabled without load, and look at the minimum input voltage.


Smooth out digital signal from SW-420 vibration sensor in order to record duration?

Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub?

No. If you want to use interrupts then just record the start time on one edge of the signal and subtract it from the current time on the other edge (not sure which edge is which on that sensor).

  Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".

It depends how you define "close".  An RTC can give you better accuracy over long periods, yes, and the Arduino struggles with > 49 days by itself.

  The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

What kind of frequency are you wanting? The frequency of the vibration itself, or the frequency at which some vibration occurs?  If the former the sensor you have won't do the job - that just tells you when there is vibration above a certain threshold.

To sense the actual frequency of vibration you need a more hands-on approach by the MCU. Either use the raw HDX-2 vibration sensor as used on the SW-420 (that's the blue tube at one end), or do it properly and use an accelerometer which you sample over time and perform an FFT on the sampled signal to isolate the different frequencies.


Is Arduino Keyboard in Single User Mode Possible?

OS X requires a "Boot Interface" compatible HID profile for a keyboard to work in single user mode (it has only loaded very rudimentary drivers by that point).  The Arduino doesn't provide that interface, so can only work with the more advanced drivers the OS provides once booted.

You can try setting the "boot interface" flag to 1 in the interface subclass (here, I think, changing HID_SUBCLASS_NONE to HID_SUBCLASS_BOOT_INTERFACE) though I have no clue what the actual effect of that will be given that it's a composite device that may or may not conform to the boot interface standard.


I need some help getting data from a rangefinder

measure.RangeMilliMeter was the key to it all. After experimenting for several hours, I finally got it.


How to count positive electrical pulses?

You should not count the number of pulses, but the number of transition from 0 to VCC volts or VCC to 0 volts (called rising resp. falling edge).

If you don't want to solder, you can also use a light dependent resistor (LDR) very close by the LED to measure the difference in brightness. See also chrisl's remark below.

The counting you can do manually (in a loop, check as often as possible or needed), or by setting up a timer to check for either rising or falling edges.

I will give the pseudo code so you can figure out the actual code:

bool _ldrPin;
unsigned long int _counter;

setup()
{
   // Set Serial
   Serial.begin(9600);

   // Set LDR
   setAnalogPin(X, INPUT);
   _ldrPin = readAnalog(X);
}

loop()
{
    if (!_ldrPin && readAnalog(X) == HIGH)
    {
        // Rising edge, increase counter
        _counter++;
        Serial.Write(_counter);
        _ldrPin = true;
    }
    else if (ldrPin && readAnalog(X) == LOW)
    {
       // Falling edge, reset status
        _ldrPin = false;
    }
}


Wire.h missing - Failing to upload I2C 16x2 LCD sketch

That library is special. It expects to be placed in the same location as the Wire library.  You need to find the location of the Wire library and place this library alongside it.  So you have:

.../Wire/Wire.cpp
.../Wire/Wire.h
.../LiquidCrystal_I2C/LiquidCrystal_I2C.cpp
.../LiquidCrystal_I2C/LiquidCrystal_I2C.h

etc


How can I connect the Tamiya double gearbox to Arduino Uno?

Here's what I've found about both the motor shield and the motors:

Motors are 3-6V and will use a lot of amperage. This may be a problem with a mobile robot. You'll have to figure out a power source that can provide 4+ amps... on battery power that's a lot. Personally, I would go with a continuous rotation servo for a compact, light robot.
Motor sheild can provide 2x 2A channels at 5-12 V (Source) using the two + and - terminals on the bottom left side of the shield. You must connect external power, because USB can't provide enough power. I can't find if the motor shield will limit current if it goes over, but if you do use the gearbox, I'd recommend another route for control that's 1/6rd the price.

This chip was recommended by Pololu on the product page.

Time to whip out your soldering iron! Really, soldering is a great investment and you'll get to a point soon where you'll need one; there will be no other alternative. Luck for you, you only have to solder 16 joints. Headers are included.

Diagrams from Pololu's site:

  *(Click to enlarge ^^^)**

*I added a little text to this image.


Detect if multiple variables are the same?

You run multiple checks. For example:

if (currentLedColor[0] == currentLedColor[1] && currentLedColor[0] == currentLedColor[2]) {
    // do something
}


can we make Drone with Dc 180 motor and Arduino?

Yes you could but you will have to use a motor driver or else the motors will not be able to get enough power and try using arduino micro or an esp32 if you want to use it with Bluetooth which will also help you to keep the weight down.


Can a Lithium Polymer battery charging circuit on Arduino boards also charge Lithium Lion batteries?

There are Lead based, Nickel-based and Lithium-based batteries (there are actually more, but these ones are the most popular). Each need a different charger, but since lithium polymer and lithium ion are in the same group, it should work but I don't have the option to test it out for you.

Q1: Not every battery has a built in over- and undercharge function. Some do, some don't. To find out if yours does, if the internet can't help, tear it apart (be extremely careful about it).

Q2: Depends what you mean by " built in battery charging functionality". If that includes the over- and undercharge functionality, then it will work (tested).

Looking at the board (https://wiki.wemos.cc/products:d32:d32#technical_specs) it seems doable.

The most important thing is to check, if the supported voltage of the li ion battery equals the supported voltage of the li polymer battery that can be charged with the li polymer charger. Since it says 3.7V on the data sheet, don't get a li ion battery with 3.7V+


Probably the serial port is too slow:

Assuming 250 kbits/s, is (including 3 start/stop bits, maybe 2 in your case) in about 250000 (bits/s) / 11 (bits/byte)= about 22 KBytes/s
Assuming each sample has 3 or 4 digits and an 'x' is added (which is 5 characters), 22 (KBytes/s) / 5 (digits/sample) = about 5-6 Ksamples/s you can transfer, which is what you experienced.

So you have to increase the speed for the serial port.


Nano: All digital pins do not output anything

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

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

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

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

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

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

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

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

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

Main points:

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

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

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


If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.

If you program that kind of facility, yes.

A TFT screen is like a blank piece of paper, and you have a set of crayons. You draw on the screen (sometimes with pre-defined shapes, called "letters"). If you want to change what is on the screen you can either throw away your piece or paper and start with a new blank page, or you can get some Tip-Ex® and cover up parts that were there already so you can draw over them.

If you want scrolling you will have to work out for yourself how best to do that given the limited resources you have available.

The simplest method is just to retain a list of the filenames in memory and print just a subset of them on the screen. "Scrolling" then just means displaying a different subset of names.


How to use different device address for MCP23017 so I can use multiple chips?

I share my solution with 7 MCP23017 chip , 7x14 pins=98 pins using adafruit library.

Connections:

addr 0 = A2 low , A1 low , A0 low  000
addr 1 = A2 low , A1 low , A0 high 001
addr 2 = A2 low , A1 high , A0 low  010
addr 3 = A2 low , A1 high , A0 high  011
addr 4 = A2 high , A1 low , A0 low  100
addr 5 = A2 high , A1 low , A0 high  101
addr 6 = A2 high , A1 high , A0 low  110
addr 7 = A2 high, A1 high, A0 high 111

Connect pin #12 of the expander to Analog 5 (i2c clock)
Connect pin #13 of the expander to Analog 4 (i2c data)
Connect pins #15, 16 and 17 of the expander to ground (address selection)
Connect pin #9 of the expander to 5V (power) // operation voltage is 1.8 to 5.5
Connect pin #10 of the expander to ground (common ground)
Connect pin #18 through a ~10kohm resistor to 5V (reset pin, active low)

Input #0 is on pin 21 so connect a button or switch from there to ground

Code:

#include <Adafruit_MCP23017.h>

Adafruit_MCP23017 mcp1; // chip 1
Adafruit_MCP23017 mcp2; // chip 2

#define addr1 7 // 7 = A2 high, A1 high, A0 high
#define addr2 0 // 0 = A2 high, A1 high, A0 high
void setup()
  {
    Serial.begin(9600);
    mcp1.begin(addr1);
    mcp2.begin(addr2);

    mcp1.pinMode(0, INPUT); //pin 21 on chip
    mcp2.pinMode(0, INPUT); //pin 21 on chip

  }

  void loop()
  {
      if(mcp1.digitalRead(0)== HIGH )
      Serial.println("HIGH");
      delay(1000);

      if(mcp2.digitalRead(0)== HIGH )
      Serial.println("HIGH 2");
      delay(1000);
  }


The SparkFun board you mentioned should detect UVB and UVA, but I guess, from your question, that you want one that cannot detect UVA.

Basically any device that has an I2C interface should work with an Arduino as long as you know how to interface with the device in the code.

If your intention is professional research, than a demo device such as the SparkFun may not fit your needs anyway as it will not be particularly accurate and is mainly intended as a little board to play about with on your Arduino and say "Hey, look, there's UV light there!"

The answer to your question is that the best place to look is above the consumer range, at some higher-end UV sensors that are not generally suitable for the little Arduino demos due to price, but may give you much more accurate readings and only sense the UVB waveband.


STM32 and SDFat - Can't create file in directory in SD

I found the issue. I'm not creating the directory folder properly. When I checked the SD card from another device, the DATA folder was invalid, and creating it manually works. I'll look for a solution and post an update.

UPDATE: https://forum.arduino.cc/index.php?topic=421131.0 I'll try this tomorrow but it'll probably fix the issue.


RF transmitter with external 8-12v power not working properly

Those 433MHz modules are tricky. I got the best results with 3V3 on the receiver, and 5V on transmitter. You should add an external antenna.

While it would be prudent to remove the little loop antenna, you don’t need to. I got an okay signal at 25 meters with line-of-sight. Metal, or brick will block the signal even at a meter or so - there’s no penetration. Consider a 2.4GHz module for high penetration at low range, or a LoRa module for high range (up to 10km).

A 433MHz antenna I’ve used with good results (can be cut for any frequency really)

Use the same material for both antenna and radials - copper is good - and optionally stiffen the radials with bicycle spokes on the inside ... make sure there is no electrical contact between the radials and the spokes; tape or heatshrink tube. I found coax cable to suck hard for this application, so I recommend using shielded headphone wire or something similar... just connect the shield to 0V/GND.

As for your breakout power module, I’ve had the same issue. Those modules are dangerous, avoid them. Use 7805 and LM1117 instead. Or just one 5V source (your powerbank?) and a TO-92 LM317 set to 3V3 output (max 100mA). Tiny 3V step-down converters like this can supply 800mA.
https://m.banggood.com/5V-To-3_3V-DC-DC-Step-Down-Power-Supply-Buck-Module-AMS1117-800MA-p-933674.html
( you can find them a lot cheaper )


Arduino UNO code ignores variables selectively

Its hard to see you code, but I think I can make a pretty good guess from your description what is going on.

It seems that you are using the time it takes to increment a value as a way to slow down your code. I think you are underestimating the speed of the arduino. The time it takes to count to 200 (if I'm reading your pictures right) is almost instant; However, you then start printing to with serial each time. Once the serial buffer is full, Serial.print() will wait until there is room in the buffer to place the new value. This time is still small, but making the code wait for it to pass 200 times will take much longer than just waiting for a number to increment to 200.

I think that having added a print statement is slowing down the code enough that your increment based delay is having a noticable effect. What you should do is use the void delay(unsigned long milliseconds); function to cause the code to stop for a bit after it first detects the button has been pressed, and then see if its still pressed afterward. You can also use delayMicroseconds(unsigned int) for shorter but more precise timing. Or better yet, use the unsigned long millis(); function to grab and store the time when the button was activated, and continue polling the current time until the desired delay has been acheived. That way is more code, It allows the code to do something productive while it waits or keep looping.


Below code is an simple example of what you described, each button will turn on the relays defined for them and turn off other relays. except for button 4 which will toggle relay 1 and 4.

int relay1 = 2;
int relay2 = 3;
int relay3 = 4;
int relay4 = 5;
int sw1 = 6;
int sw2 = 7;
int sw3 = 8;
int sw4 = 9;
int sw1Status, sw2Status, sw3Status, sw4Status;
int order = 1; // default is to set all relays off.

void setup() {
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  // input pull-up, so default state of buttons is HIGH.
  pinMode(sw1, INPUT_PULLUP);
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(sw4, INPUT_PULLUP);
}

void loop() {
  // read the buttons status
  sw1Status = digitalRead(sw1);
  sw2Status = digitalRead(sw2);
  sw3Status = digitalRead(sw3);
  sw4Status = digitalRead(sw4);

  if (sw1Status == LOW) { // if button 1 pressed
    order = 2; // go to case 2
  }
  if (sw2Status == LOW) {
    order = 3;
  }
  if (sw3Status == LOW) {
    order = 4;
  }
  if (sw4Status == LOW) { // button 4 toggle
    if (order != 5) { // if order is not equal 5 turn on relay 1 & 4
      order = 5;
    }
    else { // else go to case 1, which will turns off all relays
      order = 1;
    }
  }

  switch (order) {
    case 1: // if order equals 1
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      break;

    case 2: // if order equals 2
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      break;

    case 3: // if order equals 3
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      break;

    case 4: // if order equals 4
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      break;

    case 5: // if order equals 5
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, HIGH);
      break;

    default: // if none of above cases is valid go to case 1
      order = 1;
      break;
  }
}

Having a tidy code format and using simple coding style (if possible) will help to debug/edit/improve the code more easily.

Don't forget to de-bounce the buttons.


I cant comment so I'm going to post as an answer.  Arduino is most likely not capable of running any sort of audio unless you have an mp3 shield to support it.  As far as the wifi module, I suggest using Ethernet shield as that will run a lot better compared to wifi module.


A minor confusion in digitalWrite command

Every other value than 0 or LOW will result in setting the pin to HIGH. In the following I explain why:

The function digitalWrite() can be seen in the file hardware/arduino/avr/cores/arduino/wiring_digital.c. The important lines here are:

if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

As you can see, it checks, if the given value (from the parameter) is equal to LOW and if so will set the corresponding pin to 0. In every other case it will set the pin to 1. The definition of LOW can be found in arduino/hardware/arduino/avr/cores/arduino/Arduino.h:

#define HIGH 0x1
#define LOW  0x0

So the code checks, if the value is equal to 0 and sets the pin also to 0. Every other value will result in a 1 (meaning HIGH). Also have a look at the definition of digitalWrite():

void digitalWrite(uint8_t pin, uint8_t val)

The value is an unsigned type, so every signed type will be casted to an unsigned type. A negative number would result in a positive number inside the function.


Why is there a plastic sleeve on my HC-05 bluetooth module

It is to protect it. You should keep it so that the modules lasts longer.

If you remove it, just don't do anything stupid.


ToF VL53L1X sensor integrate with arduino

There's actually a library created by Pololu that is quite straightforward to use so you don't need to worry about any of that. I think it covers all available functionality.
https://github.com/pololu/vl53l0x-arduino

I was also a bit confused by the API comment and the datasheet.

I misread the device name so the above is not relevant.

In theory I think to use the API you can just #include the C code they provide into your sketch like a normal library. You can download the API code from the manufacturer ST here.
You'll need to give your name and email but it's free.
It's in C but you can probably understand it if you're familiar with Arduino/C++.

Before compiling you would also need to implement some I2C functions for which they provide prototypes (in the vl53l1_platform.c file). However, I think there are some additional steps when using C files that you will need to take to get this to compile, unfortunately I am not familiar with this so can't help - if anyone does then they can probably write a more complete answer.

The alternative is to write your own functions that replicate the functionality that is described in the API.
I would do this by looking at the basic process flow in the API User Manual, taking each function and working through the API files to see what it does.
The main thing you're looking for is the registers that you need to write (via I2C) in order to trigger a range measurement starting, and then the registers that you need to read to find out the result.
I would note that there are multiple levels of #defines for some of the register values and there is a lot of code that deals with managing the status of the device, so this might take a while.


4 channel relay module reversed? Or is it my code?

All the relay boards I've come across are 'active low' i.e. as you've discovered bringing the control pin down to earth activates the relay. As an aside just be careful that the arduino has enough juice to power the relays, a separate supply is normally required if these are coil rather than ssr type relays


Analog output gives a close range of values

Arduino is a lot of fun, but you better stay away from such modules.

The module is a resistor and a electret microphone. There is also a comparator for the digital output. When you have an electret microphone, and add a resistor of 4k7 or 10k, then you have the same.

The signal from the microphone is not amplified and the Arduino only gets the analog value of the audio. The module does not measure how loud the audio is.

I think Velleman makes them: www.velleman.eu/products/view/?id=435532
They are so kind to have a schematic available: vma309_scheme.pdf

Can you move on and use the Arduino for something else?
This module with this microphone is probably not going to work.
If you want to measure the sound level, then perhaps you can make a circuit yourself or buy a better module.

The "Sound Pressure" is how loud audio is.
The most used standard is called "Sound Pressure Level" or "SPL" and is measured in dB (deciBell).


Might be a little late, but you can string more than two of these on one I2C bus, with a little ingenuity.

You connect the AD0 pin of each MPU to a different I/O pin of the processor, then take low the address of the one MPU you want to talk to.

Then that MPU has one address, all the others have the other address, and being slaves will not respond.

Provided you don't have more than one MPU selected at once, works a dream.


How can I best control various high power LEDs without using PWM

The figure below illustrates a method of current control.  It shows four LEDs in a 2x2 arrangement; one  would adapt the number of LEDs in series or parallel in accord with how one's array is wired, what voltages are available, LED current requirements, transistor power limitations, etc. [Edit: See transistor-power example calculation at end.]

Each separately-controlled group of LEDs would need one such circuit.  Each circuit needs one control voltage (eg, from a DAC or a digital potentiometer voltage divider circuit) and needs one transistor per series chain.

Circuit Operation:

Suppose the following conditions hold.

Q1 and Q2 are equivalent transistors and Vbe is 0.7 V typ. (one diode drop)
D1, D2, D3, D4 are equivalent LEDs
Resistors R1, R2 are small and equal (eg 1–30Ω)
V1 is some fixed DC voltage, eg about 1 V
V > 2*Vf + Vbe + VR where Vf = typical forward voltage of D1...4

Under these conditions, V1 will drive current into the bases of Q1 and Q2, causing transistor-amplified current to flow through R1 and R2 and maintain the condition V1 = Vbe + VR1 = Vbe + VR2.

Here is a concrete example:  Suppose we want 23 mA through each LED and that R1=R2=17Ω. VR = IR = 0.023 mA · 17 Ω = 0.391 V.  If Vbe is about 0.7 V, then we set V1 = 0.7 + 0.391 V or about 1.09 V to get 23 mA through each LED.  More generally, to get current I through the LEDs we solve V1 = Vbe + VR = 0.7 + IR = 0.7 + I·17.

Base current:

The amount of current required from the V1 voltage source depends on transistor hFE or β.
Eg, if β is about 100 and ILED is 20 mA then each transistor will need about 20/100 mA or about 200 μA of base drive.  This amount of current probably could be delivered by a voltage divider based on an AD5206 (the digital potentiometer chip that's used in the SPIDigitalPot tutorial mentioned in the question).

Power Dissipation:

The AD5206 digital potentiometer datasheet shows an absolute maximum rating for Package Power Dissipation of  (TJMAX-TA)/θJA.  If ambient TA is 25℃ and θJA is 70°C/W (as for a SOIC package) this gives (150-25)/70 = 1.8 W max package power.  However, it would be reasonable to limit dissipation to under half a watt.  In the 10 KΩ version of the AD5206, that means a little less than 2.9 mA maximum per channel.  [I = √(0.5 W /(6 channels * 10000Ω)).]  If several low-beta transistors are used to drive several strings of LEDs, 2.8 mA might be marginal.

Voltage-divider Linearity:

Only a small fraction of the current through a voltage divider can be drawn off without upsetting the division ratio.  A unity gain buffer amplifier [as in the following figure] can be used to increase linearity of voltage-divider output by providing a high-impedance connection to the divider.

(In the figure above, R1 and R2 are not related to R1 and R2 of the previous figure.  Here, R2 represents a digitally-variable resistor.  Choose R1 and R3 so that V1's range is from slightly below Vbe to slightly above  Vbe + ImaxR, where Imax is the maximum LED current desired.  For example: Suppose V=5 V, that R2's total resistance is 10 KΩ, that R is 15Ω, that Vbe is 0.7 V, and Imax is 25 mA.  Let RT = R1+R2+R3.  Now R3/RT = Vbe/V = 0.7/5 = 0.14, and R1/RT = (V - Vbe - ImaxR)/V = (5 - 0.7 - 0.025·15)/5 = 3.925/5 = 0.785.  Thus R1+R3 = 0.925·RT, whence 0.075·RT = R2 = 10 KΩ, giving RT = 133 KΩ, R1 = 105 KΩ, and R3 = 19 KΩ.  With these R1 and R2 values, each digital pot step should give a change in LED current of 25/256 mA, or about 98 μA.)

[Edit:  When V1 is set to less than VBE, no current will flow through the LEDs.  That is, to turn off the controlled LEDs, set V1 to VBE or less.]

PWM with RC filter:

It may be worthwhile to experiment with using a PWM-driven low pass RC filter to supply V1, possibly avoiding need for buffer amplifiers and digital potentiometers.  See eg “Arduino’s AnalogWrite – Converting PWM to a Voltage”
by Scott Daniels at provideyourown.com, and also see the filter-calculation page it refers to.  You might need an oscilloscope to verify the design and its quality of results, and might need to use several RC filter stages in a row to adequately filter out ripple, but it can be done, at the cost of slower response to control changes.

Transistor-power example calculations:

Letting  VCE, ICE, VBE, and IBE represent collector-to-emitter and base-to-emitter voltages and currents, transistor power dissipation is VCE·ICE+VBE·IBE.  Because VBE·IBE is likely to be sub-milliwatt, we ignore it in following, taking P ≅ VCE·ICE.

In the LED-driving circuit,  VCE = V – VLEDs – Vsense, where VLEDs is the series voltage across the chain of LEDs the transistor controls, and Vsense is the voltage across the sense resistor (ie, across R1 or R2 in the top figure).

In general, it is a good idea to keep Vsense small (under a volt) to allow a wider compliance range – ie, so that LED current is the same over a wider range of variation of supply voltage V.  Thus, the approximation  VCE ≅ V – VLEDs is reasonable.

Here is a concrete example: Suppose we have eight LEDs in series, and they are white LEDs with about 3.6 V forward drop at 20 mA. [LEDs of different colors may have different drops; eg see LED color chart at oksolar.com.]  Then VLEDs = 8·3.6 V = 28.8 V. We need V(BR)CEO > V > VLEDs + VBE + Vsense, where  V(BR)CEO = collector-emitter breakdown voltage (which is 40 V min. for 2N3904 or 2N2222).  Allowing a volt for Vsense and 0.7 V for VBE we have V > 28.8 + 0.7 + 1 = 30.5 V.  Let's suppose V=32 V.  Then P < (32–28.8)·0.020 W = 64 mW.  Thus a small general purpose NPN transistor will work, for example a 2N3904 (rated at 350 mW to 1 W, depending on package, before derating for ambient and heatsinking) or a 2N2222 (similarly rated).

For a second example, suppose VLEDs = 8·1.7 V = 13.6 V (for, eg, eight infrared LEDs at 50 mA) and V=32 V.  Then P ≅  (32–13.6)·0.050 W = 920 mW, so a larger (and heatsinked) transistor would be needed.  Or, V could be decreased, say to 16 V, giving  P ≅  (16–13.6)·0.050 W = 120 mW, allowing use of a small transistor.

For a third example, suppose eight LEDs are paralleled (rather than seriesed), that VLEDs = 2.0 V at 20 mA, that Vsense is about 0.4 V at desired operating point, and that V=5 V.  The transistor will need to drop 5-2-0.4 V = 2.6 V at 160 mA, which is 416 mW, probably large enough to require a heatsink.  [Note:  if LEDs are placed in parallel and driven by a single transistor, some of them probably will be dimmer than others; “current hogging” may occur in some of the LEDs, making them brighter than the others.  However, many cheap flashlights connect LEDs in parallel without individual current control.]


Conflicting pins between the PCM library and speaker and the NRF24L01

No, you can't just change pins. Both systems use hardware that is specific to pin 11.
The best you could achieve would be to use a software SPI implementation on other pins to drive the nRF24L01, but that would mean changes to the library you are using to remove the SPI library usage and replace it with your own software SPI implementation.


Parsing Data and Comparing two string in arduino

I think that the biggest problem that you are encountering is that reading a line from serial is not as straightforward as you would like. I don't have a quick and easy solution for you, but there is much on this issue that you can look at.

You have two serial read while loops. The first exits as soon as there are no characters to read (even though some may be on the way). When "\n" is read, you set parsing but it does not mean that \n is removed from dataIn.

The second serial read while loop is using a delay(3) after detecting that a character is available, but that character could have arrived after the first read and be the only character in the buffer, for example.

I suspect that the reason that your String comparison does not work is simply because the Strings are not equal.

Your String looks like something read from an HM-10/11 or something similar. I have had some success reading those transmissions by doing the following:

Make sure the serial buffer is empty. When a character is available, read it into your building String, but continue looking for characters that are available for a set amount of time (maybe a couple of seconds). Continue looking for characters until the time has elapsed and not as soon as there are no characters available (because more may be coming). Alternatively, keep building the string until you recognize the "DISCE" marking the end of that transmission.

A problem, however, is that, in my experience, if it is a very long line (that can occur when there are many devices out there), you will never get that "DISCE". I assumed that this was a firmware issue.

Hope it helps.


Changing the order of blinking LEDs with the push of a button

The easiest is to use a 'mode', which is a boolean that keeps the state if it is blinking right, let's call it blinkToRight. Initially this is true.

An if statement will be used to change the order.

So the program will be something like (not tested):

global:

bool blinkToRight = true;

in Setup:

pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(2,INPUT);

In Loop:

// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(true, false, false);
   show(false, true, false);
   show(false, false, true);
}
else
{
   show(false, false, true);
   show(false, true, false);
   show(true, false, false);
}

void show(bool led1, bool led2, bool led3)
{
   digitalWrite(2, led1);
   digitalWrite(3, led2);
   digitalWrite(4, led3);
   delay(200);
}

checkReverse will check the input button and returns true if the mode should be reversed.

However, you cannot simply check for the button state. The problem is bouncing. But check in the Arduino examples to a debounce example for this problem and the program should work as expected.

See example: Debounce example

Since only one led will be on, you can also use the following functions for Loop and show:

In Loop:

// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(3);
   show(4);
   show(5);
}
else
{
   show(5);
   show(4);
   show(3);
}

Show:

void show(int ledOn)
{
   digitalWrite(ledOn == 3);
   digitalWrite(ledOn == 4);
   digitalWrite(ledOn == 5);
   delay(200);
}

And it's even better to use constants:

const int LED1   = 3
const int LED2   = 4
const int LED3   = 5
const int BUTTON = 2

Setup:

pinMode(LED1  , OUTPUT);
pinMode(LED2  , OUTPUT);
pinMode(LED3  , OUTPUT);
pinMode(BUTTON, INPUT);

Loop

// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(LED1);
   show(LED2);
   show(LED3);
}
else
{
   show(LED3);
   show(LED2);
   show(LED1);
}

Show:

void show(int ledOn)
{
   digitalWrite(ledOn == LED1);
   digitalWrite(ledOn == LED2);
   digitalWrite(ledOn == LED3);
   delay(200);
}


Most LED lights can't be dimmed from the mains supply.

In order to dim LEDs you have 2 choices: Limit the current through each LED or series string of LEDs, or pulse them very rapidly with a varying ratio of on/off times (known as a variable "duty cycle")

It's usually easiest to pulse them. To do that you need to be able to control the flow of DC to the LED array. If you were to take apart your IR array you would very likely find an AC to DC power supply that then feeds the LEDs through current limiting resistors.

If you can figure out the voltage and current that comes out of the DC power supply, you can select a power transistor (almost certainly a logic level power MOSFET) to wire in as an electronic switch that enables you to pulse the power to the LEDs using a logic signal from your Arduino.

This is actually a lot simpler than it sounds. You would cut 1 wire inside your LED array, solder in a single transistor to the 2 ends of the cut wire, and run the third wire from the transistor out to your Arduino.

Arduinos have several I/O lines that can be configured for PWM (Pulse Width Modulation) which is designed for this very purpose. You'd connect a PWM line to the gate of a logic level power MOSFET, and then send it a signal from 0 to 255, which would effectively dim the LED array in 255 brightness steps.

There are beginner sample projects that let you dim single visible light LEDs using this very approach. (For a single LED you don't need a transistor though, so they are really easy to wire up. All you need is a current limiting resistor.) I suggest you find and build one of those projects to get a feel for how (and how well) it works.


Pass structure pointer as an argument to a function in c

Remove your casting, and change your message parameter to be rs485_message_t *:

int16_t proto485Compare(rs485_message_t * message, uint8_t* comparec, uint8_t* comparea, uint8_t* comaprev) {
    int j = 0;
    rs485_message_t rs485Msg;
    char res;
    uint8_t FWmsg[9] = {0x09,0x31,0x30,0x30,0x30,0x30,0x33,0x30,0x34};
    uint8_t arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

    if(proto485ValidCheckSum(message))) { ...

And when you call it, simply:

res =  proto485Compare(&rs485Msg, command, action, value);

To get at the individual bytes you can then cast a new variable:

uint8_t *messageAsBytes = (uint8_t *)message;

Then you can use:

messageAsBytes[i]

etc.

However another cleaner way is to create a union in your structure:

struct rs485_message_t {
    union {
        uint8_t bytes[9];
        struct {
            uint8_t AB;     ///< Address byte (Start byte)
            uint8_t CB;     ///< Command (index) "ASCII-byte"
            uint8_t SI;     ///< Action (sub index) "ASCII-byte"
            uint8_t PH1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
            uint8_t PH0;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
            uint8_t PL1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
            uint8_t PL0;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
            uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
            uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
        };
    };
};

So you can now access message->CS0, etc, as well as message->bytes[3].

You should also pass a pointer when you call proto485ValidCheckSum - purely to save memory.

uint8_t proto485ValidCheckSum(rs485_message_t *message)
{
  uint8_t rawChecksum = (message->CB - OFFSET_ASCII) + (message->SI - OFFSET_ASCII) +
    (message->PH1 - OFFSET_ASCII) + (message->PH0 - OFFSET_ASCII) +
      (message->PL1 - OFFSET_ASCII) + (message->PL0 - OFFSET_ASCII);

  uint8_t res = (((rawChecksum & 0xF0) >> 4) + OFFSET_ASCII) == message->CS1 &&
    ((rawChecksum & 0x0F) + OFFSET_ASCII) == message->CS0;

  return res;
}

And again call it with a pointer, which the first block of code does anyway.

In general, it's better to pass a single pointer to a struct around from function to function instead of cloning it each time.

You can also use "pass by reference" if you like, but I find it's better to stick to pointers when passing something around alot like this.


Transfer a struct's data to an external struct via serial?

I think you are over-complicating it to send two bytes. Just send them as straight ASCII with a newline after, and decode it on the receiving end.

eg.

42,87

However if the question was just an example of something much more complex, then you may need to do more work. You need to have the receiving end know when a packet of data starts, and ends, and preferably have some validation that it wasn't corrupted.  If you want to pursue that idea, see my thread about sending data via RS485 which has a library that does that sort of thing.


Creation of multiple power cells to be controlled by Arduino

OK. Looks much better now. And I see one problem. It seems that the normal way to do the speed control is with a pot. A variable voltage at the input depending on the rotation. The Arduino low end designs have an analog out capability but it really is not analog. It is a pulse width variable signal that produces an on percentage between 0 volts and the CPU positive supply voltage. The boards do not have a real digital to analog converter. (maybe some higher end boards but not boards based on the Uno CPU.

It may still work but you need to integrate the pulse output and produce a real analog output voltage. A resistor on the output connected to a capacitor to ground will do the integration and filter out the pulses.

See http://www.ontrak.net/pwm.htm for more details.

The problem you might encounter is to much loading on the capacitor by the pot input circuit. Without more details about the module I couldn't say. The signal can be buffered with an amplifier but that adds to the complexity. Still would be doable though.

Or you can add a real digital to analog converter to the Arduino board. That would be my preference rather than having to add a buffer amplifier if a simple RC circuit wasn't good enough.

Do you have a link for that board?

From the picture of the linked speed module. It uses a LM324 opamp to generate the PWM signal. I did a quick look and found a typical circuit.

http://www.pcsilencioso.com/cpemma/graphics/erg_pwm_sch.gif

Typical but not the exact one. It is much as I expected. And if you did the RC only filtering then it may just work. The opamp input would not be too much loading on the capacitor. The concern that I have is that the 5 volt maximum from the Arduino may not be high enough to turn the motor on at its maximum value.


If you read the datasheet you can quickly find that the output of the device is 300mV per g.  That means:

Read the analog value
Convert it to millivolts
Divide it by 300

The result is the g value.  If you do it using floating point then yes, you get fractions of a g resolution.

For instance:

float mv = analogRead(0) / 1023.0 * 5000.0;
float g = mv / 300.0;

If the analog channel has 1024 steps, that's 5/1024 = 0.0048828V per step, or 4.8828mV per step.  Divide that by 300 and you get a resolution of 0.01628g

As for not seeing variations in X when you shake up and down, maybe that is because you really want to look at the Z axis, not the X. X is left/right, Y is forward/backward and Z is up/down.  It's all in the datasheet - it makes for good reading, I suggest you take a look.


Can I power Arduino with 12V 1.2A adapter

If it is an Arduino Uno Rev3 SMD, the documentation (see Juraj's comment) is of relevance here, click the tab "Tech Specs" to find:

Operating Voltage     5V
Input Voltage (recommended)   7-12V
Input Voltage (limit)     6-20V

While the microcontroller's (ATmega328P) operating voltage is 5 V there is an on-board voltage regulator to make the board work within the input voltage range of 6 to 20 V (max limits) or the recommended range of 7 to 12 V.
Operating this Arduino with a 12 V power adapter is within spec and therefore safe to do. The current rating of the adapter of 1.2 A is also more than sufficient to run the Arduino.


The BOOTRST fuse was disabled, but bootloader code is still running after chip reset

You don't seem to have filled in all the interrupt vectors. I get this from your .bin file:

00000000 <.sec1>:
       0:       00 c0           rjmp    .+0             ;  0x2
       2:       00 00           nop
       4:       00 00           nop
       6:       00 00           nop
       8:       fc cf           rjmp    .-8             ;  0x2
       a:       fb cf           rjmp    .-10            ;  0x2
       c:       fa cf           rjmp    .-12            ;  0x2
       e:       f9 cf           rjmp    .-14            ;  0x2
      10:       f8 cf           rjmp    .-16            ;  0x2
      12:       f7 cf           rjmp    .-18            ;  0x2
      14:       f6 cf           rjmp    .-20            ;  0x2
      16:       f5 cf           rjmp    .-22            ;  0x2
      18:       ff ff           .word   0xffff  ; ????
      1a:       ff ff           .word   0xffff  ; ????
      1c:       ff ff           .word   0xffff  ; ????
      1e:       ff ff           .word   0xffff  ; ????
      20:       ff ff           .word   0xffff  ; ????
      22:       ff ff           .word   0xffff  ; ????
      24:       ff ff           .word   0xffff  ; ????
...
    7dfc:       ff ff           .word   0xffff  ; ????
    7dfe:       ff ff           .word   0xffff  ; ????
    7e00:       11 24           eor     r1, r1           <--- bootloader
    7e02:       94 b7           in      r25, 0x34       ; 52
    7e04:       14 be           out     0x34, r1        ; 52
    7e06:       89 2f           mov     r24, r25
    7e08:       8d 70           andi    r24, 0x0D       ; 13
    7e0a:       11 f0           breq    .+4             ;  0x7e10
    7e0c:       89 2f           mov     r24, r25
    7e0e:       de d0           rcall   .+444           ;  0x7fcc
    7e10:       85 e0           ldi     r24, 0x05       ; 5

Now I can't quite see the relationship between the brown-out and those higher interrupts, but if one of them happened to fire I think it would waddle its way past all those 0xFF instructions and hit the bootloader.

The Atmega328P has 26 interrupt vectors (including Reset).


Door control with Arduino and limit switches

You will need to write code to

Control a motor. Likely a DC motor with two way control. This can be done with four MOSFETs and several diodes or much better, one H bridge IC. Your code will need to determine which one of two lines going to the dc motor is getting connected to the positive rail, and which one to the negative/ground, or both disconnected, using the three buttons you described.
You will need to write code that monitors the limit switches. I would suggest you use interrupts for these. One pin goes to ground, the other goes to the Arduino interrupt pin. You can use attachInterrupt() function to write functions that execute right away. Make sure you read up on which pins on your Arduino will support interrupts.
You will need to stop the motor movement either directly or by throwing a switch using the interrupt (or whatever detection method you use for the limit switch).

*one special consideration is that any variables that you use inside of interrupt functions should be marked as volatile, so int myVar; becomes volatile int myVar;
*also don't use Serial.print or millis() inside of your interrupt functions if can avoid it.

From here Google 'Arduino switch' and work on an implementation of limit switches separately. If you want to, Google 'Arduino Interrupts' and improve your implementation to use interrupts. Next, Google 'DC motor bidirectional control Arduino'. Work on it standalone. Once both work separately, combine into a single project.

Let me know as you go through these if you have specific questions, and I would be happy to help you learn how to build it using the components you have.


ArduCAM OV2640 and microSD card module -- SPI problems

In this case, I don't think that a device is "using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller". I think that your problem probably lies with how your SD card is connecting via the SPI bus.

The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.

I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer in the MISO line for each of the SPI devices.

In that case, I used a 74HC125 (4-channel tri-state buffer).

This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).


When I am searching for something inside a loop, I find that the
simplest thing to do is to just break out of the loop once I found it.
This was frowned upon in the days when structured programming was a hot
thing, but as long as it makes things simpler, you should not be ashamed
to break:

const int button_pins[] = {2, 3, 4};
const char * const urls[] = {"foo.com", "bar.org", "baz.net"};
const char * url;  // the selected URL

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

    // Configure input pins.
    for (int i = 0; i < 3; i++)
        pinMode(button_pins[i], INPUT_PULLUP);

    // Find first button pressed.
    int i;  // button index
    for (i = 0; ; i = i==2 ? 0 : i+1) {
        if (digitalRead(button_pins[i]) == LOW)
            break;
    }

    // The button index selects the URL.
    url = urls[i];

    Serial.print("Selected URL: ");
    Serial.println(url);
}

void loop() {}

The for loop above is written as an endless loop (no end condition).
The expression i = i==2 ? 0 : i+1 means: “if i is 2, make it 0,
otherwise make it i+1”. In other words, we are endlessly looping i
over 0, 1 and 2.

Now, it may well happen that you actually do not care about which button
was pressed once you have selected the proper URL. In this case, you can
use the URL pointer as a “flag” that tells you when you can end the
loop:

// First button pressed selects the URL.
for (int i = 0; !url; i = i==2 ? 0 : i+1) {
    if (digitalRead(button_pins[i]) == LOW)
        url = urls[i];
}

Where !url means “the URL has not been found”. This works because the
C runtime initializes url to zero, which is interpreted as false in
boolean context.

Addendum: If you are likely to add new button/URL pairs, you can
make this easier by structuring the list as an array of structs:

const struct {
    int pin;          // pin number
    const char *url;  // associated URL
} buttons[] = {
    {2, "foo.com"},
    {3, "bar.org"},
    {4, "baz.net"}
    // etc. just add to this list as needed.
};
const size_t button_count = sizeof buttons / sizeof buttons[0];

Then the search becomes:

for (int i = 0; !url; i = i==button_count-1 ? 0 : i+1) {
    if (digitalRead(buttons[i].pin) == LOW)
        url = buttons[i].url;
}


How can I2C be made to work through a level shifter?

For I2C you need a special kind of logic translator. This one isn't suitable.

  This device can only translate push-pull CMOS logic outputs. If for open-drain signal translation, please refer to TI TXS010X products.

Personally I use the PCA9306DCUR since it is specifically designed for I2C operation.


confirming this will blink LED at given frequency

You can check if it is correct by timing it for one minute and check if it is (approximately) ok.
However, I see a few improvements:

First is that you always return 1/7/2*1000 = 71.429, which is rounded down to 71. 71 * 14 = 994 ms so you get a bit faster speed than 7 Hz. if this is a problem you have to compensate for this.
Another small problem is that you delay, but the digitalWrite commands also take some time which is not included for the delays. So you need also to take this into account when using a precise delay.
When using floats I always use float constant numbers, like 1.0 and 7.0 instead of 1 and 7. This can especially be useful when you divide two integers (e.g. 1/7), which results in 0.14 this is rounded down to 0 as it is an int.

The best you can do is using the millis command. You keep a timer and compare it to the current millis value. If it is too high, do a state change. This will take into account every other method you do meanwhile the digitalWrites.
Something like: (code fixed due to EdgarBonet's remarks)
const float FREQ = 7.0; // Hz
const int PIN_NR = 4;

unsigned long _startTime;
unsigned long _counter;

int _currentState = LOW;

void setup()
{
  _startTime = millis();
  _counter = 0;
  _currentState = LOW;
  digitalWrite(PIN_NR, _currentState);
}

void loop()
{
  if (_startTime + _counter * 1000.0 / FREQ / 2.0 >= millis())
  {
    _counter++;
    _currentState = ~_currentState;
    digitalWrite(PIN_NR, _currentState);
  }
}

Some small notes:

_currentState is the current state of the LED, with ~ you can flip it (it's called the not operator).
_startTime is the (close to zero) value of the millis value at startup.
Take in mind there is a limit how long this app can run or precise. millis works with ms, meaning you cannot get beyond 500 Hz, and you get 'approximations' with frequencies below in some cases. E.g. when Freq = 80 Hz, you get 1000 * 1 / 80 / 2 = 1000 / 160 = 6.25 => 6, which is actually 1000/6/2=83.3 Hz.
Also the counter is added once per state change, and because of 1000 * _counter ... an overflow exists when _counter >= 256 * 256 * 256 * 256 / 1000 = about 4 million. With 1000 state changes per second, this happens after 4000 seconds, which is 66 minutes. For 7 Hz it will not occur fast.


Unless you require galvanic isolation (and it's highly unlikely that you do) you don't need the relay.

The EN pin only needs to be above 1.3V to turn the unit on, or below 0.9V to turn it off. The voltage range is anything up to 30V.

Just connect the EN pin directly to an Arduino IO pin. Write a HIGH for on and a LOW for off.  And of course connect the grounds together.


There doesn't seem to be, but what you could do is print each character as it arrives. From their example code:

  while (nss.available())
  {
    if (gps.encode(nss.read()))    // <--- pass to TinyGPS
      return true;
  }

So, change that to be:

  while (nss.available())
  {
    char c = nss.read();  // <--- get the incoming character
    Serial.print (c);     // <--- print it
    if (gps.encode(c))    // <--- now pass it to TinyGPS
      return true;
  }


It's difficult to answer without details of how your server works.

If your arduino is simply connected to the server, the server could open the arduino serial port (e.g.: COM5: or /dev/ttyUSB0) and simply read data.  The arduino would only need to serialWrite() data for the server to parse and store.

If your arduino is not connected but has ethernet support you could do a HTTP request to your server, and pass the data as a parameters to the request, e.g.:

http://your.server.ip/send_data?param1=10.3&param2=5.6&param3=foo

When your server processes this HTTP request, it appends param1, param2, param3 to that text file.

The arduino could also beam data back to your server via IR, or bluetooth, etc.

There's lots of ways to do this.


4 Digit, 7 Segment Display Wiring (14 pin)

It's just a 12 pin display, but with two extra pins for the colon.

Removing connections can help you better understand what it going on.

Resistor should be added to the anodes (pins 1,2,3,4,5,8,9,12,13) just like on the website. Pin 8 should be a different value, to match the brightness of the other (multiplexed) leds.

The other end of the resistor can be put into the Arduino. Depending on the resistor value you may need to add some transistor to drive the other pins (cathodes) on the display. Lower value resistors means a brighter display, but too much current for the Arduino to drive all 8 leds of a digit at the same time.

1k resistors, would mean about 3mA of current per segment. So if all segments are on in one digit, that would be 8*3, so 24mA. Which is approaching the maximum current an Arduino pin can source.


Can I increase the 10 event limit in Simon Monk's Timer library?

I don't see anything that would cause any issue. Just don't exceed 255.


The code you have seems to fill the lights with a colour and change every nth of a second.  You could control that to change every 1ms to 2^16ms (which is 65 seconds) just by changing the FastLED.delay() value.

sin8() might return a float or I suspect an int, but colourIndex is an uint8_t so that is a whole number.  All it is doing is picking a colour, based on some scheme.  If the value passed to the function is a float i.e. 1.611 then it will be converted to an int by taking just the whole number part, in this case 1.  It does not round up.

Its not clear what you are trying to do.

If you are trying to slow the rate that the LEDs change colour, you need to change the delay statement.

If you want to smooth the transition between colours you need to change in the area of the sin8 statement, but what you change it to will depend on what your palette is loaded with.

Hope that helps, if not please can you try and describe what it is you are tying to achieve.


ADS1262 and 2.2 SPI TFT (Two SPI Slave) with Arduino

I would suggest that

1) you debug individual code and to make sure that they work separately before integrating them.

2) you put those code pieces in logical blocks. for example, you are likely going to read something from the adc and displaying it on the lcd. so your code flow should be something like this:

  vol_adc = ad1262_read(ADC1_CH); //read analog from ADC1_CH
  vol_mv = adc2mv(vol_adc); //convert the adc results to mv
  lcd_display(vol_mv);  //display vol_mv on the lcd

this approach allows for much easier programming and debugging for you and your readers.


When you disconnect the arduino from 5V you must also remove either

disconnect any other device that is connected to the arduino and has its own power supply
or disconnect every device that is connected to the arduino from its power supply

When you disconnect 5V from the arduino while devices connected to a gpio are still powered, this gpio might see a voltage larger than zero. But the voltage at any pin must not exceed the arduino's actual supply voltage by more than 0.3V. Otherwise the atmega's supply rail will be pulled high through esd protection diodes and the atmega will try to operate. It will then probably draw more current than what the esd diodes are rated for and they will eventually fail (destroying that gpio).


Firstly you do not keep your code consistent between you temperature test and your LCD test code. The problem lies in your use of the internal analog reference, that reference is 1.1V and that is giving you 130°C.

Temp = 260*0.5= 130

The 260 is the ADC reading worked back from the 130°C you gave

To use Internal reference-

Internal ref = 1.1÷1024=0.001074219
That multiplied by one hundred to account for the mV reading of the lm35 gives 0.107 that will give you the correct temp when using the internal reference

Analog reference from the arduino site.

If you want to use the analog reading *0.5 comment out the analogReference()


Arduino not writing full NMEA sentence to SD-card file

After trying different approaches I decided to dumb it down to its most basic level.
Without any fancy coding or buffers, I'm now just writing the data directly to the SD-card and flushing every 15 seconds which has the risk to loose up to 15 seconds of data i.e. 15 GPS-fixes (1 per second) when cutting off power.

The only other time where a potential data loss can happen is observed when the program flushes the accumulated data to the SD. This doesn't happen every time though.

To pars the NMEA-sentences into usable data I use GPSBabel. It automatically ignores the broken lines. After converting to .gpx I view it with Google Earth.

This is the "finished" code:

#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

SoftwareSerial GPS_Serial(4, 3);  // GPS Module’s TX to D4 & RX to D3
File GPS_File;
int NBR = 1;                      //file number

unsigned long TimerA;             //save timer
bool sw = false;                  //save timer switch

void setup() {
  Serial.begin(9600);
  GPS_Serial.begin(9600);
  SD.begin(5);                    //SD Pin

  //write data to a new file
  bool rn = false;
  while (rn == false) {
    if (SD.exists(String(NBR) + ".txt")) {
      NBR = NBR + 1;
    }
    else {
      GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);
      GPS_File.write("START\n");
      rn = true;
    }
  }
}

void loop() {
  while (GPS_Serial.available() > 0) {
    GPS_File.write(GPS_Serial.read());
  }

  //set up timer
  if ( sw == false) {
    TimerA = millis();
    sw = true;
  }

  //save every 15 seconds
  if (millis() - TimerA >= 15000UL) {
    GPS_File.flush();
    sw = false;
  }
}


Writing and reading multiple values through serial

The simplest way is to just print them as a single line and separate them with "something". That "something" could be as simple as a space.

Serial.print(val1);
Serial.print(" ");
Serial.print(val2);
...
Serial.print(" ");
Serial.println(val20);

743 234 34 599 2 ... 427 1013 48 2 409

Then in processing you just read the entire line into a String and split it on the spaces into an array.


How to change wifi credentials of multiple ESP8266 together

you can reconfigure your router, or whatever network mode you are using, with auto-login to the MAC addresses of your ESPs.
And then if you provide the MACs of the corresponding ESPs, and change your WiFi credentials, then you don't need to configure the ESPs individually. It will auto-connect itself.


DS3231 AT24C32 IIC making digital outputs not work

This looks like a classical case of pin conflicts when merging several sketches.

In this case it is hidden by the fact that TWI SDA and SCL are separate pins on the Arduino Leonardo. But they are also connected to pins 2 and 3 (not A4 and A5 as on Arduino Uno).

Selecting other pins (latch/data) for the third shift register should help.

Cheers.


You are mostly correct Diana.  The gain of an OP-Amp would normally be R8 divided by R6.

However, what needs to be recognized is that in your circuit, the resistance of R3 and the microphone get entangled with your R6.

The resistance (impedance of your microphone) is in series with R6. R3 also comes into play, but I will ignore it here (subject of another question on amplifiers).

So, since R of microphone is in series with your R6, your gain (amplification) will be slightly less than you have calculated.

The old 741 Op-Amp won't work very well (probably not at all) with a single ended power supply of 5 volts.  Although you have done a good job of biasing the non-inverting input (+) at 2.5 volts.

The 741 output can't get near the +5 volts, nor can it get near ground.  Try a better Op-Amp such as MCP6002. Look at how the output of the MCP6002 can approach the rails (your power supply and ground).


Yes, you can.  You need to convert the 5V down to 3.3V with a voltage divider. You also need to consider how you are going to operate the ESP8266 when there is no power.


fatal error: ESP8266WiFi.h: No such file or directory

Have you overridden lib_dir in platformio.ini? If yes, please remove it.


Basic C++ programming, how to pass constructor argument into class?

Assuming you want to require every instance of MenuClass should be associated with a TFT_ILI9163C display object, you could use something like this:

// MenuClass.h

class TFT_ILI9163C; // declare a class name which is defined in TFT_ILI9163C.h

class MenuClass
{
  private:
    // read-only private member initialized by constructor
    // (the m_ prefix is commonly used to denote class member values)
    TFT_ILI9163C* m_tft;

  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft) : m_tft(pTft) {};

  private:
    // private storage for the Name property
    String m_Name;
  public:
    // read the Name property
    String getName() {
      return m_Name;
    };
  public:
    // write the Name property
    void setName(String value) {
      m_Name = value;
    };

  public:
    void draw() {
      // the m_tft member is a reference to the display class
      m_tft->setCursor(2, 2);
      m_tft->print(m_Name);
    };
}
MenuClass Menu;

Note that there is only one constructor, and it requires a pointer to the TFT_ILI9163C display. The body of the constructor : m_tft(pTft) {}; initializes the private member m_tft with the constructor argument pTft, so  MenuClass member functions invoke TFT functions as m_tft->fn(args);  Since there is no "void constructor" MenuClass(void), m_tft is effectively guaranteed to point to a valid TFT_ILI9163C instance.

Since it looks like you were using menName kind of like a class property, I rewrote that in the more commonly used m_propertyname style. Your MenuClass::init() was behaving like a name property setter; I'm not sure whether menu initialization requires anything else. This simple example has class MenuClass defined entirely inside the header file.

Usage is pretty similar to your example code, except now the MenuClass constructor requires a pointer to a previously constructed TFT_ILI9163C display instance:

// Main application
#include <TFT_ILI9163C.h>
#include "MenuClass.h"
// ... etc ...

// the TFT_ILI9163C display instance
TFT_ILI9163C tft = TFT_ILI9163C(cs, dc, rst);

// an example menu that draws on the display
MenuClass *menuFoo = new MenuClass(&tft); // use new to get pointer to new class instance
// MenuClass *menuFoo = MenuClass(&tft); // cannot convert 'MenuClass' to 'MenuClass*' in initialization

void setup() {
  // an example menu that draws on the display
  menuFoo->setName("Example");
  menuFoo->draw();
}

If you wanted to pass the constructor an initial Name property value as well as the tft display pointer, you could define the constructor as

  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name) : m_tft(pTft), m_Name(name) {};

You could even go a step further, and give the name argument a default value:

  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name = "Unnamed") : m_tft(pTft), m_Name(name) {};

So with this modification, the expression MenuClass(&myTFT) is the same as the expression MenuClass(&myTFT, "Unnamed"), but you can still override the default value like MenuClass(&myTFT, "DoSomething").

It is also perfectly legal to put statements inside the { } block of the constructor, but in this example all of the work is accomplished by the :memberName(value) constructor syntax.

Edit: MenuClass *menuFoo = new MenuClass(&tft); thanks @BrettAM