text:
Using a Force Sensing Resistor and time input
So the code below measures how much force is exerted on the FSR. I would like to know what would I have to change in this code so that it can record for how long the FSR is being pressed for. So instead of "What force is exerted on the FSR?", I want to ask "How long is the FSR being pressed for?"
Any help will be most appreciated
#include<SoftwareSerial.h>
#include <Wire.h>
SoftwareSerial bluetooth_port(0, 1); //ports for Rx and Tx
int flexSensorPin; // The flex sensor for pin 0

void setup()
{

  Serial.begin(9600); // Start the serial transmission
}

void loop()
{

  flexSensorPin = analogRead(A0); // Flex sensor pin
  Serial.print(flexSensorPin);
  Serial.println("EOL");

  delay(100);

}

check out the millis() function

you need to clarify your question ... is somewhere around 3 seconds an acceptable measurement of time?

When there's no "force" read the sensor value and then start counting, something like: if(sernsorReading != 0){start counting}

Use the analog comparator implemented in AVRs. this function, monitors two analog levels and generates interrupts if one of them goes higher or lower than the other as set. use this interrupt to record/stop counting. on AIN connects to FSR, and the other to a potentiometer to define a threshold. here are some links to get you going.
http://www.gammon.com.au/forum/?id=11916
https://github.com/tardate/LittleArduinoProjects/tree/master/playground/AnalogComparator

Thank you, I will definitely check these links out


text:
Passing arrays, global arrays within functions, pointers, and declaring array sizes
I'm super confused right about now!
I've been working on project involving Xbees in API mode, and I need to send different arrays of bytes to the Xbee depending on which buttons I press. Mostly what I have is working fine, but I'm having a lot of issues with the following questions; I figured I'd summarize all my questions first, then further explain them with code examples.

Arduino requires arrays contain to a size. How can I declare byte data[] without a size?
Arrays sizes must be declared with a number, or a const integer. So how come I can declare byte packet[arraySize]; when arraySize is being passed the integer ledOn_len that isn't constant?
How can I create a global array within a function?

I've taken the liberty to condense my code for readability purposes. Everything you see is here is mirroring my issues with my Xbee code.
byte ledOn[] = { 0x7E, 0xAA, 0x1C, 0x3B }; // turn led on
byte ledOff[] = { 0x7E, 0xAB, 0x1D }; // turn led off

int ledOn_len; // to be used for the array size of ledOn[] NOT a constant
int ledOff_len; // to be used for the array size of ledOff[] NOT a constant

// this doesn't work, because the array length must be a constant
//int arrayLength = 4;
//byte rando[arrayLength];

// this works just fine, since arrayLength is now a constant
//const int arrayLength = 4;
//byte rando[arrayLength];

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

  // since using sizeof(data) inside of changeLed() doesn't
  // work (it returns with 2, which is the size of a pointer)
  // set them here, and pass them along.
  ledOn_len = sizeof(ledOn);
  ledOff_len = sizeof(ledOff);
}

void loop()
{
  changeLed(ledOn, ledOn_len);
  delay(1000);
  changeLed(ledOff, ledOff_len);
  delay(1000);
}

void sendToXbee()
{
  //Xbee.write(packet); // packet isn't global, this doesn't work
  // yes I know I didn't include any software serial in this demonstration
}

void changeLed(byte data[], int arraySize)
{
  byte packet[arraySize]; // how does this work???? Pass by value
  memcpy(packet, data, arraySize); // clone data to packet

  // this is all the Serial print code

}

1) I created the function void changeLed() to calculate the checksum (xbee crap). I need to pass it the array ledOn[] or ledOff[] for the checksum calculations to occur. So I simply added void changeLed(byte data[])  (and then void loop calls changeLed(ledOn) ) which works, but why?! Anywhere else if you declare an array without an array size it says you must provide one. Confusing to me, but it still works. . . kinda. When I serial print data[i] byte by byte, it perfectly displays each byte in ledOn[], which is what I'm passing it. But when I call sizeof(data) it says it's only 2 bytes. How can it contain the exact data of 4 bytes I give it while only being 2 bytes? Here is the serial monitor of it. The first line is the printout of data[], following the 4 bytes is the length which it claims is 2. The second line is the array of bytes packet[]. I set packet[] equal to data[] with this: memcpy(packet, data, arraySize);. Now you'll notice that the array size is correct. Interesting.
Update #1: It seems like this all has to do with pointers somehow. I guess data[] is just pointing to or referencing the array ledOn[], and using memcpy(packet, data, arraySize); is actually copying the array ledOn[] to the array packet[]?

2) I try to declare a random array (byte rando[]) using int arrayLength as the size. This does not work because the array size must be a constant. So I simply add const int arrayLength and that works. Great. So how am I able to do byte packet[arraySize];!? ArraySize is being passed ledOn_len which is not a constant, so how come that works?

3) I need to be able to use the array packet[] inside of another function void sendToXbee(). Packet[] will be my final array of bytes to send to the Xbee containing either the array ledOn[] or ledOff[] which are different array lengths. As is, I cannot use packet[] in void sendToXbee() because packet[] is local to void changeLed(). But here's the catch 22: I cannot declare packet[] in the setup making it  global, because I don't have a size for that array yet!! The size of that array must be calculated within void changeLed(), depending on which array I need to send to the Xbee, ledOn[] or ledOff[].
I know this is a lot but I'd appreciate the help! Thanks guys.

Arduino requires arrays contain to a size. How can I declare byte data[] without a size?

You can't. Pure and simple. The compiler can infer a size from a declaration time assignment.

Arrays sizes must be declared with a number, or a const integer. So how come I can declare byte packet[arraySize]; when arraySize is being passed the integer ledOn_len that isn't constant?

It is a feature of C99 which GCC have also included in C++.

How can I create a global array within a function?

Simple: you can't.*
Ok. Now we've to that out of the way, let's look at what you want to do and how you should do it.
First off, you have a number of arrays of data:
uint8_t ledOn[] = { 0x7E, 0xAA, 0x1C, 0x3B }; // turn led on
uint8_t ledOff[] = { 0x7E, 0xAB, 0x1D }; // turn led off

Those arrays have an associated length, which is the size of the array divided by the size of one array entry:
const int ledOn_len = sizeof(ledOn) / sizeof(ledOn[0]);
const int ledOff_len = sizeof(ledOff) / sizeof(ledOff[0]);

At the moment you're getting away with just using sizeof(ledOn) because sizeof(ledOn[0]) is 1. But if you ever do this with arrays of anything other than byte you will come unstuck unless you get into this habit.
Now, those arrays are just blocks of memory with a fixed size, in a fixed location.  That means that the arrays, as well as being arrays, are also pointers.  That is, they are in effect just variables that contain the address where the data for the array is stored.
So you pass the pointer to the array, along with the length of the array, to your function:
void changeLed(const uint8_t *data, int len) {
}

changeLed(ledOn, ledOn_len);

When you have done is pass the address of the array to the function, not the array.
Now you can do things with that array data using that address. What you can't do is change the data (because I've marked it const).
One of the things you can do, though, is just send it.  You know where the data is. You know how long it is. You know where you want to send it to.
So you just do:
void changeLed(const uint8_t *data, int len) {
    Xbee.write(data, len);
}

That is, write len bytes starting at the address pointed to by data.
There is no need to have variable size arrays. There is no need to have global packet buffers. There is no need to copy any data anywhere with memcpy(). Just pass the data and send it.
If you need to send more data than just the content of your array, then just send it.  For example you may have to (I don't know the XBee protocol) add a header and footer to the packet.
void changeLed(const uint8_t *data, int len) {
    Xbee.write(0x01);
    Xbee.write(0x02);
    Xbee.write(len & 0xFF);
    Xbee.write(data, len);
    uint8_t cs = 0;
    for (int i = 0; i < len; i++) {
        cs += data[i];
    }
    Xbee.write(cs);
}

Just because they're not together in the same write function doesn't mean that they aren't "together".  With serial communication, there is no such thing as "together". It's just one byte after another.

I need to be able to use the array packet[] inside of another function void sendToXbee(). Packet[] will be my final array of bytes to send to the Xbee containing either the array ledOn[] or ledOff[] which are different array lengths. As is, I cannot use packet[] in void sendToXbee() because packet[] is local to void changeLed(). But here's the catch 22: I cannot declare packet[] in the setup making it global, because I don't have a size for that array yet!! The size of that array must be calculated within void changeLed(), depending on which array I need to send to the Xbee, ledOn[] or ledOff[].

Why do you think you need to copy the data into a separate packet variable? You already have the data in a variable.
If you really want to do that, then just pass packet to the next function in the same way as you already pass your other arrays.

* Actually there are ways, using dynamic memory allocation, but I won't condone using that

Very helpful! There are a few things that come to mind however. Your second quote of mine says you can't, but the what I meant by I can is that the compiler accepts it, and it works. I was curious as to why the compiler says it's okay to do it like that and why it does work, even though it seems it shouldn't.

Ah, I misread that bit. If it's local then yes, it can be allocated by a variable (since C99 IIRC)

@HavocRC https://stackoverflow.com/questions/30694199/local-variable-length-array

When I say 'together' I'm referring to keeping all of the variables within an array. The reason being is I have to calculate the checksum (addition of all bytes, & it with 0xFF, then subtract that value from 0xFF). I wrote a function that calculates the checksum, based on the bytes within the array. If tried to do the checksum calculation outside of an array, it would be a nightmare. Based on the information you provided I think I have a great path forward to fixing this. Thank you very much!

source: Stack Exchange

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

sort: votes


text:
How ro re-enable 32u4 USB controller after sleep mode?
I've run into quite the problem with my 32u4, I can't get it to reconnect to the computer upon wakeup from a sleep mode!
So I have an Arduino Pro Micro featuring the 32u4, and I'm also designing a project with a standalone 32u4 (I'm using the Pro Micro as a test platform before I begin building my project). It is a battery operated device with a soft-start, so I need power consumption to be a miniscule as possible (hence the sleep modes).
After learning about the registers and brushing up on some binary, putting the chip to sleep was fairly straight forward, however, I cannot get the USB interface internal to the 32u4 to 'wake back up' or reconnect to the computer. I've attached my code below. I also tested this code on my Arduino Nano and it works just fine, however with added USB features of the 32u4, I cannot get it to reconnect to the computer, and I have to reset the chip a million times to get the IDE to finally recognise it and upload something else to it.
Here is my lovely code below. All it does it upon startup, go sleep, and when interrupt on pin 2 goes low, wake the chip back up and run the blink sketch. It goes to sleep, and wakes up and runs the sketch, it just won't ever reconnect to my computer, until I do a hardware reset.
int btn1Pin = 2;
int led1 = 9;

// these are the 'standard' register configurations
byte _SMCR = 0; // disable sleep mode
byte _ADCSRA = 0b10000111; // re-enable ADC

int interval = 500;
int ledState = true;
unsigned long ct1 = 0;
unsigned long pt1 = 0;

void setup()
{
  pinMode(led1, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(btn1Pin), wakeUp, FALLING);
  sleep();
}

void loop()
{
  ct1 = millis(); // blink something so I know you're working
  if (ct1 - pt1 >= interval)
   {
     digitalWrite(led1, ledState);
     ledState = !ledState;
     pt1 = ct1;
   }
}

void wakeUp()
{
  SMCR = _SMCR; // disable sleep mode
  ADCSRA = _ADCSRA; // re-enable ADC
}

void sleep()
{
  ADCSRA &= ~(1 << 7); // disable ADC
  SMCR |= ( 1<<2 );    // power down mode
  SMCR |= 1;           // enable sleep
  __asm__ __volatile__("sleep"); // hypnotist snaps fingers, chip is out cold!
}

Inside AJ's brain (more research):
32u4 Datasheet for quick reference
I added a quick led turn on in the wakeUp() ISR to ensure it was actually getting executed, and indeed it was.
The description of the USBCON register (Page 267 - 21.13.1) claims that clearing bit 7 disables and resets the USB controller. I tried another iteration of code where in sleep() I cleared bit 7, hoping that reset the controller, and in wakeUp() I set the bit to turn it back on after reset, but that didn't work. In fact, it gave me a really tough time when trying to reprogram (even though I KNOW that the wakeUp() ISR is executing and the bit had to have been reset).
After some more reading, I saw (Page 262 - 21.7.2) says that in power down mode (the sleep mode I'm using),  "the oscillator is stopped and halts all the clocks (CPU and peripherals). The USB controller 'wakes
up' when:

the WAKEUPI interrupt is triggered
the VBUSTI interrupt is triggered."

Okay so this makes sense, in power down mode the USB controller is stopped due to the lack of an oscillator, cool! I understand that to mean I need to trigger one of those interrupts to re-enable the USB controller. So I searched around for the first interrupt "WAKEUPI", and it appears this bit is set by hardware (Page 282), I'm guessing this means when you plug in the USB cable? I wrote a sketch to read that register, and it returned with 00010000, so I'm assumed the above statement is true. It also says setting it with software has no effect, so I left this one to explore the next interrupt, VBUSTI, which seems to be part of the automatic USB plug in detection based off of the VBUS pad. Maybe something here needs to be changed but I can't tell.
Page 266 - 21.12 talks about software USB operating modes, and the last one is "Resuming the USB interface." The 4 bullets provide to wake up are as such:

Enable PLL
Wait PLL lock
Unfreeze USB clock
Clear Resume information

I tried to do all of the above by adding this code to the wakeUp() ISR. It still didn't work :(. I know it's brutal and ISRs should be as short as possible but I gave it a go anyways.
  PLLCSR = _PLLCSR; // enable PLL clock
  var = bitRead(PLLCSR, 0);
  while (var != 1) {} // wait for clock to lock

  USBCON = _USBCON; // unfreeze USB clock
  UDINT = 0; // clear resume flag

Maybe I'm making all of this more complicated than it needs to be, I don't know! I can't get this thing to reconnect.

You're making it too hard on yourself.
There is a method to re-start the USB, but it only works if the USB has been properly stopped - and the method that is supposed to do that is empty.
This is a little sketch that works on my Leonardo:
#include <LowPower.h>

void setup() {
}

void loop() {
    USBCON = 0;
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

    USBDevice.attach();

    pinMode(13, OUTPUT);
    digitalWrite(13, HIGH);

    delay(10000);
    digitalWrite(13, LOW);
}

It disables the USB (USBCON = 0;), sleeps for 8 seconds, then starts the USB up again from scratch (USBDevice.attach();).  10 seconds later it sleeps again.
At the computer end, you get (on Linux):
[1242489.000014] usb 2-1.5.2: Product: USB IO Board
[1242489.000015] usb 2-1.5.2: Manufacturer: Arduino LLC
[1242489.000316] cdc_acm 2-1.5.2:1.0: ttyACM0: USB ACM device
[1242498.631563] usb 2-1.5.2: USB disconnect, device number 69
[1242507.068078] usb 2-1.5.2: new full-speed USB device number 70 using ehci-pci
[1242507.199628] usb 2-1.5.2: New USB device found, idVendor=2341, idProduct=0036
[1242507.199630] usb 2-1.5.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[1242507.199631] usb 2-1.5.2: Product: USB IO Board
[1242507.199633] usb 2-1.5.2: Manufacturer: Arduino LLC
[1242507.200256] cdc_acm 2-1.5.2:1.0: ttyACM0: USB ACM device
[1242517.063425] usb 2-1.5.2: USB disconnect, device number 70
[1242525.495729] usb 2-1.5.2: new full-speed USB device number 71 using ehci-pci
[1242525.627634] usb 2-1.5.2: New USB device found, idVendor=2341, idProduct=0036
.... etc ....

Initially I was trying not to use a library, but I forgot that I could check them to see what they did. I appreciate it very much, I'll definitely be spending some time studying this one.

The USBdevice.attach is in the core, not a library.

I was talking about lowpower lol. And really? I did not realize that, I assumed it was part of lowpower.

I simply put that [ USBDevice.attach(); ]  into my original code in wakeUp ISR, USBCON = 0 in my sleep(), and it works perfectly!

I only used lowpower for the sleeping cus it was convenient.

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


text:
Completing an action on button release help with delaying to give other modules time to repond
I'm currently having problems with my code it has several modules within the main one is my current keypad one working of a mcp23017. what I needed it to do is count how long a key is pressed and upon button release it sets that variable so other modules can read it and complete an action they are required to do for example a seven segment to display a number. However, as you will see currently in cases 1 - 12 as soon as the button has been released it sets the varaible back to notPRESSED.
Code below:
{ // module keypad

  switch (module_keypad_i) {

    case 0:

      setRow(0); // Pull row 0 Low

      if (!(ColumnNum & B00000100)) { // 1 detected
        keypadDebounceTime = millis();
        module_keypad_i = 1;
        break;
      }

      if (!(ColumnNum & B00000010)) { // 2 detected
        keypadDebounceTime = millis();
        module_keypad_i = 2;
        break;
      }

      if (!(ColumnNum & B00000001)) { // 3 detected
        keypadDebounceTime = millis();
        module_keypad_i = 3;
        break;
      }

      rowSet(1); // Pull row 1 Low

      if (!(nColumnNum & B00000100)) { // 4 detected
        keypadDebounceTime = millis();
        module_keypad_i = 4;
        break;
      }

      if (!(ColumnNum & B00000010)) { // 5 detected
        keypadDebounceTime = millis();
        module_keypad_i = 5;
        break;
      }

      if (!(ColumnNum & B00000001)) { // 6 detected
        keypadDebounceTime = millis();
        module_keypad_i = 6;
        break;
      }

      setRow(2); // Pull row 2 Low

      if (!(ColumnNum & B00000100)) { // 7 detected
        keypadDebounceTime = millis();
        module_keypad_i = 7;
        break;
      }

      if (!(ColumnNum & B00000010)) { // 8 detected
        keypadDebounceTime = millis();
        module_keypad_i = 8;
        break;
      }

      if (!(ColumnNum & B00000001)) { // 9 detected
        keypadDebounceTime = millis();
        module_keypad_i = 9;
        break;
      }

      setRow(3); // Pull row 3 Low

      if (!(ColumnNum & B00000100)) { // * detected
        keypadDebounceTime = millis();
        module_keypad_i = 10;
        break;
      }

      if (!(ColumnNum & B00000010)) { // 0 detected
        keypadDebounceTime = millis();
        module_keypad_i = 11;
        break;
      }

      if (!(ColumnNum & B00000001)) { // # detected
        keypadDebounceTime = millis();
        module_keypad_i = 12;
        break;
      }

      else lcd.setCursor(0, 1);
      break;

    case 1: // Read button 1 press
      key = 1;
      Keypad_Debounce_Time(0);
      setRow(0);

      if (ColumnNum & B00000100) {
        //keypad_state = notPRESSED;
        //Serial.println(keypad_state);
        keypadStatus[0] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 2: // Read button 2 press
      key = 2;
      Keypad_Debounce_Time(1);
      setRow(0);

      if (ColumnNum & B00000010) {
        keypadStatus[1] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 3: // Read button 3 press
      key = 3;
      Keypad_Debounce_Time(2);
      setRow(0);

      if (ColumnNum & B00000001) {
        keypadStatus[2] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 4: // Read button 4 press
      key = 4;
      Keypad_Debounce_Time(3);
      setRow(1);

      if (ColumnNum & B00000100) {
        keypadStatus[3] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 5: // Read button 5 press
      key = 5;
      Keypad_Debounce_Time(4);
      setRow(1);

      if (ColumnNum & B00000010) {
        keypadStatus[4] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 6: // Read button 6 press
      key = 6;
      Keypad_Debounce_Time(5);
      setRow(1);

      if (ColumnNum & B00000001) {
        keypadStatus[5] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 7: // Read button 7 press
      key = 7;
      Keypad_Debounce_Time(6);
      setRow(2);

      if (ColumnNum & B00000100) {
        keypadStatus[6] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 8: // Read button 8 press
      key = 8;
      Keypad_Debounce_Time(7);
      setRow(2);

      if (ColumnNum & B00000010) {
        keypadStatus[7] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 9: // Read button 9 press
      key = 9;
      Keypad_Debounce_Time(8);
      setRow(2);

      if (ColumnNum & B00000001) {
        keypadStatus[8] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 10: // Read button * press
      Keypad_Debounce_Time(9);
      setRow(3);

      if (ColumnNum & B00000100) {
        keypadStatus[9] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 11: // Read button 0 press
      key = 0;
      Keypad_Debounce_Time(10);
      setRow(3);

      if (ColumnNum & B00000010) {
        keypadStatus[10] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    case 12: // Read button # press
      Keypad_Debounce_Time(11);
      setRow(3);

      if (ColumnNum & B00000001) {
        keypadStatus[11] = notPRESSED;
        module_keypad_i = 0;
      }
      break;

    default: module_keypad_i = 0;
  }
}

void Keypad_Debounce_Time(int status_num) {  {
n = millis() - keypadDebounceTime;
Serial.println(n);
if (n < 300)keypad_status[status_num] = partialPRESSED;
else if (300 <= n && n < 1000) keypad_status[status_num] = normalPRESSED;
else if (1000 <= n && n < 5000) keypad_status[status_num] = heldPRESSED;
else keypad_status[status_num] = stuckPRESSED;
  }
}

void setRow(byte RowNum){
//Set row
Wire.beginTransmission(MCP_ADDRESS);
Wire.write(MCP_GPIOA);
Wire.write(sRowPattern[RowNum]);
Wire.endTransmission();

// Read the column value
Wire.beginTransmission(MCP_ADDRESS);
Wire.write(MCP_GPIOA);
Wire.endTransmission();
Wire.requestFrom(MCP_ADDRESS, 1);
nColumn = Wire.read();
}

The keypad status for each is set up like this:
enum button_type { notPRESSED, partialPRESS, normalPRESS, heldPRESS, stuckPRESS};
button_type keypadStatus[12];

So all my segment module is doing is reading each key pressed.
I've tried adding some simple non blocking delays in the cases to try and delay it and give the other module time to react to the change like below for one of my cases:
case 12: // Display button # presses
      n = millis() - keypadDebounceTime;

      SetRow(3);

      if (nColumn & B00000001) {
        pressDuration(11);
        unsigned long currentMillis = millis();
        if (currentMillis - previousMillis >= interval) {
          previousMillis = currentMillis;
          keypadStatus[11] = notPRESSED;
          module_keypad_i = 0;
        }
      }
      break;

The pressDuration function works similar to the keypadDebounceTime but just calculates what kind of press it is sets it when the button is released then waits a set interval to set it back to notPRESSED. However, even when I have set my interval to 5 seconds I get no response from the segment display which all it is doing is waiting for the different button press states. I have older code that does the action on button release but all that does is set it to the next number not set the number wait some time then clear it. Is there something fundamental I am missing I have been scratching my head at this for a couple days now.

I honestly don't understand your code. It seems very complicated to me. Also it seems as if you mixed different functionalities into the same code elements.

I also don't understand your code, can you remove the irrelevant parts? Generally, this is a standard case for using a state machine


text:
Multiplex 7 segment during delay (external IC?)
I am using some sensors with the arduino which take a second to receive the data from them. My guess is that there is a delay used somewhere in the library. During this time the multiplexed displays stop working as the rapidly changing grounds are temporarily paused and only one of the displays has the digit lit up. I could change the sensor I'm using (DHT11) to something I could AnalogRead, however I'm curious if there is an external IC for this which drives multiplexed displays with some sort of serial communication or I2C between the arduino and it. I could use a separate arduino(or ATTiny) and write some code for it to do this, but is there a class of chips which already do this? Something where you could pass bytes of the digits and the multiplex delay and it continues to multiplex until the next data is received.
I don't mind if in this time the digits are left in their last states similar to how it would operate if they were directly driven rather than multiplexed. If anyone has insight that would be great!

Perhaps a MAX7219 would do what you want.

The MAX7219CNG+ is a 8-digit serially interfaced LED Display Driver for LED matrix displays.
  The MAX7219 is compact, serial input/output common-cathode display drivers that interface microprocessors (¦ÌPs) to 7-segment numeric LED displays of up to 8 digits, bar-graph displays or 64 individual LEDs.
  Included on-chip are a BCD code-B decoder, multiplex scan circuitry, segment and digit drivers and an 8x8 static RAM that stores each digit.
  Only one external resistor is required to set the segment current for all LEDs.
  A convenient 4-wire serial interface connects to all common ¦ÌPs.
  Individual digits may be addressed and updated without rewriting the entire display.
  The MAX7219 also allow the user to select code-B decoding or no-decode for each digit.

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


text:
Stable temperature sensor under voltage fluctuations
I'm looking for an inexpensive temperature sensor which is non reliant on the input voltage to return an analog reading back or some sort of digital signal. Accuracy is not very important, for instance +/- 4 C is fine. The lm35 I have been using jumps from 25 to 70 degrees regularly with changes in circuit load.
My other option is to add a separate voltage regulator, but I am trying to avoid that if possible! Thanks!

Switching to digital temperature sensors such as DHT22 or BMP sensors would be a great idea as output will be less fluctuated and it is often independent of minor fluctation.

The DS18B20 is a temperature sensor with a digital interface (1-Wire). It works at 3.3 to 5V and the cable length can be a number of meters. It is accurate to 0.5°C.
The DS18B20 is probably the most used temperature sensor for Arduino projects. Its price starts at less than a dollar/euro. You only need the DS18B20, a pullup resistor of 10k and a digital pin.
In the Arduino IDE, go to the Library Manager and search for 'onewire'. Install the "OneWire by Jim Studt, Tom Pollard, ... Paul Stoffregen, ...".
Then search for 'dallas' and install "DallasTemperature by Miles Burton, ...".
The OneWire library on its own can read the temperature of the DS18B20, but the DallasTemperature makes it easier to use.
Look for the examples of the DallasTemperature in the Arduino IDE to start with the DS18B20.
The 1-Wire is a bus, you can add more DS18B20 sensors to the same wire. The DallasTemperature library has two options. Select either a sensor by index, or by its ID. Every DS18B20 has a unique ID inside the sensor.
Sometimes an analog temperature sensor has specific advantages, for example a ntc temperature sensor or a thermocouple sensor. For normal indoor or outdoor usage, the digital temperature sensors are far more easier to use.
Why measure only the temperature ? If you want the baromic pressure and humidity as well, the BME280 has it all. Its temperature accuracy is not very accurate, it is only ±1°C.

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


text:
Menu libaries for a clock
I have a 7 segment clock with 4 digits, and 2 push buttons to control time (hours seconds days month etc). What is the best way to manage the settings of each sub menu when the user wants to change the time? Is coding it myself or using a menu library such as this one better for the task? https://playground.arduino.cc/Code/Menu
Thanks

I would make it myself.
One way to do it:

Create an enum with all states, like Normal, ChangeMonth, ChangeDay, ChangeHour, ChangeMinute };
Use one button to increase the item you are changing with 1
Use the other button go to go the next enum

You can make it fancier by using longer/shorter presses (e.g. to increase faster)
Don't forget to debounce button inputs.

Good idea, I like it. What is your recommendation on recognizing pushbutton presses for getting into the menu when in a for loop in another function?

You have to be very carefully with long running for loops ... It's better to not use a for loop but keep an index and keep checking in the main loop, increasing the index when you did one iteration of the loop. Or keep the for loops very short.

Great suggestions, thanks! I've eliminated all for-loops with incrementing counters and push buttons are recognized immediately!

@MarianoElia Good to hear and good luck with your project


text:
toInt error when converting character of string to interger
with the following code:
int foo = bar[1].toInt;

or
int foo = bar[1].toInt();

I get this error
request for member 'toInt' in '*(bar + 1u)', which is of non-class type 'uint8_t {aka unsigned char}'

the context for this is bar is the response from a HTTP client over web sockets

Why are you trying to call a method on something that isn't an object?

I am trying to convert a character of a string to an integer https://www.arduino.cc/en/Tutorial/StringToIntExample

Then what is bar? It must be an array of String objects then, otherwise this doesn't work. The error clearly shows that you have something like uint8_t* bar;. Are you trying to convert a single character to a int, i.e. something in the range of '0' to '9'?

'bar' is the web sockets response (payload). this is generated by the arduino web sockets library https://github.com/Links2004/arduinoWebSockets (i am basing most of my code on this example https://github.com/Links2004/arduinoWebSockets/blob/master/examples/WebSocketServer_LEDcontrol/WebSocketServer_LEDcontrol.ino)

Can you use atoi() ?

using this code int foo=atoi(payload[1]); i get this error invalid conversion from 'uint8_t {aka unsigned char}' to 'const char*' [-fpermissive] using this code     int bar=payload[1].atoi; i get this error request for member 'atoi' in '*(payload + 1u)', which is of non-class type 'uint8_t {aka unsigned char}'

It has to be int foo=atoi((char*)payload[1]);. And are you sure about the index 1, meaning the second character of the payload?

The question is meaningless without knowing what datatype bar is.

The Arduino function toInt requires a String object.
You're passing it a single character, not a String.
int foo = String(bar[1]).toInt();

I'm not quite clean on what you are trying to do.  So lets assume the String has "abc123" in and you want the numeric part.
const String input = "abc123";
const int foo = input.toInt();  // This will not work!

const String input = "abc123";
const String tmp = input.substring(3); // Take the end of the string
const int foo = input.toInt();  // foo == 123

const String input = "abc123";
const String tmp = input.substring(3,4); // Take the end of the string
const int foo = input.toInt();  // foo == 1 or 12 (can't quite tell from the docs)

Is one of those what you want to do?
You can't take a character and then apply a function from the string class to it without making it a String first.
int foo = String(bar[1]).toInt();  // This should work

You mean .toInt()?

I thought I did then I read the original question again.  I don't know about these new fangled String classes.  If its not a uchar I don't use it :)  Corrected post.

authors: Юрий Большаков


text:
Is it possible to put ATtiny85 to sleep while using TinywireS?
I have an arduino uno as the master I2C device talking to an ATtiny85 as the slave.
What I want to do is have the Attiny85 receive a message from the UNO to tell it to power off which will then trigger a mosfet to turn all the power off to the UNO and then sleep for a period of time.
This all seems to be working fine but every now and then I seem to get a lock up where the UNO just stays on.
Is what I am doing below ok. I am worried about TinyWireS_stop_check() call and if that is going to be messed up by the fact I have delays in the loop and also the fact it goes to sleep.
Thanks
// Code for the ATtiny85
#include <powernap.h>
#include <TinyWireSlave.h>

#define I2C_SLAVE_ADDRESS 0x4 // Address of the slave
#define POWER A3
// The default buffer size, Can't recall the scope of defines right now
#ifndef TWI_RX_BUFFER_SIZE
#define TWI_RX_BUFFER_SIZE ( 16 )
#endif

uint8_t sleepInterval = 1;
bool cycleComplete = false;
bool sleepNow = false;

Napper napper;

enum InterComms
{
    IDLE = 0,
    PWR_OFF = 1,
    CALIBRATION_MODE = 2,
    SLEEP_INTERVAL = 3,
    KEEPALIVE = 4
};

char rxChrData; //Receives the data.
char rxString[12];  //Varbiable for holding one string of data.
int rxIndex = 0; //Used to index rxString.
int i = 99;
bool calibrationMode = true; //Always true when power is turned on

void requestEvent()
{
    TinyWireS.send(calibrationMode);
}

void receiveEvent(uint8_t howMany)
{
    if (TinyWireS.available()) {
        if (howMany < 1)
        {   // Sanity-check
            return;
        }
        if (howMany > TWI_RX_BUFFER_SIZE)
        {   // Also insane number
            return;
        }

        howMany--;
        uint8_t byte = TinyWireS.receive();
        switch (byte)
        {
        case PWR_OFF:
            i = 100;
            sleepNow = true;
            break;
        case CALIBRATION_MODE:
            calibrationMode = true;
            i = 110;
            break;
        case SLEEP_INTERVAL:
            i = 120;
            howMany--;
            sleepInterval = TinyWireS.receive();
            break;
        case KEEPALIVE:
            i = 130;
            measureTimer = millis();
            break;
        default:
            i = IDLE;
            break;
        }
        //Make sure buffer is emppty
        while(howMany--)
            TinyWireS.receive();
    }
}

void setup()
{
    pinMode(POWER, OUTPUT);
    analogWrite(POWER, 255);

    TinyWireS.begin(I2C_SLAVE_ADDRESS); // join i2c network

    TinyWireS.onReceive(receiveEvent); // not using this
    TinyWireS.onRequest(requestEvent);

    napper.setup();

    measureTimer = millis();
    return;
}

void loop()
{
    unsigned long currentMillis = millis();

    TinyWireS_stop_check();

    if (sleepNow)
    {
        sleepNow = false;
        tws_delay(2000);
        cycleComplete = true;
        calibrationMode = false;
        analogWrite(POWER, 0);
        tws_delay(200);
        napper.napminutes(sleepInterval);
        analogWrite(POWER, 255);
        cycleComplete = false;
        //Reset timer
        measureTimer = millis();
    }

    if ((unsigned long)(currentMillis - measureTimer) > (300000) /*&& !cycleComplete*/)
    {
        analogWrite(POWER, 0);
        tws_delay(1000);
        analogWrite(POWER, 255);
        measureTimer = millis();
    }
}

If you are trying to save power, have you considered getting rid of the ATTINY85 and transistor completely? Power the UNO directly (not using the on board regulator) and have it put itself into deep sleep (where it uses almost no power) on receipt of your message. You could also wake on receipt of of another message. All it would take is a couple free pins on the UNO, and would be a much lower power (and simpler) solution.

Thanks for the reply. The attiny powers down other modules along with the UNO so unfortunately just putting the uno to sleep wouldnt be enough. The uno will be replaced by a standalone atmega328p.

Could you have the UNO be the master controller and have it control the power to the other devices? Likely all it would take is one pin on the UNO (or bare 382) connected to a transistor.

Can you post the schematic of your circuit? Moreover if you turn off the UNO but then put power to its pins because the I2C is still on, you'll power it again...


text:
Is it possible to recover an Arduino if it does not wake up after putting it to sleep
I have an ATTiny85 controlling the power to a number of devices. When I first power on it will power the devices via a mosfet. Take the readings it needs to and then puts itself to sleep for 15 minutes then wake up and repeat.
My question is, because I am using the Watchdog timer to put it to sleep, I can't use the reset functionality of the watchdog (ie wdt_Reset). So is there anyway to detect a lock or hang if the ATTiny85 never wakes up for some reason or would I need additional hardware to check for this. If so what kind of circuit would I need.
Thanks

Do you mean: The sleeping part works fine, but you want to detect some other sort of hang and also use the watchdog timer to recover from that?

Thank you for your comment. Ideally I want to be able to recover from a hang if the chip is sleeping and if it hangs when it is running.

I don't see how it can "hang" if it is already sleeping. You could reconfigure the watchdog timer to reset the chip if it hangs prior to the part of the code which puts it to sleep.

So is there anyway to detect a lock or hang if the ATTiny85 never wakes up for some reason or would I need additional hardware to check for this. If so what kind of circuit would I need.

The whole point of the watchdog timer is to wake (or reset) the chip after a certain (short) time. You don't really need a second watchdog timer to wake the processor if the first one fails.
I made a temperature and humidity sensor which is battery powered, and which uses the watchdog timer to wake it and take readings (which sounds like what you are doing). It has been running for a number of years now (over four) and it has never "hung".

Not sure what you mean by "using the watchdog to put it to sleep". You can sleep with or without the watchdog enabled, and you can even use the watchdog to both wake you with an interrupt and also reset in case of a lockup. Check out section 8.5.2 in the datasheet...

If WDE is set, WDIE is automatically cleared by hardware when a
  time-out occurs. This is useful for keeping the Watchdog Reset
  security while using the interrupt. After the WDIE bit is cleared, the
  next time-out will generate a reset. To avoid the Watchdog Reset, WDIE
  must be set after each interrupt.


text:
fast reacting color sensor
I want to recognize the color of passing by objects. The speed of the objects is quite fast, arround 1 meters per second maybe a bit slower. The objects can have only two colors, as an example red or green and the distance between the sensor and the passing by objects is only a few millimeter.
I want to use a color sensor or multiple sensors of the same type bheind each other and timed so that at least one of them take a measurement of the object.
But I dont know which sensor I should take.

I don't think this question has anything to do with Arduinos, at least not the way its currently written, but the answer is very simple look at the Pixie Cam. http://charmedlabs.com/default/pixy-cmucam5/


text:
Burning a bootloader onto my Arduino MEGA 2560 without another arduino board, or isp board
My youtube video explains it. It's starting to get on my nerves.

Please explain your problem in text instead of a 4 minute video.

You need a programmer (isp or Arduino board as programmer). It is not possible to burn a bootloader without it. The USBasp version 2 plus a 10 to 6 pin adapter cost about 2 dollars.


text:
3 buttons digital inputs
I have 3 digital button inputs, I want to do a continuous scan of 3 of them until a button is pressed and to know which button has been pressed. Please help, I'm new to programming and arduino.
Thanks

Try out this code. You can see result on Serial Monitor. I hope it will help you.
const int kPinBtn1 = 2;  // Button 1
const int kPinBtn2 = 3;  // Button 2
const int kPinBtn3 = 4;  // Button 3

void setup()
{
  pinMode(kPinBtn1, INPUT); // Button 1 as Input
  pinMode(kPinBtn2, INPUT); // Button 2 as Input
  pinMode(kPinBtn3, INPUT); // Button 3 as Input

  digitalWrite(kPinBtn1, HIGH); // Pullup
  digitalWrite(kPinBtn2, HIGH); // Pullup
  digitalWrite(kPinBtn3, HIGH); // Pullup

  Serial.begin(9600);
}

void loop()
{
  if(digitalRead(kPinBtn1) == LOW)      // If button 1 pressed
  {
    Serial.println("Button 1 pressed"); // Print "Button 1 pressed" on Serial Monitor
  }

  if(digitalRead(kPinBtn2) == LOW)      // If button 2 pressed
  {
    Serial.println("Button 2 pressed"); // Print "Button 2 pressed" on Serial Monitor
  }

  if(digitalRead(kPinBtn3) == LOW)      // If button 3 pressed
  {
    Serial.println("Button 3 pressed"); // Print "Button 3 pressed" on Serial Monitor
  }
}

Usually you would take advantage of a pin change interrupt and only then read the state of all buttons. This solution will pollute the Serial Monitor while a button is being kept pressed. But it fulfils the requirements of C. Dave. I'm not sure if he exactly knows which direction he is heading.

@C.Dave - I guess since you are new to programming Kwasmich kept it simple.  Once you have that working you could research arrays (in C or C++) and you'll find that you can half the amount of code.

@C.Dave Glad to know.


text:
How i can have one code for multi sensors
am doing multi sensor project concerning PIR,vibration,tilt angle,temp&humidity,gas sensors with LCD in Arduiono mega ...i have each sensor code,need help on programming in one program

You have to keep some points in your mind:
(1) You have to ensure that pins must be not conflicting with each other. If you merge all sensor codes in one code then pins must be conflict. So you have to change pin number.
(2) If all sensors have separate working then make the function for all that sensors. It will very helpful for understanding and debugging the entire code.
(3) Don't try to merge all codes same time. Add one by one and also change pin number during that.

am doing multi sensor project concerning PIR,vibration,tilt angle,temp&humidity,gas sensors with LCD in Arduiono mega ...i have each sensor code,need help on programming in one program

This could be considered a general question: Is it possible to merge several sketches and if so how?
The first step is to check pin conflicts: Are any of the sketches using the same pins (or resources)? If that is the case this needs to be resolved.
The next step is to check timing. Is is sufficient to run each loop() after each other or does the timing behavior also require changes.
The idea is then to simply "merge" the different setup() and loop() functions to a single setup() and loop().
In most cases, the timing behavior will leave no other choice than to rewrite the code.
There are a few tools (such as a Scheduler) that can be used but they require additional understanding of programming and nothing for the novice.


text:
Char transmission using Virtualwire RF signal
This is a really basic problem, but I haven't been able to resolve it myself and would really appreciate the help.  So I've been struggling for a few weeks now to set up RF communication between two arduino uno chips.  I have the transmitter and receiver hooked up to 5V supply, with the data pins connected to digital pin 4.  My code looks like this:
Transmitter code:
#define rfTransmitPin 4  //RF Transmitter pin = digital pin 4
#define ledPin 13        //Onboard LED = digital pin 13

unsigned int data = 0;  // variable used to store transmission data

void setup(){
  pinMode(rfTransmitPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  digitalWrite (rfTransmitPin, HIGH);
  data = digitalRead (rfTransmitPin); // Read the digital transmitter pin
  Serial.println(data);
  digitalWrite (ledPin, HIGH);
  delay(2000);

  digitalWrite (rfTransmitPin, LOW);
  data = digitalRead (rfTransmitPin); // Read the digital transmitter pin
  Serial.println(data);
  digitalWrite (ledPin, LOW);
  delay(2000);
  }

Receiver code:
#define rfReceivePin 4  //RF Receiver pin = digital pin 4
#define ledPin 13        //Onboard LED = digital pin 13

unsigned int data = 0;   // variable used to store received data

void setup(){
  pinMode(ledPin, OUTPUT);
  pinMode(rfReceivePin, INPUT);
  Serial.begin(9600);
}

void loop(){
  data=digitalRead(rfReceivePin);    //listen for data on Digital Pin 4

   if(data = HIGH){
    digitalWrite(ledPin, HIGH);   //If a HIGH signal is received, turn LED ON
    Serial.println(data);
  }

  if(data = LOW){
    digitalWrite(ledPin, LOW);   //If a LOW signal is received, turn LED OFF
    Serial.println(data);
  }
}

This should be really simple, but for some reason I'm reading a continual HIGH signal from the receiver module.  I'm trying to sort out the basic functionality of the RF tx-rx pair before developing code to send a char using the Virtual Wire library, but I can't even get it to function at this level.  Since my code is so basic I'm convinced it must be a hardware issue and I'm not sure what I'm doing wrong.  Any suggestions?

VIf you using Virutalwire try exemple in the library.
You can't send simple digitata data with Rf.
Best Regards Mikael
link Virutalwire

Hi Mikael, thanks for the reply.  I've tried running the example transmitter/receiver code, and all I get is the setup printout on the serial monitor, the message doesn't come through.

http://www.hackshed.co.uk/rf-communication-between-2-arduinos/

This will you show you how you use VirutalWire

Turned out to be a faulty receiver, it's all working as it should be now :-)

Glad you got it working


text:
Current available SRAM?
I've reached the limit on available SRAM memory. I need to "cut down" some variables, but I actually don't know how far I need to go with it.
Is there a way on measuring current available memory on program execution?

Start with moving string literals into the flash memory only (AVR based boards) - Nick Gammon's article about it

If you set "Show verbose output during compilation" in your IDE preferences, you'll see a message like the following in the IDE window's lower pane. The part I bolded is the amount of SRAM assigned:

Sketch uses 2,148 bytes (6%) of program storage space. Maximum is 32,256 bytes.
Global variables use 204 bytes (9%) of dynamic memory, leaving 1,844 bytes for local variables. Maximum is 2,048 bytes.

You can also include this function and print its result to get the same information on the terminal during run-time:
int freeRAM () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}


text:
What would be the best way to sense the tank level of a 1000L water tank?
I want to read in the values to an arduino analog input.
The approaches I have been looking at are:
1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.
2.) A pressure transducer; these tend to be very pricy.
3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)
Would anyone happen to have some advice on what sort of sensor would be good for the application of reading in the tank level and using the information in a sketch?

Options 4 & 5: Resistive measurement between two probes (can cause electrolysis) and Capacative measurement between two insulated probes (harder to do but safer and can be used with corrosive / dangerous liquids).

http://www.instructables.com/id/Capacitive-Fluid-Level-Sensor/

You may find Robotics Stackexchange useful for this question.  (If you post there, delete here)

what's best to you depends on your objectives / criteria. a much better way for you to ask the question would be what are the pros / cons of various way of measuring tank levels? then you can judge for yourself which is best for you in that particular application.

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

1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.

Ultrasonic rays will ping through water till it transfer back from the bottom of tank. So it can not provide you the level of water.

2.) A pressure transducer; these tend to be very pricy.

Yes it will be very pricy.

3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)

This option will be best and more reliable. You can use some water level indicator probes or magnetic float switch.
Probes/Electrode
When electrode is in contact with water it will pass current through it and give indication to system or controller.
Magnetic Float Switch
Magnetic float switch having magnet under water proof enclosure. When water level reach upto Float switch then circuit will be close and will give level signal to system.
In above to switches magnetic float switch will be best option. Because if water having High TDS then there will be erosion of electrode or element of TDS will gether around electrode and result in conductivity loss of rode.
And this is not possible in case of Magnetic Float switch as it is under water proof enclosure. It is also cheap solution.

You are mistaken about the ultrasonic. While a transducer well coupled to the water will measure its depth, one placed in air a distance from it will measure to the reflection off the surface, readily measuring the unused capacity. A return that's gone through the water/air interface twice would likely be too weak for the simple ones to detect, and besides they report only the first meaningful return.  Similarly, with an immersible sensor you might even be able to get a reading from the floor looking up through the water to the surface, though it's not clear that would be worth the trouble.


text:
Virtual analog inputs? Possible?
Just wondering whether it is possible to create 'virtual analog' signals, I am designign a system that uses a tank level sensor (pressure transducer); the component has not yet arrived and I am expecting it in a few weeks.
Is there any way to simulate the signals it would spit out, using some sort of GUI where I can physically control the 'virtual' tank level?
I'm thinking something along the lines of Wonderware's Intouch?
Would appreciate the help! Thanks

Don't spend a ton of time on it, but look up "IOC", "mock input", and "Dependency Injection" software concepts and keep the basic ideas in mind as you build out your sketch. it will help later.

You don't specify the sensor you're trying to emulate, so we can't tell you exactly how to do it.
The obvious hardware approach would be a potentiometer.
You could also do it in software by writing a function to get the value, and temporarily replacing its implementation with one which generates random values, or reads values from a serial port, or reads them in order from a hard-coded array, or calculates them according to the time, or whatever you want.

Thanks for the response! I'm trying to simulate a tank level sensor (so probably a pressure transducer)

If you just want different values on an analog port then you could use a potentiometer, or a second Arduino the reads a value from its serial port and sets the value of its analog port connected to your first Arduino.  Just remember to have a common ground if you do this.

Seconding the potentiometer approach. If you scale the analog result to the output range of the actual component, the rest of your system should never notice the difference when you install the hardware and replace the pot-reading function with a sensor-reading one.


text:
What bootloader is present by default on Arduino Uno?
Or where can i find information of default bootloaders present on each Arduino board. All I could look up was it could be one of these bootloaders on the atmega chip :-
.Atmega
.Atmega8
.bt
.caterina
.caterina-Arduino_Robot
.caterina-LilyPadUSB
.gemma
.lilypad
.optiboot
.stk500v2
This was the list present in the folder ~\Arduino\hardware\arduino\avr\bootloaders.

It is defined in the file "boards.txt" (arduino-1.8.7\hardware\arduino\avr\boards.txt).
For example the Arduino Uno is called "Arduino/Genuino Uno" and it has the bootloader: uno.bootloader.file=optiboot/optiboot_atmega328.hex
You can find that hex file in the folder arduino-1.8.7\hardware\arduino\avr\bootloaders\optiboot.
The official Arduino boards are shipped with the newest bootloaders.
Sometimes the bootloaders are improved or changed. That is mentioned in the Release Notes.
For example the latest change to a bootloader is that the Arduino Nano has now the same optiboot bootloader as the Arduino Uno.
When buying a Arduino clone board, anything is possible.
Some companies make there own Arduino-compatible boards with their own bootloaders.

Exactly what I was looking for. Thanks :)

Optiboot Bootloader for Arduino and Atmel AVR
https://github.com/Optiboot/optiboot/wiki
Take a look at this information.


text:
Android phone can't get ESP8266WebServer page if Content-Length > 1460
I uploaded the following sketch to my ESP8266:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);
String toServe;

void serveShortString() {
    server.send(200, "text/plain", "short string!");
}

void serveLongString() {
    server.send(200, "text/plain", toServe);
}

void setup() {
    WiFi.softAP("test");

    // fill string to serve:
    toServe.reserve(3000);
    for(int i=0; i<150; i++) toServe += "1234567890123456789\n";

    server.on("/long", serveLongString);
    server.on("/short", serveShortString);
    server.begin();
}

void loop() {
    server.handleClient();
}

It serves a short message on /short and a long message (3000 chars) on /long.
The /short page works everywhere: Windows, Desktop Linux (Fedora) and Android.
The /long page, on the other hand, only works on Windows and most of the time on desktop Linux. It never works on Android. I tried two phones.
I captured the network traffic on my Android phone using tPacketCapture. This is the result:

When trying to get /short, everything works fine. When trying to get /long, only the header comes through but the content never arrives. As I said, everything works fine on Windows and (most of the time) on Desktop Linux. Any idea what's going wrong?

Sounds like you're hitting some MTU limit or fragmentation issue.

@Majenko yeah, when the response takes up more than one TCP packet, Android only receives the first one (as seen in the capture). It works on other operating systems though.

This seems to be a problem with the core libraries, probably best to open an issue on GitHub.

The solution is to add the following line to platformio.ini:
build_flags = -D PIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY

I noticed that the same sketch works without a problem when building with the Arduino IDE, so I checked the differences in building with platformio and the Arduino IDE.
Turns out the relevant difference is that the Arduino IDE uses lwIP 2 by default, while platformio uses 1.4, which seems to have this bug (the same bug appears when using the Arduino IDE with lwIP 1.4).
The build flag above tells platformio to use lwIP v2.


text:
Change one specific byte of an IP address
So if I have an IP address IP Address: 192.64.5.1, is it somehow possible to change a specific byte of that IP to like IP Address: 192.64.**6**.1
My idea is to change the IP Address into variables IP Address: a.b.c.d
Now I could say a= 192; b= 64; c= 5 + 1; d= 1
But what if I receive the IP Address: 192.64.5.1 as a String. Is it somehow possible to split it up into 4 parts that I can each individually assign to an integer (a, b, c or d)?

You can do it all with the IPAddress class.
For instance: create an IP address from a string:
IPAddress myAddr(myString);

Create a new IP address with one byte changed:
IPAddress myNewAddr(myAddr[0], myAddr[1], myAddr[2] + 1, myAddr[3]);

and myAddr[2] = 6. myAddr[2]+=1 or myAddr[2]++ works too

Yes, you can split the string with the C library function strtok, than concatenate everything together with your own string with the C library strcat.
You can convert strings to atoi, so use the resulting string from strtok with atoi to an integer.
Tip: try it on a PC with a local C compiler, because you can check it very fast (unless you can implement it first time right). Than you copy it to your Arduino sketch. Make sure to start with a char buffer big enough for the biggest possible IP address string.


text:
Compare incoming message from ESP8266
If there's one thing I never managed to do: it's comparing strings.
So I have the incoming message saved here
String Message2 = IClient[i].readStringUntil('\n');

And every time I try to compare it with
strcmp(Message2.c_str(),"Red"); //Hopefully comparing the Message2 with "Red"

I never get 0 returned.
I know from printing the Message2 to Serial that Message2 contains the word "Red".
I've tried using different methods (string.equal(string2); etc.) but it never said that they are equal. What am I missing out on?

Might want to remove the extra characters ("..."). Or compare with ""Red"".

Found the answer!
After testing around with changing the terminator of the readStringUntil('\n') method it appears that there were leading and trailing white spaces, though not being displayed on the serial monitor they still had an impact on the strcmp(string1, string2) method.
I could solve this problem by "trimming" the received string before comparing it by using the String1.trim(); method.
In the end looking like:
String Message2 = IClient[i].readStringUntil('\n');

Message2.trim();

strcmp(Message2.c_str(),"Red");

a week ago https://arduino.stackexchange.com/questions/62546/wifi-connection-times-out-if-credentials-retrieved-via-serial-terminal#comment134274_62546


text:
ESP8266 TCP/IP communication
So I'm looking into having a TCP communication between 1 ESP8266 Chip (Station) and 2 ESP8266 (Clients) connected to that station. Every time I find a code including the TCP, they only include things like client.print(). But how can I write a message to a certain IP address in that network.
When I do client.print() it sends the message to ALL the clients. But I want to be able to do something like client1.print() and client2.print()

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.
If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.
client socket
if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side
WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}


text:
"function" was not declared in this scope (called in setup)
I have this bit of code I'm trying to execute only once. but I seem to get this error every time I try to compile: "calcOppervlakte' was not declared in this scope" when it's being called in the setup.
I've looked at code examples where calling functions like this works, and I cannot wrap my head around this problem.
google isn't really helpful either since the search for something-something not declared in this scope gets me thousands of results.
double pi = 3.14159265359;

void setup() {
  Serial.begin(9600);
  for(int r = 1; r <11; r++){
    Serial.print(calcOppervlakte(r)); <----
  }
}

void loop() {

}

double calcOpppervlakte(float radius){
  double result = pi * pow(radius, 2);
  return result;
}

The function name you're calling is calcOppervlakte but the function name in the definition is calcOpppervlakte. If you look closely you'll see there is an extra p in the function definition. If you change the names to match the error will be resolved.


text:
Can i use a range in a switchcase like in pascal?
in pascal's case statement i can use this:
Var i : integer;
...
Case i of
 1..5 : DoSomething;
end;

i was wondering if there is a way in can do this with c/c++ in the arduino compiler using:
switch (var) {
   case 1..5:
     // statements
     break;

or is this only possible using if/else?

In C/C++ you need to write the case explicit "case A: case B: ... break;" https://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm

Short answer: No
Longer answer: Each case in a switch statement must be a discrete value (which is why floats and doubles won't work either) but there are way around it.  In order of preference:
A) Utilise the "drop through" feature
switch (value)
{
  case 1: // Deliberate drop through
  case 2: // Deliberate drop through
  case 3: // Deliberate drop through
  case 4: // Deliberate drop through
  case 5:
    DoThingA();
    break;
  case 6:
    DoThingB();
    break;
}

B) Change the logic so the range is the default  (not nice, but if you have no other option):
switch (value)
{
  case 6:
    DoThingB();
    break;
  default:
    DoThingA();
    break;
}

C) Use a helper function (Really ugly, but...).  There would have to be a good reason not to call the DoThing() from the helper function.
enum DoOptions {EOptionA, EOptionB};
DoOptions DoWhat (int value)
{
  if (value < 6) return EOptionA;
  return EOptionB;
}
switch (DoWhat(value))
{
  case EOptionA:
    DoThingA();
    break;
  case EOptionB:
    DoThingB();
    break;
}

I guess ill be using if statements then. thx for the quick reply.

The above posted code results in two(2) compiler messages, 1 warning and 1 error

That doesn't surprise me, I wrote them to explain what I was trying to say in the text, not to provide a water tight solution to the problem.  If you are not able to clear the issues on your own, feel free to post details and I'll solve them for you.

There are some GNU extensions available in the avr-gcc/avr-g++ compilers (used in Arduino IDE for AVR based Arduino boards). One of them is suport of ... for the case:
  switch (i)
  {
    case  10 ... 100:  Serial.println(F("First"));           break;
    case 101 ... 1000: Serial.println(F("Second"));          break;
    default:           Serial.println(F("Everything else")); break;
  }

But, it's not the part of C/C++ standard, it's just compiler extension, so there is possibility it fails to compile on different platforms (mainly different compiler). So it's better to avoid it in portable code.

In the settings I have turned on extra warnings and I have added the pedantic flag, then the compiler issues a warning: range expressions in switch statements are non-standard. But I still use it anyway.


text:
LiPo + charge/boost circuit vs pre-built "power bank" - contrasting portable power sources
Portable 5V power for my projects - I was about to get the necessary parts to wire up an OEM LiPo battery (3.7V battery, boost circuit, charging circuit) when I took a peak at pre-built "power banks".  From all the sources I see the LiPo batteries alone cost more than the power bank, at much lower capacity.  For reference:

a 10400 mAh power pack (max output 3A @ 5V) is 26$ on Amazon
a 10000 mAh power pack (max output 2.1A @ 5V) is 9$ on Hobby King
a 2500 mAh LiPo is 17$ on Amazon
a 5000 mAh Lipo is 8$ on Hobby King

The power packs already have charging and voltage regulation circuitry! The price difference makes me think I am missing something.
Reading around I notice issues with power packs auto-shutdown at low current draws. But other than this power packs seem cost optimal and technically equivalent - at least within the output amperage range of the power banks.
Questions:

Are there any technical differences in output voltage, lifetime, or otherwise I am missing here?
Are there any "surprises" I'm going to face by using a power pack?
Can you recommend a solid power pack that doesn't shut down at arduino level draws. (My app will draw 800mA @ 5V max, but during sleep, the draw of an Arduino Nano)

Thanks!

This would be better posted at https://electronics.stackexchange.com - perhaps someone can move it?

fwiw, i've bought about 10 power banks and diy shells. All of them want at least ~70ma to stay away. You can get creative with supercaps or watchdogs to work around that. Or KISS: don't use sleep and they are great. Also, some battery charging modules have the same feature, so check your datasheet.

The thing to remember with power banks bought on places like eBay and Amazon is:

THEY LIE ABOUT THE CAPACITY

A typical power bank you would expect to get around 3600mAh from, even though it may say 10000mAh, 50000mAh, 1,000,000,000,000mAh, etc.
The only technical difference between rolling your own circuit and a power bank is the low-current switch-off that many (but not all) of them have.  That switch-off is fine if you are always drawing a good amount of current, but once your device goes to sleep and the current drops right down you'll find the power bank will switch off and your device will never wake up again.
However, with rolling your own system you know what you are getting. You know the capacity of your battery.
One further thing to consider: Do you really need 5V? The majority of electronics run from 3.3V nowadays, and the Arduino is no different. There are Arduino boards designed to run from 3.3V, and even 5V boards can be tweaked to run at 3.3V (albeit slower than normal).
So the ideal solution would be:

A single-cell Li-Poly / Li-Ion giving nominal 3.7V
A Li-Ion charger circuit
A low-dropout or switching regulator with max 400mV dropout.

And no boost circuit needed. Also, no logic level shifting when communicating with 3.3V devices.


text:
wiring a arduino led project
I am moving a project from breadboard and jumper cables.
It light a bunch of LEDs with different sets running of many almost every pin.
I need a few meters of cables.
I will a resistor on each led.
I have no idea what kinda cable/wire to use and googling cable gets me nowhere.
What kinda wire do people use?

I don't quite understand your question, but would ribbon cable fit the bill?

Otherwise, describe what sort of cable you're looking for (presumably you have some sort of idea) and someone may know what it's called.

When choosing wire for your project the main consideration is the amount of current. Second would be the distance.
For LEDs the current is generally low (milliamps) so something like a 20 or 22 gauge wire would be fine. You should be able to get it at a local hobby electronics shop or Amazon of course.
FYI, Wire gauge numbering is such that the lower the number the thicker wire. Thus 20 is thicker than 22.
You may find this AWG (American Wire Gauge) table helpful: http://www.powerstream.com/Wire_Size.htm

With careful choice of wire thickness and length paying close attention to the resistance-per-meter it may be possible to do away with the LED resistors entirely and use the resistance of the wire instead.

authors: Василий Егоров


text:
DS3231 AT24C32 IIC making digital outputs not work
I have just taken the code from
https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/wiring-and-test
to get DS3231 AT24C32 IIC to work fine with my Aduino and its working fine.
I have then taken
https://learn.adafruit.com/adafruit-arduino-lesson-4-eight-leds
and expanded it to work with three 74HC595 Shift Register. And this is working fine with all three sets of LEDS lighting up one after an other like in the demo.
So I do not think there is anything wrong with my wiring.
When I merge the two demos together, all the output pins on my this shirt register just give out positive current constantly.
I have walked through each line of the code and the problem is caused by
if (! rtc.begin()) {

if I take out that if statement everything works.  But since that is the bit that starts the clock I want that.
So how do I get the DS3231 started and not have all the pins on the third shift register high?
Also if it matter it is an official Leonardo board.
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

int latchPinOne = 5;
int clockPinOne = 6;
int dataPinOne = 4;

int latchPinTwo = 11;
int clockPinTwo = 10;
int dataPinTwo = 8;

int latchPinThree = 3;
int clockPinThree = 13;
int dataPinThree = 2;

byte leds = 0;

void setup()
{
#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  pinMode(dataPinOne, OUTPUT);
  pinMode(latchPinOne, OUTPUT);
  pinMode(clockPinOne, OUTPUT);

  pinMode(dataPinTwo, OUTPUT);
  pinMode(latchPinTwo, OUTPUT);
  pinMode(clockPinTwo, OUTPUT);

  pinMode(dataPinThree, OUTPUT);
  pinMode(latchPinThree, OUTPUT);
  pinMode(clockPinThree, OUTPUT);

  Serial.begin(9600);
  Serial.println("Start");

  delay(3000); // wait for console opening
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
}

void loop()
{
  leds = 0;
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(500);
  }
}

void updateShiftRegister()
{

  digitalWrite(latchPinOne, LOW);
  shiftOut(dataPinOne, clockPinOne, LSBFIRST, leds); // send the data
  digitalWrite(latchPinOne, HIGH);

  digitalWrite(latchPinTwo, LOW);
  shiftOut(dataPinTwo, clockPinTwo, LSBFIRST, leds); // send the data
  digitalWrite(latchPinTwo, HIGH);

  digitalWrite(latchPinThree, LOW);
  shiftOut(dataPinThree, clockPinThree, LSBFIRST, leds); // send the data
  digitalWrite(latchPinThree, HIGH);
}

Check for pin conflicts. What pins are used for the RTC? SDA and SCL but they are also pins 2 and 3. Opps!

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.

It was the fact I was using Pin 2 And 3 for output.  I didn't know that the SCL and SDA were connecting Pin 2 and 3.  I Changed it to Pin 7 and 9, and everything worked.

https://en.wikipedia.org/wiki/The_devil_is_in_the_detail


text:
Light up more than one LED connected to 74HC595 Shift Register
I have a 74HC595 Shift Register with a LED (and resistor) on each of the 8 output pins.
I can light them all up
I can light one up
How do I light two up?
For example the one on pin 2 and the one on pin 7
I used this a my starting point.
https://learn.adafruit.com/adafruit-arduino-lesson-5-the-serial-monitor?view=all
Is 74HC595 Shift Register  the correct componet to use?

You don't mention if you are using and Arduino, but I will assume that is the case.
Using the shift register to light up LEDs is fairly straight forward.
You can use the ShiftOut() function to send out an 8bit binary value to the register. https://www.arduino.cc/en/Reference/ShiftOut
In summary however, if you want to light up the LEDs on the output pins 2 and 7 you would shift out b01000010 to the shift register. If you wanted pins 4, 5 and 7 to light up, you shift out b01011000. These assume the least significant bit is sent first.
Here's an example:
// set shift register output pins 2 and 7 to high
uint8_t data = 1<<2 | 1<<7; // use bit shifting

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, data); // send the data
digitalWrite(latchPin, HIGH);

Cheers, that works a charm

How do I light two up? For example the one on pin 2 and the one on pin 7

If the LEDs are active high, sending 0x82 lights up the two LEDs.
If they are active low, sending ~0x82 lights up the same LEDs


text:
Communicate from Arudino to computer over 3.5mm port
I'm wondering if it would be somehow possibly to have easy communication with a computer for Arduinos that don't have USB like the pro mini. That would make an easy way of having two-way communication with a computer. The computer could just play or record audio using software written specifically for this purpose. Would something like this require any special circuitry or would it just be a matter of connecting the right wires?

This is exactly how old home computers loaded and saved data to cassette.

@Majenko I guess a good question would be, what standard was used, and if that standard maybe already has an Arduino implementation.

FSK is the most common and easiest to implement. You can transmit just with the tone() function if you time it right...

I didn't read the all page, but it seems it can be achieved, see David Awehr's blog (this one is conected to a android phone instead to a PC tho) and this Hackaday page where they seems to it, but the PC's audio input normally use 44,1kHz or 96kHz, so if you wanna go for the higher Serial speed (let's say just 115200bauds) you should think about it this.

Thanks, those articles will be a point to further my research.


text:
Arduino Mega resets when DFPlayer speaker plugged into amp!
I have a MP3 DFPlayer Mini connected to a Mega2560. I'm using serial to control it. The Mega is powering/grounding the DFPlayer, and USB is powering the Mega. If I plug a small speaker directly to the DFPlayer speaker pins, I hear the audio as expected. Tracks play correctly, at the proper volume, etc.
I also have a 20w audio amplifier (MAX9744, and 20w speaker ofc), powered separately by a 12v DC wall plug. If I plug an iPod into that via the stereo jack, I hear nice loud audio, as expected. Everything is fine.
For months, I have had the DFPlayer speaker pins supplying audio into the headphone jack on the amplifier. It has been working perfectly. Until recently...
Now, for some reason, the Mega2560 instantly resets, and will continue to reset every couple of seconds while the speakers are plugged in to the amplifier. As soon as the line in stereo jack is removed from the amplifier, the Mega works again.
This has me completely stumped. This setup has previously been working perfectly, for several months. The amplifier is clearly affecting the Mega somehow (via the DFPlayer!), even when no audio is actively playing. But I'm stuffed if I can figure out where the problem is!
I appreciate any ideas and suggestions you may have.

Sounds as the ampifier is drawing too much current from the DFPlayer. Maybe try to add a resisitor between amplifier and DFPlayer to check for this. The resistor will reduce the possible current. So if I'm right the mega will then work as intended. I don't know why this would have happend though. Maybe some current rating exceeding

You should not connect the speaker outputs to an amplifier. There are separate outputs on the DFPlayer for doing that.

chrisl: The amp is drawing power from a totally separate source. The DFPlayer and Amplifier are connected in only one way - via stereo headphone jack.

majenko: which pins should I be using? The dac ones? If so, any ideas why it's been working just fine for months using the speaker out pins?

For externally amplified speakers, you should be feeding the DAC and GND pins to the amp's inputs.  Those DAC pins provide a signal that varies by a small number of volts and is shifted so that they're always positive.  This is in the range expected by small headphones (ear buds) and line level inputs to audio components like an amplifier.
The speaker pins on the DF Player mini are pre-amplified (a little tiny bit) to directly drive a very small speaker (like 2 Watts at 8 Ohms).  They are a differential signal that includes both positive and negative voltages (relative to GND).  Note that the two speaker outputs (SPK+ and SPK-) are not left and right, but two sides of a differential signal.  Based on the schematic on page 11 of the datasheet (Chinese), it's a mono output made from mixing the outputs of the left and right DACs.
I could see how you might have gotten away with sending those to the amp, since the pre-amped speaker outputs are low power, and a good amp probably has input protection.
I don't know enough about electronics to know why it's failing now when it seemed to be working before.  It could be sensitive to the amplifier's gain or a ground loop between the power sources, but I'm just shooting in the dark.  Somehow, I suspect the DF Player Mini struggled to provide enough current to your amp, and since the DF Player Mini was powered from your Arduino, the Arduino essentially browned out, triggering a reset.

As Adrian McCarthy pointed out, you don't want to be running the speaker outputs into an amp like that. Use a DAC pin and Ground. As to why its stopped working - I've had trouble powering an arduino plus dfplayer from USB. The combination can quite easily draw more current than USB is designed to give. It's a bit fuzzy because not all USB supplies work exactly to proper spec. and exactly how much current you need can depend on factors as unpredictable as how much bass there is in your piece of music. If definitely nothing at all has changed in your setup, I would check in case you've got a joint going bad and shorting in the connection from the dfplayer to the amp...


text:
Will Nodemcu support 4AAA
Will Nodemcu support 4AAA batteries which is 6v approx, or should i go with 3AAA batteries which is 4.5V approx. And one more question , is it ok to use AA instead of AAA ?

Yes, yes and yes.

Will Nodemcu support 4AAA batteries which is 6v approx

Yes, it will. However there is no back-powering protection on the USB, so having that connected whilst the board is connected to your computer could potentially damage your computer's USB port. That's why VIN's label was changed to 5V on the newer boards.

or should i go with 3AAA batteries which is 4.5V approx.

Yes, you should. Not only does that mean your USB port won't die, but you're not wasting as much power. The NodeMCU employs a linear "LDO" regulator to get 3.3V from the incoming power source. That means that the voltage difference between incoming power and 3.3V is thrown away as heat. The higher the incoming voltage the more heat is generated to discard that voltage.  Using a lower voltage, therefore, means that you don't waste as much. That fourth battery is doing absolutely nothing towards powering your project and is just being used to generate more heat.  One thing to note though is that 5V coming in from USB could try and charge your 3xAAA batteries. If they're not rechargeable then they could cause problems (overheat, leak, cause a fire, etc).  Adding a schottky diode in series with them would protect them from that.

is it ok to use AA instead of AAA ?

Yes. Your project will last longer before you need to replace the batteries, since AA batteries have a higher mAh capacity than AAA.

Thanks. How long do you think 3 AAA battery can last before replacing, approximately? Im connecting only one soil moisture sensor to the nodemcu.

I can't tell you that.

Can you suggest me someway , that the board gets power for atleast a month? I tried 9V battery, and conncted the positive and negative to Vin and Gnd. The board started working abnormally. I guess 9V battery is overloading the board

It is impossible to give any value. It all depends on your code and your hardware. To get that kind of length of operation of AAA batteries you will need to use some very aggressive power saving techniques (deep sleep modes, high efficiency regulators, isolated power domains, etc).

And 9V batteries are complete junk.

Not sure I can agree with the 3 cell recommendation.  While there are indeed risks in using 4, with 3 (especially if they are NiMH not alkaline) they will probably fail to meet the regulator minimum input voltage midway through what should be their usable life, ie, to get 3.3v out you need more the 4.3v in, and most people would not consider an AA measuring 1.4 volts "dead".   Going into regulator dropout does not automatically mean the board complete fails, but it's not really a good idea.  The truth of the matter is that the NodeMCU is not designed for battery power.

The ESP8255 can operate happily right down to 2.5V. LDOs really don't care if you go below the regulation threshold - especially if they are part of a family that has versions right down to say 0.8V (as most families do), since all that differs between them is the internal feedback network. You just get a (few) diode drop(s) worth of voltage reduction.

You don't have to connect any UART. This is done through USB serial communication. So, just copy the uf2 file to pico. Let it reboot. Then you should see a ttyS* or ttyACM* device shows up in /dev/ if PX4 is running fine. Then you can connect to it using putty or minicom.

What do uf2 files and the pico have to do with a nodemcu device?


text:
Concatenate integers as string
How can i concatenate integers as a single string?
int out1, out2, out3 = 0;

    out1 = digitalRead(r1);
    out2 = digitalRead(r2);
    out3 = digitalRead(r3);

I tried like so, between others, with no luck.
Serial.write(out1 + "" + out2 + "" + out3);

For example the expected result when all outputs are HIGH should be 111, while when only the r3 output is HIGH it should be 001
All i want, is reporting to the sender of the serial command, the pins state

Since you only use 1s and 0s, you could also convert it to a three digit number, and print that Serial.write(out1*100 + out2*10 + out3);

@Gerben: You mean Serial.println().

Correction: Serial.println(out1*100 + out2*10 + out3); (thanks @EdgarBonet)

If you're just outputting to serial you don't need to concatenate - just print each bit separately, such as:
Serial.print(out1);
Serial.print(",");
Serial.print(out2);
Serial.print(",");
Serial.println(out3);

You should avoid using String as it's not good on devices with small amounts of memory like Arduinos. Instead if you really need to concatenate numbers you should use a C string and maybe snprintf to format the numbers into it:
char out[30];
snprintf(out, 30, "%d,%d,%d", out1, out2, out3);

I second Majenko's points about just printing the bits separately if
possible, and avoiding String objects.
However, if you do need to build such a string (not String object, just
plain C string), you don't need sprintf(), which is quite a big
function: you can build the string character by character. For example:
char out[4];  // 3 + 1 char for the termination character
out[0] = out1==HIGH ? '1' : '0';
out[1] = out2==HIGH ? '1' : '0';
out[2] = out3==HIGH ? '1' : '0';
out[3] = '\0';  // add NUL termination
Serial.println(out);

This is using the ternary operator, which here means “if out1 is
HIGH, then use the character '1', otherwise use '0'”.
Now, it just happens that in Arduino HIGH means 1 and LOW means 0.
And single digit numbers can be converted into character by just adding
the numeric code of character “0”, which is 48 but can written as '0'
in C++. Thus you can write:
out[0] = out1 + '0';  // convert number to character

And you can put all together as:
char out[4];  // 3 + 1 char for the termination character
out[0] = digitalRead(r1) + '0';
out[1] = digitalRead(r2) + '0';
out[2] = digitalRead(r3) + '0';
out[3] = '\0';  // add NUL termination
Serial.println(out);

Serial.write(b) prints one byte not a string. Use print() to print strings and numbers.
Serial.print(digitalRead(r1));
Serial.print(digitalRead(r2));
Serial.println(digitalRead(r3));


text:
How to connect 70 analog sensor to a single Arduino (Mega or Uno) device?
I was working on a project in which I need to collect soil moisture data for a farm. For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino. But, this is not possible as there are just 6 analog pins on Arduino Uno and 16 analog pins on Arduino Mega. I have restrictions on the number Arduino that I can use that is just one due to monetary constrains.
        The data would be collected at a delay of 5 seconds. The data gathered would be stored on SD card module which would be analyzed later.
      Any suggestion on how I can collect data from 70 analog sensors on a single Arduino would be highly appreciated. Are there any alternatives that I can use in place of Arduino? I heard that we could do something with AVR  atmega Microcontroller, am I correct? I don't know how to use Microcontroller; any useful resources will be highly appreciated. Thank You.

There are fairly inexpensive chips called "analog multiplexers" which let you choose one input out of a range (8 or 16 is typical). You could take the reading, then switch to a different input, and take another reading.
I have a page about analog multiplexers.
Example of it in operation:

In this example you have 8 inputs, and by setting the A/B/C pins appropriately, one of the 8 is selected and appears at the O/I pin (output/input).
There is a 16-channel model as well. I see the 16-pin chip (74HC4067) available on eBay for $US 1.26 right now. You can get four of them (which would give you 80 inputs) for $4.88.
Also see the Wikipedia article on multiplexers.

For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino.

Yes, well how will these sections get their data into one place? That is probably the bigger problem.
You may need to use a lengthy cable using RS485 (balanced signals) or maybe cheap radio transceivers.
Trying to use a "single Arduino" on what might be quite a large farm is the issue. It's not the Arduino's fault. You have to have some way of sending the data from the further points to where it is to be collected.

@ Nick Gammon: Thank you. Your answer was helpful. Relating to collection of data in one place, I was planning to use wires which will transfer the data to the Arduino. What problem will be caused by this? The idea of using radio transceivers is great. As I am planning to do this on a large scale, the major cost of my plan comes from the soil moisture sensor (as they are used majorly) . Now if I use a transmitter, I need to use it for all the soil moisture sensors which are doubling my budget.

If you are reading analog, extra wire adds extra resistance, which throws off your readings.  Look into the ESP8266.  WiFi module that costs about $5 at the cheapest and has a 1v analog input.  You can drive it off batteries without an Arduino.

Quite right, although the OP seemed to want to keep the device count down. It seems odd to only have a "single Arduino" but to go and buy 70 x ESP8266. However that may well be the best solution. :)

You should use some cheap chips to collect the data and use only one with big capacity to finally combine and process the data further.

Consider using a cheap small Arduino to build a "base module" that can do some of the tasks needed, build a bunch of them and hook them up to a R485 bus, and have one master Arduino control them all. That would be a much more flexible and expandable system. The cheapes Arduinos cost around 10$. If you build your own you could probably do it even cheaper.

Source:
[1] http://forum.arduino.cc/index.php?topic=73861.0
(quote)
[2] https://arduino-info.wikispaces.com/RS485-Modules (bus)

Given that good moisture sensors are going to be an order of magnitude more expensive than the logger, I'd suggest that you are giving yourself more problems than it's worth to try to connect that many sensors to the same unit. A Pro-mini based logger rarely comes in >$25. Even though we can connect that many one-wire sensors to a single logger ( https://thecavepearlproject.org/2015/03/01/using-ds18b20-sensors-to-make-a-diy-thermistor-string-pt-1-the-build/ ) it's not a good idea from the perspective of the amount of data that is lost if you have a single point failure. Generally we only put 10-15 sensors on any one unit, and we try to deploy them in "parallel" sets so that if one multi-sensor unit does fail, we loose spatial resolution, but still have enough information to work with.


text:
Using AA batteries to power Arduino and GPS unit
I'm more of a software guy, so I need your help to figure out the power issue with my Arduino.
What I would like to do is using a GSM/GPS unit (Ai-Thinker A7) with Arduino Nano as a car tracking system. I have USB cables in the car, so I can plug it into my Arduino and power both while I'm driving. To power the unit while I'm not driving, I thought using rechargeable batteries would be a good idea. I'm planning to use GPS via SMS activation, so I hope fully charged batteries will be enough to power it for at least a week. But I'm confused about a couple of things.
Rechargable batteries are 1.2V. So technically I can use 5 of them and power my Arduino and the GPS unit (which requires 5V), right? However, for a similar unit at Adafruit they say that a LiPo battery is a must. Well, I think it is because GPS unit draws more power while using GPS and stuff. So, in this case are AA batteries out of the question? Will I fry anything if I build the system as follows?

If AA batteries happen to be fine, do I need another piece in my design, such as this one?
At last, I have no idea if I need any diode, capacitor, resistance or sth else for this system. I would appreciate further comments about my design.

you need to be able to supply 2 amps. AA batteries can supply that for short periods. if find you needed more amps, you can add more cells in parallel instead of series to increase available amps. you might want to consider a buck/boost converter than can turn any (reasonable) voltage into another voltage.

If you are using NiMH batteries watch out for the self discharge, they can lose almost 50% of their charge in a week. It increases with temperature and in the summer cars get hot, you could easily find that your batteries don't last a week in the car even with nothing connected to them.

@Andrew Never thought of that, thanks. Which batteries could be better for in-car use, is there a resource that you can point out to me?

@SertalpBilal Li-Ion have very good self discharge characteristics but long periods of high temperatures can ruin their maximum capacity and they are a lot more complex to charge / make safe. Your best bet for a simple solution may be the low self discharge NiMH cells you can get (also sold as "pre-charged" rechargables). They cost a lot more than standard rechargeables but would avoid the issue.

@Andrew Do you mean something like this one?

@SertalpBilal yes.

@Andrew Thanks! As a follow up question, would that be just fine if I connect everything as shown in the drawing using low self-discharge batteries? Arduino has a linear regulator, so it will take care of step down, am I right?

The voltage regulator on the Nano has a dropout of 1.25V which means you need 6.25V on the input. That works out as 1.25V per cell if you have 5, it depends on loading and temperature but for low power applications most batteries hit that at about 50% charge. Probably best to go with 6 cells. On the plus side that should make finding a battery holder easier, 6 cells is more standard. Other than that I can't see any obvious issues.

I suggest using 6 or 8 AA's (eg 6 alkalines or 8 NiMH) and a  MP1584EN DC DC Power Stepdown Buck Converter (about a dollar on ebay, 1.5 to 3 times that on Amazon).  Note, the hole pattern does not match up with breadboard spacing:
The batteries would tie in via a couple of diodes (preferably Schottky), as shown below.  When the 12 V supply is off, the converter would be powered by 9.6 V from eight rechargeable AA's.  When the  12 V supply is on, no current is drawn from the AA's.  The converter output should be adjusted to 5V before being connected to the Nano or other devices it powers.
Using a buck regulator has two advantages vs a linear regulator: battery current is lower (allowing the battery pack to be more efficient as it discharges) and less energy is wasted as heat.
Note, it might make sense to remove the power LED from the Nano, to save 3 to 5 mA of current.

simulate this circuit – Schematic created using CircuitLab

Thanks for the detailed response. A few questions:
Is there any advantage of using 6/8 AA batteries with a step down converter compared to using a LiPo (3.7V) with a step up converter? I worry that the device will get heavier/bulkier with that many batteries.
Another question is, can I recharge batteries by plugging my Arduino into the USB in this case? It seems diodes will prevent the current into charging direction.

Not so sure if this is the one I'm looking for, but do you think something like this would work?

authors: Игорь Игумнов


text:
Strange artifact in writing to serial while executing loop
Hope you can see this.
https://gist.github.com/DevilWAH/60ad144d2858f53845ac2e80f84bb070
The main file in this is "morse-led-rfid" which is taking reading data of an RFID tag and then displaying the text as Morse code on to a APA102 / Dotstar LED strip.
The issue is when the function updatestrip(tempbuffer[i]); is called.
Serial.println(F("\n**Start Reading**\n"));

  for (uint8_t i = 1; i < 15; i++)
  {
   if (i != 3 && i!= 7 && i != 11 && i != 15 ) // Skip the non data blocks
    {
     readblock (i, key);
       for (uint8_t i = 0; i < 16; i++)
         {
      updatestrip(tempbuffer[i]);
      Serial.write(tempbuffer[i]);
        }
    }
  }

This is what I am calling to scroll the LED strip and write the letter in morse. if in the code snip it above i comment out "updatestrip...." then i get the txt from the RFID tag printer to serial as i would expect.
as a soon as i un comment it, the strip displays the morse code but the serial output gets garbled, it misses letters, prints reversed "?'s" and repeats its self?
Good output = "My Bunny is the best"
Bad output = "?Bunny is the ?t" (question marks reversed)
Further investigation i found if i leave it uncommented but go all the way to the bottom of the "more-strip" sheet and comment out the "else statement in the shiftLED function" the serial again displays correctly, but of course the led don't :)
void shiftLED() // shift all LED up 1
  {
    for(uint16_t i = ledCount; i > 0; i--)
    {

      if ((colors[i - 1].red == 0 ) && (colors[i - 1].green == 0 ))
       {
          colors[i] = cblack;
        }
      else if (i > 19 && i < 40)
      {
        colors[i] = cred;
      }
     // else
     // {
     //   colors[i] = cgreen;
     // }
     // }

 }

Can any one suggest why the else statement a few function down is affecting the "serial.write(tempbuffer[i])" in the main loop?

Using an i loop inside an i loop is very bad practice. Never nest the same variable like that - it makes it impossible to know what you intend.

Hi, I did actuality think that, and went though and changed this. I have to admit to being a very hacky programmer (not sure i can even call my self that, it an insult to the real ones). Will add to list of things not to do.

In your code colors is declared as
rgb_color colors[ledCount];

This means that the very first iteration of this cycle in shiftLED
for (uint16_t i = ledCount; i > 0; i--)
{
  // access colors[i]
}

will access ledCount[ledCount] which is obviously out of bounds (and will actually write into that location!). The behavior is undefined after that.
Using unsigned types for "backward" array iteration requires a bit of skill. The common idioms are
for (uint16_t i = ledCount; i > 0;)
{
  --i; // do this ASAP

  // access colors[i]
}

or
for (uint16_t i = ledCount; i-- > 0;)
{
  // access colors[i]
}

or
// Careful: this technique is not usable with unsigned types
// narrower than `unsigned int`
for (uint16_t i = ledCount - 1; i != -1; --i)
{
  // access colors[i]
}

This is assuming that you want to iterate over the whole array: from [ledCount - 1] all the way back to [0].
But if you intended to iterate back to [1] and stop short of [0] (which is apparently the case), then a simple fix for your cycle would be
for (uint16_t i = ledCount - 1; i > 0; i--)
{
  // access colors[i]
}

I.e. simply start from ledCount - 1, not from ledCount.

OH! correct me is I am wrong but you mean when LEDCount = 60 the valid array values are 0 though 59? so accessing access colors[i] when i = LEDCount means i am writing to array position 60 not 59! A kind of buffer over flow?

And you got me to go look up more about signed and unsigned. When back at home tonight i will try out your suggestions, thanks for the help.

@DevilWAH Yes, if LEDCount is 60, then the valid indexes for colors array are from 0 to 59. Index 60 is out of bounds.

Just to confirm that sorted it out :) thank you for taking the time out to help and explain.