Unable to turn off SRAM 23LC1024 connected to Arduino I'm trying to reset SRAM 23LC1024 (Turn it off and turn it on again) connected to my Arduino Mega 2560. I need to do that because I want to profile the SRAM in an attempt to implement PUF. Currently, I'm able to read and write to SRAM.

I try to cut off the ground connected to SRAM, disable the SPI, but the memory in SRAM is not back to random value (initial value of SRAM if you reset it correctly). To disconnect or connect the ground with SRAM, I used MOSFET. Before cut off the ground, I write 1's to all memory. But, after wait for seconds (or minutes), the value still the same.

Now, the only way to reset the SRAM that I know is by resetting the Arduino itself. Can someone help me?

Below is my code

#include <SPI.h>

//SRAM opcodes

#define RDSR        5
#define WRSR        1
#define READ        3
#define WRITE       2

byte cs_pin = 10; //cs_pin location of the two SRAMS

//uint32_t maxram = 131072; //number of bytes in 23LC1024 SRAM
uint32_t maxpage = 4096;  //number of pages in 23LC1024 SRAM
//uint32_t maxpage = 1024;  //number of pages in 23K256 SRAM

/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-*/
//Page transfer Functions
//here we can read and write 32 bytes at each address

void Spi23LC1024Read32(uint32_t address, uint8_t cs_pin, uint8_t* buff)
{
  uint32_t i;
  uint8_t read_page;

  digitalWrite(cs_pin, LOW);
  SPI.transfer(READ);
  SPI.transfer((uint8_t)(address >> 16));
  SPI.transfer((uint8_t)(address >> 8));
  SPI.transfer((uint8_t)address);

  for (i = 0; i < 32; i++)
  {
      read_page = SPI.transfer(0x00);
      buff[i] = read_page;
  }
  digitalWrite(cs_pin, HIGH);
}

void Spi23LC1024Write32(uint32_t address, uint8_t buffer170, uint8_t cs_pin)
{
    uint32_t i;

    digitalWrite(cs_pin, LOW);
    SPI.transfer(WRITE);
    SPI.transfer((uint8_t)(address >> 16));
    SPI.transfer((uint8_t)(address >> 8));
    SPI.transfer((uint8_t)address);

    for (i = 0; i < 32; i++)
    {
        SPI.transfer(buffer170);
    }
    digitalWrite(cs_pin, HIGH);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-*/

uint32_t i, j, n;
uint32_t value;
uint32_t num = 0;
uint32_t total_send = 10;
uint8_t buff[32];
uint32_t index = 0;
uint8_t total_buff[32*128];
int inByte;

int pin_hold = 11;
int pin_select = 10;
int pin_mosfet = 12;

void readSRAM(){
  SPI.begin();
  digitalWrite(pin_select, LOW);
  digitalWrite(pin_hold, HIGH);
  digitalWrite(pin_mosfet, HIGH);
  delay(100);

// read
  for (j = 0; j < maxpage/128; j++){
    index = 0;
    for (i = 0; i < 128; i++)
    {
      Spi23LC1024Read32(j*128+i, cs_pin,buff);
      memcpy(&total_buff[index], buff, sizeof(buff));
      index += 32;
    }

    for (i = 0; i< index; i++){
      Serial.println(total_buff[i], HEX);
    }
  }

   digitalWrite(pin_select, HIGH);
  digitalWrite(pin_hold, HIGH);
  digitalWrite(pin_mosfet, LOW);

  SPI.end();
}

void writeSRAM(){
  SPI.begin();
  digitalWrite(pin_select, LOW);
  digitalWrite(pin_hold, HIGH);
  digitalWrite(pin_mosfet, HIGH);
  delay(100);

// write
  for (j = 0; j < maxpage/128; j++){
    index = 0;
    for (i = 0; i < 128; i++)
    {
      Spi23LC1024Write32(j*128+i, (uint8_t) 0, cs_pin);
    }
  }

  digitalWrite(pin_select, HIGH);
  digitalWrite(pin_hold, HIGH);
  digitalWrite(pin_mosfet, LOW);

  SPI.end();
}

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

  delay(100);

  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(pin_select, OUTPUT);
  pinMode(pin_hold, OUTPUT);
  pinMode(pin_mosfet, OUTPUT);
}

void setup(void)
{
  set();

  readSRAM();

  writeSRAM();
}

void loop()
{
}

As an experiment I would make sure ALL the pins are at 0V for reset. Power on ANY pin with a return path may provide enough parasitic power to prevent a proper shutdown.

As has been pointed out you can use a I/O pin to power the device. This SRAM has 10mA operating current; enough to be supplied by an I/O pin. Then, with code only, you can make sure all pins go to 0V for the reset. This will also give you an extra power saving mode for free.


Arduino - Rural A-GPS Station I'm trying to set up a GPS tracking solution in a rural area. The catch is the GPS trackers need to be lower cost (power and cash), because there will be a good amount of them.

So I'm trying to find a solution where I can benefit from A-GPS using a beacon of some sort to handle any cpu/server calculations while receiving GPS noise from the tracking devices (I think that's the idea). I've read up a bit on Mobile Station Assisted (MSA) GPS, but I'm not entirely sure what solutions there are to handle this.

Any help or advice is appreciated.

Example:

Arduino GPS tracker x 200 ---[RF comms/GPS noise]--->  Beacon/Tower  ---[Internet]---> GPS Server

I'm not sure I get what you want, but the A7 module of Ai-Thinker is a good GPRS module with GPS in it.


How to know the external interrupt origin from the ISR I'd like to know if there is any way to know what is the origin of an external interrupt by programming inside the ISR.

I know I can use a different ISR for each external interrupt and that works but I'm thinking if it's possible to use the same ISR for all external interrupts

If you check the origin pin and trigger condition inside ISR it's not a reliable way to do.

Is there any memory record which store the external interrupt activation?

This is a general question for any AVR microcontroller.

Is there any memory record which store the external interrupt
  activation?

There is, but I do not think it will be easy to exploit.

At low level, each interrupt is handled by a different ISR. So you will
have INT0_vect handling external interrupt 0 and INT1_vect
handling interrupt 1. These ISRs are all defined by the Arduino
core library. In your case, they will both call the same handler that
you defined. Thus, the information about which ISR fired is now on the
stack: it is the return address of your function.

The reason this information will not be easy to use is that you do not
know how far it is from the stack pointer. It depends on how much stuff
your own handler pushed onto the stack. You could disassemble it and
count, but then your code will be fragile, as the smallest change in the
handler (or compiler version) may change this count.

An easier approach may be to define your own INT0_vect and
INT1_vect, overriding those from the Arduino core. These new ISRs
will both call your handler, but they will pass it an argument to tell
which interrupt fired.

Or you can register a different handler for each interrupt, each calling
a common function. But this adds an extra level of function calls.


Byte text file to array I'm trying to display a bitmap on gLCD 128x64, I stored the bitmap into txt file 1.txt in a SD card this is a part of bit map  as following:

0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0,
0xC0, 0xC0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00.......

I want to convert the content of this text into array:
Unsigned char logo[] with making a split on ",".

Any help please

The most efficient way is to read the file byte-by-byte into a small character array until you get a comma or the end of file - ignoring any characters that aren't of interest (line feeds, etc).

Then for each chunk that you read you then convert it to an integer.

For example (untested):

char temp[5] = {0}; // should be more than enough
int pos = 0;
int bno = 0;

const char *hexchars = "0123456789abcdefABCDEFx";

while ((int ch = myFile.read()) >= 0) {
    if (ch == ',') { // We found a comma
        logo[bno++] = strtoul(temp, NULL, 16); // Base 16 conversion
        pos = 0;
        temp[0] = 0;
    } else if (strchr(hexchars, ch) != NULL) {
        if (pos < 4) {
            temp[pos++] = ch;
            temp[pos] = 0;
        }
    }
}

Of course, you have to know how big the logo array has to be beforehand.

One does, though, have to ask "Why are you storing a graphical logo as a textual representation of binary data" in the first place?  It would be far easier to just store it as a simple binary file and read the data directly into the logo array with a single File::read(void *buf, size_t nbyte); function call.  Using text as an intermediate format is both wasteful and needlessly increases complexity massively.


Custom Debounce Code Not Working It's my custom debounce code

It keeps the led on by flipping the required threshold value when triggered after the led has turned on to keep the led in a high state and vice verse triggered again, the comments on the code explain it in more detail.

/*
 * This code is my custom debounce code, I made this but this isn't working as planned,
 * see the thing is that it turns on when I hold the button and if I release it,
 * it starts to flickers and then gradually turn off, what is wrong with my code ?
 * I can't see it.
 */

const int ledPin = 13; // led connected to pin 13
const int PushButton = 2; // a pushbutton connected to pin 2
int switcher = HIGH; // the switcher changes it's value, we require this later
int dilay = 1; // controls the delay
unsigned long lastTrigger = 0; // records the last time the led was turned on

void setup() {
  pinMode(ledPin, OUTPUT); // sets ledpin as output
  pinMode(PushButton, INPUT); // sets pushbutton pin as input
}

void loop() {
  int pushButtonState = digitalRead(PushButton); // stores the value of the pin each time the loop begins agian

  if((millis() - lastTrigger) >= dilay){ // my custom debounce code
    if(pushButtonState == switcher){ //  this is the trick, when the pushbutton pin is high it's equal to the switcher value
      digitalWrite(ledPin, HIGH); // it turns on the led
      int switcher = LOW; // now the switcher value will be low now the pushbutton pin value will also be low keeping the led on
    }else{
      digitalWrite(ledPin, LOW); // now if the led is on and pushbutton is high, then it will not be equal to the switcher because we had changed it in the previous statement
      int switcher = HIGH; // now the switcher is high and the pushbutton value low, switcher isn't equal to pushbutton so there by keeping the ledpin as low

    }

    if(pushButtonState == 1){ // if pushbutton is high
      int lastTrigger = millis(); // then  lastTrigger equals to the current time
    }
  }

}

Change int switcher = LOW/HIGH to just switcher = LOW/HIGH.

Otherwise you are redefining the variable, and will make it a local variable, and not change the global variable with the same name (as you are expecting).


Serial monitor disconnecting itself Problem: can't print to the serial monitor, it appears that the serial monitor disconnects itself after uploading a program.

I'm brand new to arduino, and I'm trying to upload a basic program to print to the serial monitor.

I use an arduino uno and my OS is Ubuntu.
I am connecting the arduino to my PC via USB.
Using Arduino Studio Release 0.0.5 experimental build 0.0.5-16058

(I am able to communicate via the digital output pins, tested by making a simple circuit to make the led light blink)

Here is the program:

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

void loop()
{
    Serial.print("test");
    delay(500);
}

Here is the result of the build, look at the last line and it says the serial monitor was disconnected? Why would this happen automatically?

[2/2/2016 8:51:26 PM] - Start Building
[2/2/2016 8:51:26 PM] - CPP File Created [/tmp/build1454471486915/test.cpp]
[2/2/2016 8:51:26 PM] - test.cpp compiled
[2/2/2016 8:51:26 PM] - CDC.cpp compiled
[2/2/2016 8:51:27 PM] - HID.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial0.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial1.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial2.cpp compiled
[2/2/2016 8:51:27 PM] - HardwareSerial3.cpp compiled
[2/2/2016 8:51:27 PM] - IPAddress.cpp compiled
[2/2/2016 8:51:27 PM] - Print.cpp compiled
[2/2/2016 8:51:27 PM] - Stream.cpp compiled
[2/2/2016 8:51:27 PM] - Tone.cpp compiled
[2/2/2016 8:51:27 PM] - USBCore.cpp compiled
[2/2/2016 8:51:27 PM] - WInterrupts.c compiled
[2/2/2016 8:51:27 PM] - WMath.cpp compiled
[2/2/2016 8:51:27 PM] - WString.cpp compiled
[2/2/2016 8:51:27 PM] - abi.cpp compiled
[2/2/2016 8:51:27 PM] - hooks.c compiled
[2/2/2016 8:51:27 PM] - main.cpp compiled
[2/2/2016 8:51:27 PM] - new.cpp compiled
[2/2/2016 8:51:28 PM] - wiring.c compiled
[2/2/2016 8:51:28 PM] - wiring_analog.c compiled
[2/2/2016 8:51:28 PM] - wiring_digital.c compiled
[2/2/2016 8:51:28 PM] - wiring_pulse.c compiled
[2/2/2016 8:51:28 PM] - wiring_shift.c compiled
[2/2/2016 8:51:28 PM] - CDC.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HID.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial0.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial1.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial2.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - HardwareSerial3.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - IPAddress.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Print.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Stream.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - Tone.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - USBCore.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - WInterrupts.c.o linked to core.a
[2/2/2016 8:51:28 PM] - WMath.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - WString.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - abi.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - hooks.c.o linked to core.a
[2/2/2016 8:51:28 PM] - main.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - new.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - test.cpp.o linked to core.a
[2/2/2016 8:51:28 PM] - test.ino linked to core.a
[2/2/2016 8:51:28 PM] - wiring.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_analog.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_digital.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_pulse.c.o linked to core.a
[2/2/2016 8:51:28 PM] - wiring_shift.c.o linked to core.a
[2/2/2016 8:51:28 PM] - test.cpp.elf linked to core.a
[2/2/2016 8:51:28 PM] - test EEPROM
[2/2/2016 8:51:28 PM] - test.hex builded
[2/2/2016 8:51:28 PM] - Uploading...
[2/2/2016 8:51:30 PM] - Uploaded
[2/2/2016 8:51:30 PM] - [arduino ide - serial monitor] Serial monitor connected to /dev/ttyACM0
[2/2/2016 8:51:36 PM] - [arduino ide - serial monitor] Serial monitor disconnected from /dev/ttyACM0

I'm not sure why your IDE is doing that, but the official Arduino IDE from Arduino.cc works on Ubuntu and does not have that issue. Download from Arduino Software download page.


What is the best way to define an I/O pin? I read definitions like

const int ledPin = 9;

and also

#define ledPin 9

I know that a definition like

int ledPin = 9;

is a bad practice if you're not going to change it (which you usually won't), though I've see this several times in Arduino programs.
Which one of the other two is preferred?

#define ledPin 9 is preferred. By doing int ledPin = 9; you will be allocating an int memory whose value is used every time you use ledPin. #define is different in the sense it doesn't allocate memory. there is no memory called ledPin. Before compiling all "ledPin"s in the code(other than strings) are replaced by 9. So basically

digitalWrite(ledPin);

becomes

digitalWrite(9);

Advantages of #define : Saves memory and since all ledPin are replaced by 9 before execution, it saves processor time.
Doesn't really matter in small codes...


What would be the right way to connect 2 fsr resistors, jumper wire cables and 2 10khm resistors onto the breadboard Hi at the moment we are trying to connect 2 fsr sensors to the breadboard and then using the jumper wire cables to connect it from the breadboard to the arduino device.

we connecting the cables to 2 analog pins and the other two to the 5v and ground pin, the problem is that they way we phyically connect these components on both the breadboard and the ardiuno are wrong.
So could someone help me to understand what would be the right way to physically connect all the components together.

From this Adafruit tutorial:

  The easiest way to measure a resistive sensor is to connect one end to Power and the other to a pull-down resistor to ground. Then the point between the fixed pulldown resistor and the variable FSR resistor is connected to the analog input of a microcontroller such as an Arduino (shown).


Should I try to make my sketches as small as possible, even when I have enough room? There has been a lot of talk about shrinking sketches recently, but if you don't need the room, should it be done? Will it speed up my program?

Take this code:

int led = 13;
int val;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  val = digitalRead(10);
}

1,396 bytes on Arduino Uno. Now let's shrink it a bit:

int led = 13;
int val;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  blink();
  val = digitalRead(10);
}

void blink() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

1,270 bytes. A 10% decrease! It could be shrunk even more. I have the space... is it more efficient (as far as speed) to make it the most compact I can or leave it "uncompressed?" I would imagine that it would be a little more work (not much) calling blink();, therefore slowing down my code. Is this true? Are there other advantages/disadvantages of making it as small as possible (besides storage/distribution of C++ files)?

You second code may be smaller in size but due to the function call overhead the max execution speed is reduced.
Does this matter in your case? No, because you have huge delays anyway, but if the code was an actual series of repeated calculations that should be executed as fast as possible then it would make a difference.

As a general rule, smaller code is not necessarily faster too.

For code optimization (either size or speed) you can refer to this application note from Atmel AVR4027: Tips and Tricks to Optimize Your C Code for 8-bit AVR Microcontrollers

I could repeat everything it says here but I don't think there is a point, you can read the original article directly.

Regarding the compiler optimization level. Arduino IDE uses the avr-gcc compiler with a setting for Os optimization.
The avr-gcc available optimization levels are (source1 source2)

O0 or no -O option
At this optimization level GCC does not perform any optimization and compiles the source code in the most straightforward way possible. Each command in the source code is converted directly to the corresponding instructions in the executable file, without rearrangement. This is the best option to use when debugging a program and is the default if no optimization level option is specified.
O1 or -O
This level turns on the most common forms of optimization that do not require any speed-space tradeoffs. With this option the resulting executables should be smaller and faster than with -O0. The more expensive optimizations, such as instruction scheduling, are not used at this level. Compiling with the option -O1 can often take less time than compiling with -O0, due to the reduced amounts of data that need to be processed after simple optimizations.
O2
This option turns on further optimizations, in addition to those used by -O1. These additional optimizations include instruction scheduling. Only optimizations that do not require any speed-space tradeoffs are used, so the executable should not increase in size. The compiler will take longer to compile programs and require more memory than with -O1. This option is generally the best choice for deployment of a program, because it provides maximum optimization without increasing the executable size. It is the default optimization level for releases of GNU packages.
O3
This option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels -O2 and -O1. The -O3 optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.
Os
This option selects optimizations which reduce the size of an executable. The aim of this option is to produce the smallest possible executable, for systems constrained by memory or disk space. In some cases a smaller executable will also run faster, due to better cache usage.


WatchDog on Arduino Nano - does not recover I'm trying to add a watchdog on an Arduino Nano, for my code, and I'm following exactly code in this manual, but after the amount of time for not resetting the watchdog- it resets but does not reboot.

At last paragraph- it says that :"

  However, I could not find something similar in Optiboot bootloader (If
  I'm wrong, correct me please!), used by Arduino UNO and other new
  boards. It seems that they sacrificed this check for size. So, it is
  possible that watchdog timer will be enabled after reset, so -  if you
  set it's value too low, your board may never come out of bootloader
  stage. So, to be always on the safe side, set watchdog to longer
  periods (2S and more).

So I've tried for 8s, but still same result.

What is wrong ?

  EDIT1:

#include <avr/wdt.h>
int k=1;
void setup() {
  Serial.begin(9600);
  wdt_enable(WDTO_8S);
}
void loop() {
  //do stuff here
  k++;
  wdt_reset();
  Serial.println(1000 * k);
  delay(1000 * k);

}

This works on an Uno R3.

The sketch restarts every 4 seconds when wdt_reset() is commented out.

Please copy the code and try it.

  #include <avr/wdt.h>

  void setup() {
    pinMode(13,OUTPUT);
    digitalWrite(13,LOW);

    delay(50);
    digitalWrite(13,HIGH);    // flicker the LED to identify when setup() is running
    delay(50);
    digitalWrite(13,LOW);
    delay(50);
    digitalWrite(13,HIGH);
    delay(50);
    digitalWrite(13,LOW);
    delay(50);
    digitalWrite(13,HIGH);
    delay(50);
    digitalWrite(13,LOW);
    delay(50);

    wdt_enable(WDTO_4S);

  }
  void loop() {
    digitalWrite(13,HIGH);
    delay(500);
    digitalWrite(13,LOW);
    delay(500);
    //wdt_reset();
   }


Conditional randomization gets stuck First-time poster here...

I have the following code to randomize note values and store them in an array loop1[i], where i is a specific step in the loop:

nextNote = random(-2, 3);
note = note + nextNote;

loop1[i] = note;

while (loop1[i] == loop1[i - 1] ||
       loop1[i] == loop1[i - 2] ||
       note > 6 ||
       note < 0) {
  nextNote = random(-2, 3);
  note = note + nextNote;
  loop1[i] = note;
}

(I hope this is clear enough).

Now, it usually works to a certain point until the sketch loops forever in order to randomize an allowed number. Therefore, my questions are:

Running an ATmega 2560, is this actually a task too demanding for the processor or should I suspect that it's not working properly?

How can I optimize the code, but retain the conditions above in order to avoid the loop getting stuck?

I think you have a problem with your math here, not with your code. What
you are simulating is very similar to a 1-dimensional random
walk.
According to the linked MathWorld page, for such a process “the most
probable number of sign changes in a walk is 0”.

If, at some point in your program, the loop starts with note == 6, and
then it starts randomly going up, there is a sizable probability for it
to never go back to values below 7.

Edit: One possible solution could be to avoid the random-walk notion
and instead repeat the random choice always from the same starting
point.

int oldNote = note;  // starting point
do
    note = oldNote + random(-2, 3);
while (
    note == loop1[i - 1] ||
    note == loop1[i - 2] ||
    note > 6 ||
    note < 0);
loop1[i] = note;


NodeMCU does not boot up when GPIO pin is high I have a NodeMCU board connected to a door and there is a micro switch that makes one GPIO pin (GPIO15 - D8 in this specific case) go high when the door opens.

My problem is if I lose power while the door is opened, the GPIO15 is fed high at the next boot when power is restored. And it makes the board go to a not responding state. I have to boot it again while the door is closed (pin is low) to bring it back to work. I experienced this while flashing too. I cannot flash while this pin is high (while the door is open).

How can I fix this?

Certain pins of the ESP8266 perform special functions at bootup. GPIO15, when HIGH, makes the ESP8266 boot from an SD card.

You can read more about the special functions of the pins here.

The solution? Don't use GPIO 0, 2 or 15 for things that can affect the boot sequence.


Driver shield providing 24+ pins at 100mA (for Mega 2560) Do any shields (or similar boards) exist to let the Mega 2560 (or Due) output a full 100mA per pin on at least 24 pins, in a digital on/off fashion? I know there is a motor shield, but it looks to have only a handful of outputs. It seems very common that people need to output higher current than the MCU can provide safely (if at all), but there do not appear to be any shields for this. Of course individual transistors are fine for a few outputs, and some chips can do up to 8, but what about the rest of us who want to use all those nice pins on the Mega, Due, or similar but who need more power?

You can:

use a driver chip, e.g. ULN2803 which gives you 8 outputs of up to somewhat 500mA from 8 digital pins
use a serially addressible power+logic chip, such as TPIC6A595NE which gives you 8 outputs, each can drive 350mA, and has a built-in short circuit protection. You can cascade these, 3 chips give 24 outputs, and need only three pins to drive all 24 (or more if you use more chips) outputs.
There are 24 output devices, however not in this current range. 24 output devices are usually i2c or spi based led controllers - some of them gives you goodies like rock solid hardware PWM on all 24 ports - but none of them gives you 100mA output.


graph of a function Arduino I am making a temperature circuit with arduino.
is there any way to plot the value of the temperature in a graph using arduino?
thank you very much in advance

Yes you can use the Plot menu command in the new Arduino 1.6.6 or you can use the Visual Micro debugger to create graphs in Visual Studio


Error running FirebaseDemo on nodeMCU So I followed the guide on GitHub to run this demo which compiles and runs. It does warn of some deprecations and such in the firebase libraries :

  In member function 'const String& FirebaseArduino::error()'  warning:
  returning reference to temporary [-Wreturn-local-addr]
       return error_.message().c_str();

It is failing to update my firebase database and the firebase error message is not being displayed, seems to be because of the above error. But this does make it complicated to debug...

Can someone please help me get around this?

Appreciate any feedback or pro tips :)

UPDATE

So found an issue on GitHub that solved connecting to the database. Fingerprint update apparently... https://github.com/FirebaseExtended/firebase-arduino/issues/369 but still would like to solve the firebase library error so that everyone can get legible error messages back when using it.

It does warn of some deprecations and such in the firebase libraries :
In member function 'const String& FirebaseArduino::error()' warning: returning reference to temporary [-Wreturn-local-addr] return error_.message().c_str();

i also get some depreciation like
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'bool FirebaseObject::isNullString(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:67:57: warning: 'const char* ArduinoJson::Internals::JsonVariantCasts<TImpl>::asString() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:28): use as<char*>() instead [-Wdeprecated-declarations]
   return variant.is<const char *>() && variant.asString() == NULL;
                                                         ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'ArduinoJson::JsonVariant FirebaseObject::getJsonVariant(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:87:26: warning: 'ArduinoJson::JsonObject& ArduinoJson::Internals::JsonVariantCasts<TImpl>::asObject() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:23): use as<JsonObject>() instead [-Wdeprecated-declarations]
     json = json.asObject().get<JsonVariant>(start);
                          ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/throw_out_of_range.cpp:6:28: warning: unused parameter 'str' [-Wunused-parameter]
 void __attribute__((weak)) __throw_out_of_range(const char* str) {
                            ^
In file included from /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:1:0:
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.h:82:79: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
   const void AddToJson(const FirebaseCloudMessage& message, JsonObject& json) const;
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:80:60: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
     const FirebaseCloudMessage& message, JsonObject& json) const {
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'int FirebaseRequest::sendRequest(const string&, const string&, char*, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:76:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }
 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'void FirebaseStream::startStreaming(const string&, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:89:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   analyzeError("STREAM", status, path_with_auth);
                                                ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'String FirebaseArduino::push(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:79: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:7: warning: unused variable 'status' [-Wunused-variable]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
       ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::set(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:94:65: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "PUT", path.c_str(), buf);
                                                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::getRequest(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:101:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "GET", path.c_str());
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual void FirebaseArduino::remove(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:147:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "DELETE", path.c_str());
                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual const String& FirebaseArduino::error()':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:201:33: warning: returning reference to temporary [-Wreturn-local-addr]
   return error_.message().c_str();
                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:47:50: warning: 'bool HTTPClient::begin(String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:156) [-Wdeprecated-declarations]
     http_.begin(url.c_str(), kFirebaseFingerprint);
                                                  ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:51:80: warning: 'bool HTTPClient::begin(String, uint16_t, String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:157) [-Wdeprecated-declarations]
     http_.begin(host.c_str(), kFirebasePort, path.c_str(), kFirebaseFingerprint);
                                                                                ^
Compiling library "ESP8266HTTPClient"

to fixed that, go to Preferences in Compiler Warnings choose as Default. it ignored all warning in depreciation, don't forget to update your library to get Firebase Fingerprint has changed on 2 Aug 2018.
Uploaded your sketch again, your should be get data like


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

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);


Arduino Yun V2.0.1 can't configure WiFi I can't configure at 192.168.240.1. It's giving me this message multiple times:

1- AJAX/HAR Error:0 has not allowed Arduino Configuration Wizard to complete.

Details of my board:

Arduino Yun V2.0.1 anders evinrud

I have this error too when I typed a wrong password to connect to the green 'osjs' interface.
have you changed the password of your board ?
have you tried the 2 possible passwords ( "arduino" or "doghunter" ) depends on the image installed ?
hacve you cleared your browser cache / test with another browser ?


Use only one pin as serial output/input with arduino I'm looking for a way to use Arduino UNO's as serial outputs or input "individually", I don want to have an RX pin for each TX pin. I know the library SoftwareSerial, but I'm not sure if it is posible to achieve my objective with it.

I have also read that in this library "If using multiple software serial ports, only one can receive data at a time". Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?

Thank you for your time.

AVR304, "Half Duplex Interrupt Driven Software UART on tinyAVR and megaAVR devices" describes how to implement a half-duplex software UART using 2 pins. Simply omit the half of the UART that you do not need in your own implementation.


Echo from device not matching input I'm writing a char array to a device with an arduino mega that should be giving me an echo back, instead, I'm getting an array back with different chars that correspond to my sent function, but not in a way I can figure out. for example {1,6,250,0,91,233,252} returns the array {127,62,1,146,90,0,0}
As 1 is always returning 127, I'm guessing it has something to to with how I'm casting my received data, but after messing with it for a few hours, I can't seem to get it to cast correctly.
Main Function
gets destination address and data, echos back if requested
calls CRC(this works fine) and SkRead(the problem area)
void Create_Message(int Address, int Data, bool echo)
{
  lcd.setCursor(0,1);
  lcd.print(Address);
  lcd.print(" ");
  lcd.print(Data);
  Address--;
  byte SvAdd = 1;
  byte FuCode = 6;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
  uint16_t crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
  byte CrcHi = crc >> 8;
  byte CrcLo = crc & 0xFF;
  /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
  * to
  *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
  */
  unsigned char cmd[8]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcLo,CrcHi};
  for (int i=0; i< 8; i++)
  {
  Serial1.write(cmd[i]);   // Send string
  if(echo){Serial.print(cmd[i]);Serial.print('.');}
  }
  if(echo){Serial.println();}
  if (SkRead(echo) == cmd)
  {
  Serial.print(Address);
  Serial.print('\t');
  Serial.println(Data);
  }
  //clear line
}

CRC
(works fine, just wanted to show full code)
/*---Create CRC Function---*/
uint16_t CRC(byte AdDa[], int Size )
{
  uint16_t crc16 = 0xFFFF;
  int pos = 0;
  int i = 0;
  /*Write CRC*/
  for (pos = 0; pos < Size; pos++)
  {
    crc16 ^= AdDa[pos];          // XOR byte into least sig. byte of crc
    for (i = 8; i!= 0; i--) // Loop over each bit
    {
      if ((crc16 & 0x0001) != 0)        // If the LSB is set
      {
        crc16 >>= 1;                      // Shift right and XOR 0xA001
        crc16 ^= 0xA001;
      }
      else
      {
        crc16 >>= 1;                      // Shift right
      }
    }
  }
  /*Note, this number has low and high bytes swapped,
  so use it accordingly (or swap bytes)*/
  return crc16;
}

SkRead
This is my problem area, I'm sure the data is being sent and read correctly, but one of my assignments is throwing it off so the received echo is not received in a way that matches what is sent.
unsigned char SkRead(bool echo)
{
  digitalWrite(Pin13LED, HIGH);  // Show activity
  outputstring = "";
  unsigned long bide=millis()+2000;
  byte inChar;
  while(Serial1.available()<8 && bide>millis()){}
  while(Serial1.available())
  {
    inChar = (byte)Serial1.read();
    outputstring += (char)inChar;
  }
  //Serial.println(outputstring);
  digitalWrite(Pin13LED, LOW);  // Show activity
  int charl = outputstring.length() + 1;
  unsigned char outputschar[charl];
  outputstring.toCharArray(outputschar,charl);
  if (echo)
  {
    for (int i=0; i< charl; i++)
    {
     Serial.print(outputschar[i]);
     Serial.print('.');
    }
    Serial.println();
  }
  return outputschar;
}

I don't know where to start.

You did not provide a full sketch. There is, for example, no Serial.begin1() in sight.
You did not provide enough information about the device. If you don't want to tell us what it is, then give an indication of its age. In the 1980's it was common to have 7E1 format (7 data bits, even parity, 1 stop bit).
You have to be sure what the baudrate is. To detect a wrong baudrate, you need a oscilloscope or logic analyzer. When the device has a processor and the baudrate is derived from it's clock, the baudrate could be different from the specified baudrate by a few percentage. That is already a problem with the Arduino.
It could be a problem with inverse voltage levels. What does the device use as idle and as active level ? The Arduino Mega uses +5V at the TX pin when idle, and low is active. That means that the TX pin is normally high, and the first low pulse is the start bit.
The device could return an error code instead of an echo.
Your SkRead function can be improved:
Using a String object to collect the incoming data and after that converting the String object to a unsigned char array to use it, is not the most elegant solution. You could just use a unsigned char array to read the incoming data.
It is not okay to add something to the millis value. That is a problem when millis does a rollover (after 50 days or so).
Normally a character is read as soon as it is available. You wait until 8 characters are in a buffer. No one else does that.

To solve this puzzle you need more information. Try to capture the RX and TX signals with a oscilloscope or logic analyzer. Or else try to write a very small sketch that creates the problem.

My best guess is that it is not your sketch, but perhaps a combination of inverse levels, parity and baudrate.

[ADDED]
After writing down the bits over the serial bus, it might indeed be inverse voltage levels and maybe something with 7 bits or parity. That would also explain the last bytes to be 255. Those 255 are not valid data.


What is causing my Uno to wake up? NOTE: this code was working perfectly fine in another program.

I have a simple piece of code that puts the Arduino to sleep. When it is finished and intergrated into my project, it will only wake the processor up when an alarm from an external RTC triggers one of the hardware interrupts.

#include <avr/sleep.h>
#include <avr/power.h>

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

void loop(){
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);        //deep sleep mode
    Serial.println("Device is going to sleep...");
    sleep_enable();        //put device to sleep

    sleep_disable();        //Device restarts here on wake
    Serial.println("Device is awake...");
    delay(1000);        //to slow down serial output
}

In theory, the program should shut down the processor indefinitely because there is nothing available to wake it up.

However, the device continues waking itself up immediately after shutting down.

I have tried attaching the interrupts hoping it was some kind of anomalous watch-dog function. I have tried tying the interrupt pins to +5V and also (in a separate attempt) to GND. Nothing has helped.

What is causing the processor (and/or program) to constantly wake itself up?

sleep_enable() allows the MCU to sleep, but it does not cause it to sleep. Call sleep_cpu() after enabling.


using esp8266 feather to burn bootloader on redboard Is it possible to burn the bootloader of an arduino redboard using an esp8266 feather? whenever i connect my redboard to my pc the ports list on the ide would just be greyed out. I've looked around online and tried everything I found except burning the bootloader since I didnt have a spare arduino, atmega or a programmer. I have an EPS8266 feather though.

If anyone know whether or not this is possible to do and could walk me through on how to do it if it was.

The RedBoard has an FT232 chip for the USB interface.  Flashing the bootloader on the main MCU will have no effect at all on your problem.

While, yes, it is technically possible to use the ESP8266, it's not easy and, since it won't cure your problem of a greyed out port option, isn't worth the effort to try and do it.

Instead, you should be looking at things like your USB ports, USB cables, FT232 drivers, etc on your computer.


Swap two arrays (using pointers, not copy) I've got two arrays, defined as:

uint8_t array1[10];
uint8_t array2[10];

I'd like to swap the arrays (actually the pointers to each array) using code like this:

uint8_t *tmp = array1;
array1 = array2;
array2 = tmp;

However, I keep getting errors like:

invalid array assignment

for the last two lines. I don't recall this being such a problem in traditional C++. I've tried all sorts of casting to no avail. Is there something I'm missing?

I can get the code to run properly if I switch the declarations for the arrays to use new and have them just be more-or-less pointers rather than arrays, but I'd rather not have to do that:

uint8_t *array1 = new uint8_t[10];
uint8_t *array2 = new uint8_t[10];

Code is running on an ARM-based SAMD51 (Cortex M4 processor).

Thanks for any tips!

Figured it out. Though using new works, I wanted to keep the buffers out of the heap. The following declarations work with the swap code:

uint8_t a1[10];
uint8_t a2[10];
uint8_t *array1 = a1;
uint8_t *array2 = a2;

uint8_t *tmp = array1;
array1 = array2;
array2 = tmp;


Does NodeMCU have some protection against wrong connections that could kill a computer USB? I know some computer USB could handle some bad connection (by blocking the port, which need to reboot the computer). But I wonder if a NodeMCU 8266 offers some protection.

Most USB ports are shut down when an over-current event is detected.

There is nothing in a NodeMCU that can prevent an over-current event in the case of things like short circuits. The 5V (or VIN on some versions) pin is directly (or sometimes via a single diode) connected to the 5V pin of the USB. Cause a short on the 5V pin and you cause a short on the USB.

Protection is designed to be at the port level not the device level so that devices don't have to be forced to comply to protection "standards" that would drive up costs and result in devices being non-compliant and risk damaging the computer.

If you find that you are often causing shorts on the 5V pin and killing (albeit temporarily) your USB ports you should change your working practices.

It can be good to always connect your devices to an external powered USB hub instead of directly to your computer. That way if you kill a port you can just unplug the hub and plug it back in again to reset all the ports. No need to reboot your computer.

Cheap hubs often just have a simple PTC fuse instead of proper over-current protection which can actually be more useful for device developers since the port won't be disabled, just the external power shut off.

Most Arduino boards do incorporate a PTC fuse in the USB power circuitry, but NodeMCU and similar boards don't.


Why do I get “ stray '#' in program ” error? I am making an Arduino program with SIM800L module and would like to check credit status of the SIM card.
When I manually enter the command: AT+CUSD=1,"*123#" into Serial Monitor, it works fine.

But in the Arduino (1.8.7) I am receiving an error
      stray  "#" in program

when compiling this line of sketch:
      SIM800.print("AT+CUSD=1,"*123#"\r");

I am not experienced enough to fix this problem.
Could somebody help me, please?

Thank you.
Marko

Use the escape backslash to get a double quote in a text. See: https://en.cppreference.com/w/cpp/language/escape

Is the *123$ between double quotes?

Serial.println("Hello");
Serial.println("I said: Hello to you");
Serial.println("I said: \"Hello\" to you");
Serial.println("AT+CUSD=1,\"*123#\"\r");
Serial.println("AT+CUSD=1,\"*123#\"");

I think the carriage return \r at the end is not needed when the println is used. The println adds a linefeed \n by the way.


Arduino controlled by USB gamepad I want to control my Arduino with USB gamepad. I know that exists library for USB keyboard for Arduino but I don't know any library for usb gamepad. I have PS3 styled gamepad. I dont want to use shield.

Any solution or help?

A USB host shield or mini board depending on your Arduino board should work.

https://github.com/felis/USB_Host_Shield_2.0

https://www.circuitsathome.com/usb-host-shield-hardware-manual/


How do I join two RGB ledPanel 32x64 in order to get one 64x64? I'm making a project to make a pixelArt of 64x64 using two 64x32 RGB ledMatrix and Arduino MEGA.
This is the RGB Panel I am using.
I use ADAFruit and RGBMatrixPanel libraries in my Arduino Code and if I connect the Arduino pins to the RGB panel it works, but the problem is when I try to connect the output of the first panel to the input of the second, I saw the "same image duplicated" but with different brightness, and if I change the length of the panel seems to print random LEDs.
I know that Adafruit is thought to get a screen with max of height of 32, but I don't care, because for my purpose you can assign each pixel programmatically in order to print the proper image.
I followed this guide in order to make the connection with a panel of 64x32.
I think that I have to change my code and also my physical connections, but I don't know how, can anyone help me?
Other option that I thought was create another matrix2 instance at the same code using different PINS, but this is very weird.
This is the current connections: (I have a power supply of 5v - 10A)

This is the result that I have: (duplicated in both screens with a brighness/weird shadow in the second)

And this is the final result that I'm looking for: (this is made with two Arduino Megas)

Thanks in advance!

First off, connecting the 2nd panel to the same output pins as the first one, you are simply sending same data to the 2nd panel, which is why you get the duplicate visuals. I'm guessing you are sending power that same way, which is why you are seeing the brightness dim.

Secondly, it's hard to read on the pics in the AliExpress listing, but the Sparkfun site had a better image, which shows an "Output" connection on the back of the panels.  You need to daisy chain the 2nd panel to the first panel through this "Output" connection. This should prevent you from having to create a 2nd matrix2 and use a 2nd set of pins.

Third, having a 2nd set of pins and controlling the 2nd LED matrix can make updating the image faster. It depends on your library as well as how the LED matrix is made, so it really depends on those factors, but some LED systems are designed so there is a maximum amount of pixels that can be displayed before there's a noticeable delay in LED updated. With this amount of LED pixels, you're probably fine, but if you want fast updates and expect to expand your matrix in the future, you might want to consider driving the panels separately. I'm not saying you have to now, but if you're seeing lag, this might be a good option.


What purpose does the yellow and green LEDs have on the Arduino? I have wired up a small project with a shift register (see below), but depending on how I put the 74HC595 IC (8-bit shift register with 3-state output register), the green and yellow LEDs of the Arduino stop shining.

What are these LEDs for? Do they tell something about a possible damage of the IC/short circuit in the setup?

The green LED is marked with ON, and it indicates that the Arduino has power.

The yellow LED is marked L and is just connected to pin 13. So when you set pin 13 to HIGH the LED lights up. You can however still use pin 13 for other things.

When the green LED stops shining you most likely have a short somewhere. As the short will drain all power away, so the Arduino has no power left to light the LED(s).


Cost-effective storage for prototyping In my project I need to add some storage space and I don't want to use an SD card, because in the "final product" the user shouldn't be able to access the data on their own.

So I was considering the options here http://playground.arduino.cc/Main/InterfacingWithHardware#Storage but many of the technologies are either outdated, for example as reads here ADESTO is discontinuing production of dataflash, or they give too little memory, like the I2C EEPROM (which is 128KByte per chip and I would rather not go through the hassle of multiplexing lots of memory chips since I'd like to have 1MByte of storage at least), or are extremely overpriced and cannot be found on retail: some sites require you to buy 2000$ worth of chips or charge you 30$ for delivery, which kind of kills the fun of prototyping something.

I know I am being picky not wanting to use an SD for the prototype, but I would like to know if you ever faced this problem and how you solved it, or if you know some alternative solution which gives a good amount of memory (~1 or 2 MBytes at least) within reasonable costs.

You may not want to hear this, but the cheapest option would be an SD card, or a micro-SD card. You could solder it into place, thus making it quite hard for the end user to take it out and plug it into a reader.

Imagine you had this micro-SD card glued onto your board (making it hard to remove in the first place):

It isn't particularly obvious what it is, unless you recognize the shape. You could cover it with a blob of plastic to hide that. Then with the SPI wires soldered to the contacts, removing would be even harder.

That gives you gigabytes of storage, a file system, the works. And all for a few dollars.

A technically sophisticated user could probably prise it loose and get at the data (although if you used strong glue this could be quite hard) but they could also get at the contents of another storage chip too.


I fried my arduino. Can I upload code wirelessly? So, I'm a complete arduino newbie. I left a live wire close to my arduino and part of it burnt (underneath the USB output). The LED that indicates power still turns on when I plug it into my computer, and a simple LED circuit on my breadboard, when hooked up to the arduino, still works. The only thing that's wrong is that my computer doesn't recognize the Arduino serial port any more, so I can't upload any code onto it.

I also own a bluetooth HC-05 module. Is there any way I could upload code onto my Arduino wirelessly, using that? Or am I better off just buying a new one?

If the main MCU is still functioning fine then yes, sure you can.

The only caveat is that you may have to manually reset the Arduino at the right moment in order to enter the bootloader for programming.

Connect the bluetooth module to TX/RX/GND (TX->RX, RX->TX)
Configure the bluetooth module to work at the bootloader baud rate (115200 baud) - you may need to wire it to your PC to manage this part.
Connect a virtual COM port to it and program through that.
Press RESET just as it's about to run AVRDUDE in the IDE.


Where am I supposed to get an I2C BUFFER_LENGTH defined? I am using a BLE nano - as soon as I try to include I2Cdev.h and compile, I get this error:

Arduino\libraries\I2Cdev\I2Cdev.cpp:276:62: error: 'BUFFER_LENGTH' was not declared in this scope

How should I fix this? I imagine I can hard-code it in and guess around as to the value (32 seems common), but I think I am missing something else as far as it using the right libraries for the hardware, so how can I check/fix that if it is indeed the case?

BUFFER_LENGTH is set in I2Cdev.h depending on the target. BLE nano is not directly supported (what I can see).

Cheers!


Control laser diode from digital pin I have a 200mw laser module that came with a 3v 1A power supply. I want to control it from a digital pin on an arduino uno.
Can I use a simple voltage divider like this or is there some consideration to current I'd need to take into account? The laser module was quite expensive so I'm hesitant to try it out.

simulate this circuit – Schematic created using CircuitLab

Your solution does not work, mainly because GPIOs are not intended to source current higher than a few mA. If you want the laser diode to emit a reasonable amount of power, you need to drive it with a transistor. A MOSFET-based low-side-switch would probably be the easiest solution. But note that you still need to limit the current, e.g. by using a series resistor.
Even better would be to use a constant current driver (you can use any led driver with appropriate rating).
If the power supply that came with the laser diode is a constant current source, it might be possible to switch its output directly (without resistor), but that depends on how it behaves when it is open-circuited.


Specific noise while using arduino ADC in free running mode To make an oscilloscope in matlab environment, for data acquisition on arduino side, when inbuilt analogRead() is used, it's working fine, but with very low sampling rate, that aliasing is clearly observed. That too, non-uniform sampling. Thus listing out the drawbacks:

Very slow data rate, even if, sent with 115200 baudrate,
Aliasing
Non-uniform sampling

Thus, to overcome above, ADC in free running mode was used, with 16 as prescaling factor, thus 76.9KHz sampling rate (counting each ADC as 13 clock cycles). Thus, data is uniformly sampled now. Also it is quite fast, because of sampling, and is observed. The only problem now exists is, output has a specific noise. The data being sampled is 50Hz sinusoidal current waveform by current sensor ACS712. It overlays instantaneous current waveform over a bias of 2.5V. Thus, when signal is not present, a constant voltage of 2.5V is observed, thus, 512, because of mapping to 255 range.. 127. But in the case of free running mode, along with 127, 191, 63 only are observed. And it can also be seen that nearly 127 = 63*2, and 191 = 63*3. And when current waveform exists, it's highly distorted, but perceptible that it's not the previous signal of just 127, 191, 63. In the below plot, current is passed since 33.5sec.

I am unable to understand this, structured noise. What may be the reason ? I have once read, last two MSB bits get noisy at this sampling rate, but then how would 127, jump to 191. Why is 63 getting added, subtracted at each instant ?
I understand the reason for non-uniform sampling now is because of Serial.print(), whose interrupts are obstructing the ADC interrupts, but don't understand the reason behind the noise observed.

Following is the code uploaded in arduino. Serial data is read from matlab by fread() function.

long t1=0,ts1=0,ts2=0;
int aval=0, val=0;

void setup() {

 TIMSK0 = 0x00;           // disable timer (causes anoying interrupts)
 DIDR0 = 0x3F;            // digital inputs disabled
 ADMUX = 0x40;            // measuring on ADC0, right adjust, AREF reference
 ADCSRA = 0xAC;           // AD-converter on, interrupt enabled, prescaler = 16
 ADCSRB = 0x00;           // AD channels MUX on, free running mode
 bitWrite(ADCSRA, 6, 1);  // Start the conversion by setting bit 6 (=ADSC) in ADCSRA
 sei();
 Serial.begin(115200);
 t1=millis();
 }

ISR(ADC_vect)
{
 aval = ADCL;
 aval += ADCH << 8;
}

void loop() {
val = map(aval, 0, 1023, 0, 255);
Serial.write(val);
delay(10);
}

If you use an ISR to retrieve the ADC result, you will need to protect the read of the variable. An interrupt may occur when reading aval in the loop(), as this is a 16-bit value and the read requires several instructions. This may give corrupt values.

void loop() {
  noInterrupts();
    val = aval;
  interrupts();
  val = map(val, 0, 1023, 0, 255);
  Serial.write(val);
  delay(10);
}

Cheers!


How to encode resistance change (reed) for Arduino? I have a water counter which switches reed on each 10 liters of water. I would like to count these values with Arduino.

I wrote a program which counts changes from analog input and connected counter between +5V and analog input. It counts well but I am doubt I connected correctly. Because when reed is opened, then analog input is connected to nothing, while it should be connected to GND.

How to implement correct conversion from reed to analog or digital input?

A reed switch is just a button. Treat it as such. Either connect it between a digital input and ground, with a pull-up resistor (internal one would do) or between a digital input and +5V and use a pull-down resistor.


Is there any way to connect my old phone camera with an arduino? I have an esp8266 wifi module, arduino uno and an old mobile. I was wondering if there is any way by which i could remove the camera from the mobile and connect it with my arduino in order to view video captured by the camera.
Is this possible by the hardware which i currently have? Or i will have to buy more hardware?
Please let me know if more information is required also give the link of helpful articles.

Is there any way to connect my old phone camera with an arduino?

Yes, but it may be a huge amount of work requiring expensive equipment and skills that take decades to acquire.

See Mike's Electric - Interfacing a cheap phone camera module to a PIC32 microcontroller. which is a great video and will give you an idea of what is involved. Note that he's using a 32-bit microcontroller with relatively large RAM on the chip. You might need to use a 32-bit Arduino (Due etc) not one of the 8-bit Arduinos (Uno etc).

Mike is the kind of person who could reverse-engineer a random camera module from an old phone but this isn't a project for a typical Arduino user like you or I.

Since these camera modules cost about $1, it is probably best to look for a camera breakout for Arduino that comes with documentation and software libraries.


How to set Delay on GSM shield? I bought a Gsm module recently(not official arduino shield) and i connect it to Arduino uno. The problem (I guess) is , i can't set delay properly, the terminal send it too fast that i missed it or too slow even i set its baud rate to 4800 (I have tried it with many baud from 4800-to-115200).

I uploaded the code to Git ,with this address.

More details: For example when i enter d in terminal it act like this message came up : +CMTI: "SM",3 and it want to save it but it miss plus at first of it and it save CMTI: "SM",3,

After that it perform this : AT+CMGR=3 the terminal show the message in half size : +CMGR: "REC UNREAD","+9*********2","H/E.3D/1","16/02/28,00:27:02+14" which totally missed body part.

The weird thing is when i put some println on the program it miss more characters , and second weird thing is it missed more character in second run or i push d again.

I have tried to change the delays but no success.How can i fix it ? any help would be appreciated.

Edit:

If i make it simpler, when i use these code i get half message :

#include <SoftwareSerial.h>
SoftwareSerial serialGPRS(7, 8);
void setup()
{
  Serial.begin(19200);
  serialGPRS.begin(19200);
}
void loop()
{
  serialGPRS.println("AT+CMGR=1");
  delay(1000);
  while(serialGPRS.available()!=0)
    Serial.write(serialGPRS.read());
}

like: +CMGR: "REC READ","+9*******",".H/E.3D/1

The SoftwareSerial receive buffer is getting filled up and discarding characters. You are not reading fast enough from the buffer. Adding Serial.println() will slow down your reading even more. The simplest solution to this is to increase the size of the SoftwareSerial buffer from its default size of 64 bytes to 256 bytes (or smaller, depending on what works for you).

On a Windows PC, go to C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial. Open SoftwareSerial.h and change the line:

#define _SS_MAX_RX_BUFF 64 // RX buffer size

to

#define _SS_MAX_RX_BUFF 256 // RX buffer size

Save the file and try your sketch again.


Why is one LED more luminous (brighter) than the other? Given that there is a circuit with two pins (12 and 10) from an Uno providing power to LEDs on two separate branches, why is the yellow LED dimmer than the green LED? (Please see below image.) To my understanding, the branches attach to GND in parallel, so the LEDs should be equally bright.

If it helps, the two branches are programmed so one LED is off when the other is on and vice versa, with a 1s interval between changing pin state. This isn't a PWM thing as using pin 8 instead of 10 makes no difference.

Just like men, all LEDs have been made different.

Practically, that means two different LEDs (one green and one yellow for instance) will have different brightnesses (more precisely, luminous intensities) when they are traversed by the same current (forward current).

LED luminous intensity is a function of the current that traverses it (among other factors).

If you want the same brightness for those 2 LEDs, then you'll have to:

Get both LEDs datasheets (should be a couple of A4 pages for each)
Find the luminous intensity/forward current function curve in each
Determine which brightness you want for both
Deduce the current for each
Calculate the resistor value to get that current for each

Then you will have to use two different resistors values in your wiring, based on calculations of step 5.

Simpler, you could just replace one of your 2 resistors with one small pot that you can use to tune brightness of the second LED until it fits brightness of the first one.

Be careful with pot manipulation though, as a 0 resistance would probably grill your LED (and potentially the Arduino pin it is wired to).


RCSwitch on Attiny85 I would like to use my Attiny85 as an remote controlled relay switch.
I have already tested the sketch on my Atmega328 and it worked.
Now I wanted to burn the sketch on my Attiny85 using ArduinoISP but I get the following error in the ArduinoIDE:

sketch_dec25a.ino: In function ‘void setup()’:
sketch_dec25a:13: error: ‘class RCSwitch’ has no member named ‘enableReceive’
sketch_dec25a.ino: In function ‘void loop()’:
sketch_dec25a:20: error: ‘class RCSwitch’ has no member named ‘available’
sketch_dec25a:21: error: ‘class RCSwitch’ has no member named ‘getReceivedValue’
sketch_dec25a:22: error: ‘class RCSwitch’ has no member named ‘getReceivedValue’
sketch_dec25a:25: error: ‘class RCSwitch’ has no member named ‘resetAvailable’

That's my code:

#include <SoftwareSerial.h>
#include <RCSwitch.h>

int RELAY_PIN = 2;

RCSwitch mySwitch = RCSwitch();
SoftwareSerial mySerial(1, 3); // RX, TX

void setup()
{
  pinMode(RELAY_PIN, OUTPUT);
  mySwitch.enableReceive(0);  // Receiver on inerrupt 0 => that is pin #2
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySwitch.available()) {
    Serial.println(mySwitch.getReceivedValue());
    if(mySwitch.getReceivedValue() == 1234567){
      digitalWrite(RELAY_PIN, HIGH);
    }
    mySwitch.resetAvailable();
  }
}

I am using these cores: https://code.google.com/p/arduino-tiny/

I am using the SoftwareSerial just for debugging.
Sorry for my bad english and thanks for your help!

The issue you face is that RCSwitch does not seem to support receive mode for ATtiny.

This is what you can find in RCSwitch.h:

// At least for the ATTiny X4/X5, receiving has to be disabled due to
// missing libm depencies (udivmodhi4)
#if defined( __AVR_ATtinyX5__ ) or defined ( __AVR_ATtinyX4__ )
#define RCSwitchDisableReceiving
#endif

Then all methods related to receptions are not defined in RCSwitch class for ATtiny MCUs:

#if not defined( RCSwitchDisableReceiving )
void enableReceive(int interrupt);
void enableReceive();
void disableReceive();
bool available();
void resetAvailable();

unsigned long getReceivedValue();
unsigned int getReceivedBitlength();
unsigned int getReceivedDelay();
unsigned int getReceivedProtocol();
unsigned int* getReceivedRawdata();
#endif

I am really not sure if there is a way to work around it, I have not looked at the code in RCSwitch.cpp.

Maybe you best option would be to find another RC library.

For instance, if you can use Infra-Red RC, then there are libraries out there that could work for ATtiny:

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


How to avoid odd naming rules for Arduino when writing a library? I'm building a small library that will be used and production and released open source. I'm paying a lot of attention to the "best practices" to make sure this code is reliable and easy to use. I also would also like to make this easy to edit. I'm having an issue with the naming scheme of the whole project.

There are a few Arduino naming quirks. If I have a sketch called mylib:

...I can't create a tab called mylib.cpp. However, I can create a file called mylib.h...
...The folder and main sketch file must be the same name as the folder it is in
...The sketch name (and folder) cannot contain any spaces.

Well, why are you creating a sketch for a library? The Arduino IDE won't open a .cpp file unless there's a sketch in that folder (and you have to open the .ino/.pde file in that folder). I'm trying to get this to work with the Arduino IDE so, if users need to edit the library, then can just open the file and go to the correct tab. If they use an external editor, they won't be able to compile it to see if there are any errors.

I'd ideally just do this structure:

my_lib
   |- my_lib.ino
   |- mylib.cpp
   |- mylib.h

However, a user might see that the folder is called my_lib and try including the file my_lib.h.

I think this is a major oversight in the Arduino IDE, but I need to have this work with the Arduino IDE. If it was just me working on this code, I might consider making the library directly in a project directory, but that isn't ideal. Is there anything that I can do to bypass this/make it easy for users to edit? Is there any "standard"/"convention" that defines how to do this?

Yep, the Arduino IDE kinda sucks eventually. There is no best practise really, as Arduino *.ino files aren't proper c / c++ anyway. I would hope that people who know how to write C++ classes (as opposed to Arduino) would be able to do it outside the IDE.

My suggestion would be to make the *.ino file a test file. That is, it runs a set of functions to check that the library behaves as desired. It could also include example code, so people who use the library know how to include it in their programs.

All that being said, time to fly Penguin...  Ditch the Arduino IDE and go with embedXcode or some other third party IDE template :P

(I just wanted to put a pic of a penguin)


Four temperature SHT31 sensors on ESP32 I have to read out the teperature and humidity of four independent SHT31 sensors with the help of an ESP32. Is there any prefered way to do this, since the only examples I can find online are only with one sensor. I have no access to the address pins of the sensors.
Thank you in advance for any help!

Yes, reading 4 SHT31 is possible with an ESP32.
If you have the analog version, readout is quite trivial: you simply use 8 analog inputs (2 for each) to read the signal.
If you have the digital version, which has an I2C interface, you need to control each sensor's address pin separately to select the specific sensor you want to read. Otherwise, there will be an address collision on the bus.


Arduinos using I2C reading integers wrong I have two Arduino unos, and I am using I2C to have them communicate with each other. The A4, A5, and GND of each Arduino is connected to the other. These are my functions:

On the sending Arduino:

void playNote(int pitch, int len, int location){
  Serial.println(String(String(location) + ":" + String(pitch) + "," + String(len) + "\n"));
  Wire.beginTransmission(location);
  Wire.write(pitch);
  Wire.write(len);
  Wire.endTransmission();
}

On the receiving Arduino:

void receiveEvent(int howMany){
  int pitch = Wire.read();
  int len = Wire.read();
  Serial.println("Pitch: " + String(pitch) + ", Length: " + String(len));
  playNote(pitch,len);
}

pitch always sends fine. When I send len as 150, it works and is received as 150. However, when len is sent as 300, it is received as 44. I cannot figure out why this is. Any help is appreciated.

wire.write(n) sends a single byte of value n

150 decimal = 96 Hex
300 decimal = 012C Hex ...so is 2 bytes, and is truncated to one byte of value 2C Hex.

2C Hex = 44 decimal

Send a single byte! Maximum value of a byte is 255 decimal

If you need to send multiple Len bytes, then you need to ascertain the number of bytes and send them individually.
In your code you send multiple bytes concatenated one after the other already ...you send Pitch followed by Len.
All you need to do is split Len into L1, L2 bytes first.

L1 = Len and xFF
Shift Len left or do other logical math to derive high byte, L2
Then send L1 and L2


How to send and receive unsigned int from one arduino to another arduino I'm trying to send some big numbers ranging from 0-62000 from one arduino to another via serial communication. I'm using unsigned int to hold values from 0 to 65535. And I'm using serial.print() and serial.write () to send numbers and serial.read()-'0' ; to receive numbers, but I'm unable to send and receive numbers above 9. Please help me.

Here is my code -

(For master)

const int Button_1 = 2;
unsigned int s =0;
void setup ()
{
   Serial.begin(115200) ;
   pinMode(Button_1,INPUT);
}
void loop()
{
  if (digitalRead(Button_1))
  {
     s = 61805;
     Serial.write(highByte(s)) ;
     Serial.write(lowByte(s));
     delay (5);
     s=0;
  }
  else
  {
     s = 60005;
     Serial.write(highByte(s)) ;
     Serial.write(lowByte(s));
     delay (5);
     s=0;
  }
}

(code for slave)

unsigned int upperByte, lowerByte, r=0,p=0;
void setup()
{
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT) ;
}
void loop ()
{
  If (Serial.available()>1)
  {
     upperByte = Serial.read();
     lowerByte = Serial.read();
  }
    r = (upperByte << 8) + lowerByte ;

   while (r==61805)
    {
        digitalWrite(LED_BUILTIN, HIGH) ;
    }
    while (r==60005)
    {
        digitalWrite(LED_BUILTIN, LOW) ;
    }
}

There are 2 ways to transmit data over serial: As byte data or in ASCII codes

Byte data: Everything, that is digitally stored or processed, is a series of 0s and 1s (bits) (electrically HIGH and LOW level), which are grouped into bytes (8 bits). So all data is just numbers at low level. The different datatypes (like numbers, Strings, executable code) are only reached by different interpretation of the byte data. You can take the number value of a byte directly. A byte like 0b00000101 for example is equivalent to the decimal value 5. So every byte can hold numbers between 0 and 255. (Google the binary system for more information). To hold bigger numbers, more bytes are put together. For example an integer consists of 2 bytes (16 bits) and can hold numbers between 0 and 65535. Note: These are the unsigned types. There are also signed types, that also can hold negative values. To understand this, google binary two's complement. To transmit such a bigger type over serial (which is byte based), you need to seperate the bytes of the type, send them consecutively and put them back together at the receiving side. You can do this with the following code:

unsigned int number = 54321;
Serial.write(number & 0xFF); //getting the lower byte of the number by using bitwise AND
Serial.write(number >> 8); // getting the high byte of the number by shifting the bits of the value 8 bits to the right

There are macros defined for Arduino, that can do this for you:

Serial.write(lowByte(number));
Serial.write(highByte(number));

In long term, you should learn, how the bitwise operators work. They are often needed. To put the data back together, you can look at CrossRoads answer.

Note: Serial.write() will send the byte data unchanged, while Serial.print() will convert the data to ASCII before sending. They are not equal.
ASCII Data: One interpretation of byte data is the ASCII standard (which is really old). Every byte value between 0 and 127 get's a corresponding ASCII value, meaning characters of the alphabet, digits, some special characters and some control characters. Numbers, that are transmitted as ASCII data, consist of multiple bytes, one for each digit. Thats, what you tried. Since the receiver has to seperate the different numbers to process them correctly, you have to mark the end of each number. This is commonly done with the newline character \n (optionally preceeded by the carriage return character \r, windows style). You add this at the end of every number. Serial has an extra function for that: Serial.println() will print the parameter as ASCII and will add a carriage return and newline character. On the receiving side you read the bytes into a buffer, until you see this delimiter sequence. After that, you process the whole buffer. If you want to know, how this Serial communication is done in code, look at the SerialEvent example, that comes with the Arduino IDE.

What way you use for transmitting data, is up to you and depends on your needs. If you only want to transmit number data, nothing else, you can use byte data. For complex or diverse data types, you can use the ASCII representation.

EDIT: I have described above, that - when using ASCII data - you can use one or more special characters to delimit one message/number. The receiver can then distinguish between the numbers in that row of digits. This is just some kind of protocol, that you impose on the data. You state, that every message is ended with this special character, much like very sentence in the english language is ended with a dot.

An important requirement is, that the special character does not occure inside of a message/number. So cannot use the character '1' as delimiter, since it will also occur inside of your numbers and you would chop the numbers in the wrong way.

The same principle can be imposed as protocol onto a byte stream. For example: You define, that every message/number will be ended with a special byte sequence, so that the receiver always can say: "This is the whole data of a number and not just a part of it." As above, the special byte sequence must not occur inside of the valid data. You wrote, that your numbers are always in the range of 0 to 62000. This means, that the value 65535 will never occur as valid data, thus you can use it as delimiter. In hex 65535 is written als 0xFFFF, which means, that you send two bytes with every bit set to 1 (each byte having a decimal value of 255). In your code everytime, that you are receiving something, you can check, if you have got 2 consecutive bytes with the value 255 (or written as 0xFF). If not, write the data into a buffer. If yes, that means, that you can process the data inside the buffer to a number.

For sending that would look like this:

Serial.write(lowByte(number));
Serial.write(highByte(number));
Serial.write(0xFF);
Serial.write(0xFF);

Note: This protocol will make sure, that sender and receiver cannot get out of sync. But still the first reading after a transmission problem (for example that a byte got send before the receiver was ready) will be garbage. That will happen very very rarely, so for most people it's not a problem. There are more principles, that you can use in your protocol to mitigate those problems, if you want to. For example you can define another special byte sequence as the start of a message/number. Or you can calculate a checksum of the number and only use messages/numbers, that fit to that checksum.


Ethernet Shield 2 data to PHP server doesn't work I am trying to send data via GET to my PHP server from my Ethernet Shield2.
This is part of my sketch:

char myserver[] = "www.myserver.com/";
if (client.connect(myserver, 80)) {
  Serial.print("Connected to ");
  Serial.println(myserver);
  client.print("GET /arduino/controller.php?");
  client.print("air_temp=");
  client.print(DS18B20_temperature);
  client.println(" HTTP/1.1");
  client.print("Host: ");
  client.println(myserver);
  client.println("Connection: close");
  client.println();
  client.println();
} else {
  // if you didn't get a connection to the server:
  Serial.println("Connection failed to Server");
}

The serial monitor displays "Connect to myserver.com" but my PHP code doesn't seem to receive the air_temp value from DS18B20_temperature. I checked this value and it's true.

However, when I try myserver.com/arduino/controller.php?air_temp=25 in my browser, the PHP code is running well.

What's going wrong with my code?

I just removed the line server.begin() and it's works !!!
Thanks.


Storing an array of function pointers I have some Arduino code that looks like:

char packet = ser.read();
switch(packet){
    case 'a':
         someobj.somefunc();
         break;
    case 'b':
         otherobj.otherfunc();
         break;
    ...
}

I've added a few large libraries that are now causing my sketch to exceed the Arduino Uno's memory. I've done all the usual tricks to reduce memory usage, like using F(), removing unused variables and functions, but I'm still 5% over the memory limit.

I tried commenting out various parts of my code to see what was taking up so much space, and I found removing this switch statement freed up a whopping 20% of memory.

Since it acts like glorified array index, I was wondering if it could in fact be replaced with an array of function pointers, with the packet variable serving as the array index. e.g.

uint packet = ser.read();
func_array[packet]();

Although the class instance types are arbitrary, the methods all return the same type and take no arguments.

How would you write an array of pointers to arbitrary class instance methods in Arduino C/C++?

This is not a direct answer to your question, as I have no such answer,
and I believe the answer you are seeking would be of no use to you.

The problem with your question is that your method of testing memory
usage is heavily flawed. By removing the switch statement, you most
likely have allowed the linker to remove lots of methods referenced by
it, leading to huge memory savings. Those savings do not mean the
culprit is the switch statement itself.

The correct way to test static memory usage is to use either
avr-objdump or avr-nm. You have to find where the IDE puts the
compiled elf file, then you can issue the command:

avr-nm --size-sort -Crtd my_program.elf

This will give you a list of all symbols in your program sorted by size.
Symbols of type 't', 'w' and 'd' (upper or lower case) eat flash.
Symbols of type 'd', 'b' and 'v' eat RAM.


send values from arduino uno to wemos d1 r1 I have a weather project in which I have to measure the temperature and humidity ( dht22 sensor ), the pressure and other things and then show them in a local web page ( usings wemos d1 r1 ) in either my phone or pc ( I have both Arduino uno and Wemos d1 r1 for this project )
I wanted to use only wemos d1 r1 since it works the same as arduino uno except it has an esp8266 Wi-Fi built-in while arduino uno doesn't have ,but as you may know it only has 1 analog pin while I need at least 3 or 4 analog pin so in my case i should connect the sensors with the arduino uno and measure the temperature, humidity etc .. and then send those values to the wemos d1 r1 which will show the results itself in a web page as I said eariler
It seems that there is a way to do that using I2C connection but I have read many articles talking about connecting arduino to another arduino using I2C connection but I don't know how to do that in my case ( Arduino uno and Wemos d1 r1 ) and if there is another way to send values please tell me

As I see it, the most straight-forward way to connect 2 Arduinos is using their built-in UART (aka Serial port, TX/RX pins) communication.
There are many tutorials on this on Google, and a similar explanation can be found in this question:
Serial communication arduino mega and D1 Wemos Mini
However, there is a slight difference.
Arduino Mega has built in more than 1 hardware serial ports (I can't recall now if it's full 3 ports, or just 2), what leave one port for debug purposes, and the other - for your communication.
In your case (Arduino Uno) - you have only one serial port, that if will be used for the inter-Arduinos communication - will not be available for debug/console messages.
The solution for this is adding a Software Serial port, also highly available in tutorials over the net, here is one example:
softwareserial between arduino uno and esp8266
Enjoy your project!


Diorama Controller Part 2 - Need More Outputs For background see my original post.  I've decided to not to use batteries and have it wired up with wall power.

I wish to use the Arduino Pro Mini 5V as the controller for my diorama project.  I have five completed buildings which will all have LEDs (with only two wired up so far).  The two currently wired buildings have multiple "zones/rooms" that can have its LEDs activated separately.

Building 1 is a saloon with rooms above.  It has a total of 7 zones/rooms.

Building 2 is a store with a doctor's office above and rooms in the back of each.  It has 4 rooms.

With this setup, I am able to use the software to simulate people coming and going within the rooms.  It's pretty neat.

However, I'm currently at 11 outputs out of the Mini.  I'm running out of pins.  How can I have more outputs?

I think I understood what you want. If you want to control more LED's with less pins, consider using a shift register. For example, sn74hc595 could increase your digital outputs drastically. It has 8 bits, so you can have 2^8 combinations of outputs with it! For example, 0000 0001 is something, and 0000 0010 is something else, and so on. Check it out! I hope this helps :)

https://learn.sparkfun.com/tutorials/shift-registers - Basic knowledge about shift registers
http://www.bc-robotics.com/datasheets/sn74hc595.pdf
Other shift registers are great as well


Sending code for error detection facing problem with error not able to compile code MY PROJECT CODE:

#include ESP8266WiFi.h
#include LiquidCrystal.h
#include FirebaseArduino.h>
#include HX711.h>
#define FIREBASE_HOST "iot-based-smart-dustbin.firebaseio.com"
#define FIREBASE_AUTH "ljIbV03K07rLwoHRKSaAxWzJNCb3Lh6buc76dkvb"
#define WIFI_SSID "AndroidAP"
#define WIFI_PASSWORD "ashu1234"
char c; //ESP
String data   = "";  //ESP
#define DOUT  15
#define CLK  13
#define IR1 14
#define IR2 12
HX711 scale(DOUT, CLK); // Init of library
float calibration_factor = -96650; //-106600 worked for 3-40Kg max scale setup
const int rs = 16, en = 5, d4 = 4, d5 = 0, d6 = 2, d7 = 10;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup()
{
   Serial.begin(9600);
   pinMode(IR1,INPUT);
  pinMode(IR2, INPUT);
  pinMode(DOUT, INPUT);
  pinMode(CLK, OUTPUT);
  lcd.begin(16, 2);     // Print a message to the LCD.
  lcd.print("WELCOME");
  delay(2000);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
//  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED)
    {
  //    Serial.print(".");
      delay(500);
    }
//  Serial.println();
//  Serial.print("connected: ");
//  Serial.println(WiFi.localIP());
  scale.set_scale();
  scale.tare(); //Reset the scale to
}
void loop()
{
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  float a=scale.get_units();   // a Variable to take weight values at input
  lcd.clear();
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.setFloat("Weight", a);  //to set value in firebase // value on a sent to weight variable
  if (digitalRead(IR1)==HIGH)
  {
    Firebase.setFloat("IR1", HIGH);
    lcd.setCursor(0, 0);
    lcd.print("Location 1:High");
  }
   if (digitalRead(IR1)==LOW)
  {
    Firebase.setFloat("IR1", LOW);
    lcd.setCursor(0, 0);   //column, Row
    lcd.print("Location 1: Low");
  }
   if (digitalRead(IR2)==HIGH)
  {
    Firebase.setFloat("IR2", HIGH);
    lcd.setCursor(0, 1);
    lcd.print("Location 2:High");
  }
   if (digitalRead(IR2)==LOW)
  {
    Firebase.setFloat("IR2", LOW);
    lcd.setCursor(0, 1);
    lcd.print("Location 2: Low");
  }
  delay(2000);
  lcd.clear();
  if (a>=4)
  {
    lcd.setCursor(0, 0);
    lcd.print("Weight: High");
  }
   if (a<4)
  {
    lcd.setCursor(0, 0);
    lcd.print("Weight: Low");
  }
 delay(2000);
}
void send_msg_1()
{
  Serial.println("AT+CMGF=1");// for GSM module in TEXT mode
  delay(1000);
  Serial.println("AT+CMGS=\"+9921526975\"\r");// Phone number (change)
  delay(1000);
  Serial.println("Dustbin at Location 1 is full");// Message body (change as per requirement)
  delay(1000);
  Serial.println((char)26);// send message
  delay(1000);
}

ERRORS I am Getting while compiling as follows:

sketch_jul18a:34:22: error: no matching function for call to 'HX711::HX711(int, int)'
 HX711 scale(DOUT, CLK); // Init of library
                      ^
C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:34:22: note: candidates are:
In file included from C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:23:0:
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note: HX711::HX711()
   HX711();
   ^
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note:   candidate expects 0 arguments, 2 provided
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note: constexpr HX711::HX711(const HX711&)
 class HX711
       ^
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note:   candidate expects 1 argument, 2 provided
exit status 1
no matching function for call to 'HX711::HX711(int, int)'

Please help me to solve this problem. Too much struggling...

Probably the main problem is already in the first lines:

#include ESP8266WiFi.h
#include LiquidCrystal.h
#include FirebaseArduino.h>
#include HX711.h>

You should use the correct formatting:

#include "ESP8266WiFi.h"
#include "LiquidCrystal.h"
#include "FirebaseArduino.h"
#include "HX711.h"

Also, HX711 does not have a constructor with arguments, so instead of

HX711 scale(DOUT, CLK);

uese

HX711 scale;

and in Setup:

scale.begin(DOUT, CLK);

You probably have the code meant for a different library.

See HX711_full_example. Or use the code belonging to your used HX711 library.


Porting SH1106 Oled Driver - 128 x 64 / 128 x 32 Screen is garbled but partially responsive I'm porting the SH1106 driver to netmf and have found several libraries that more or less accomplish the same thing. A few were much easier to understand and had less abstraction so I followed those.

I've tried the U8glib with my arduino and it works just fine. The ported display driver yields these results:

inverted:

What you're looking at is the screen right after the initialization and attempting to draw a filled circle. You can see the bottom of the circle at the top of the screen. Somehow the origin or page is shifted, but I don't fully understand what's going on. I can send the invert display command and that works as well and turn the display on and off. My initialization code is this:

public void init()
{
    resetPin.Write(true);
    Thread.Sleep(1); // VDD (3.3V) goes high at start,
    resetPin.Write(false); // bring reset low
    Thread.Sleep(10); // wait 10ms
    resetPin.Write(true); // bring out of reset

    dcPin.Write(DisplayCommand);

    SendCommandB(0xAE);    /*display off*/

    SendCommandB(0x02);    /*set lower column address*/
    SendCommandB(0x10);    /*set higher column address*/

    SendCommandB(0x41);//0x40);    /*set display start line*/
    SendCommandB(0xB0);    /*set page address*/
    SendCommandB(0x81);    /*contract control*/
    SendCommandB(0x80);//contrast);    /*128*/
    SendCommandB(0xA1);    /*set segment remap*/
    SendCommandB(0xA6);//invertSetting);    /*normal / reverse*/
    SendCommandB(0xA8);    /*multiplex ratio*/
    SendCommandB(0x3F);    /*duty = 1/32*/
    SendCommandB(0xAD);    /*set charge pump enable*/
    SendCommandB(0x8B);     /*external VCC   */
    SendCommandB(0x30);    // | Vpp);    /*0X30---0X33  set VPP   9V liangdu!!!!*/
    SendCommandB(0xC8);    /*Com scan direction*/
    SendCommandB(0xD3);    /*set display offset*/
    SendCommandB(0x00);   /*   0x20  */
    SendCommandB(0xD5);    /*set osc division*/
    SendCommandB(0x80);
    SendCommandB(0xD9);    /*set pre-charge period*/
    SendCommandB(0x1F);    /*0x22*/
    SendCommandB(0xDA);    /*set COM pins*/
    SendCommandB(0x12);
    SendCommandB(0xDB);    /*set vcomh*/
    SendCommandB(0x40);
    SendCommandB(0xAF);    /*display ON*/

    // Switch to 'data' mode
    dcPin.Write(Data);
    this.ClearScreen();
    this.Refresh();

}

I have two methods to "refreshing"

public virtual void Refresh()
        {
            Spi.Write(displayBuffer);
        }

    /// <summary>
    /// Send buffer to display
    /// </summary>

public void Display()
        {
            //set column address
            dcPin.Write(DisplayCommand);
            SendCommandB(0x21);
            SendCommandB(0);
            SendCommandB((byte)(Width - 1));

            //set page address
            SendCommandB(0x22);
            SendCommandB(0);
            SendCommandB((byte)(_pages - 1));
            dcPin.Write(Data);

            //Spi.Write(displayBuffer);

            for (ushort i = 0; i < displayBuffer.Length; i = (ushort)(i + 16))
            {
                //Spi.Write(displayBuffer);
                SendArray(displayBuffer, i, (ushort)(i + 16));
            }
        }

At this point I'm a little lost. My hunch is something to do with paging and or display RAM. I'm looking for some insight here on how to fix this as I know there's a lot of experience here with these displays. Thanks!

While your initialization routine looks fine to me (comparing to the datasheet and as evidenced by the fact the display turns on), what doesn't look right is your drawing routine:

//set column address
dcPin.Write(DisplayCommand);
SendCommandB(0x21);
SendCommandB(0);
SendCommandB((byte)(Width - 1));

//set page address
SendCommandB(0x22);
SendCommandB(0);
SendCommandB((byte)(_pages - 1));

The commands 0x21 and 0x22 don't correspond to any commands I can see in the datasheet.  They look more like commands more commonly seen with ILIxxxx or SSDxxxx screens to create an "addressable window" from 0,0 to Width-1, _pages-1.

Instead you should be using the same commands you used in the setup routine to set the current col / page coordinate in RAM to write to.

Commands (0x00 | (col & 0x0F)) and (0x10 | (col >> 4)) set the column position, and (0xB0 | (page & 0x0F)) set the page number.

You then write all 128 bytes for the current page before moving on to the next page.  This means you will have to do it a page at a time, something like:

for (ushort page = 0; page < 4; page++) {

    // Set the current RAM pointer to the start of the currently
    // selected page.
    dcPin.Write(DisplayCommand);
    sendCommandB(0x00); // Set column number 0 (low nibble)
    sendCommandB(0x10); // Set column number 0 (high nibble)
    sendCommandB(0xB0 | (page & 0x0F)); // Set page number

    // Send a single page (128 bytes) of data.
    // Without knowing the rest of your program I don't know the right
    // data sending routines to use, so I made them up. Change it to
    // do it how your program expects.  Maybe with your SendArray
    // function.

    dcPin.Write(DisplayData);
    for (ushort col = 0; col < 128; col++) {
        sendDataB(displayBuffer[page * 128 + col]);
    }
}

Note that this method is very similar to how the KS0108 GLCD drivers work.  Each byte of the page represents 8 pixels on the screen so the screen, at 32 pixels high, is split into 4 pages, where each page is 8 pixels, or one byte, high.

The effect you are currently seeing is because you are never changing the current page number (0) so you are always writing your data to the first page.  This loops around multiple times, so you end up writing all 4 pages to the same strip of the display ending up with the last page being displayed, which is the last 8 lines of your display data.  The rest of the display is never being touched and just contains whatever random data was in the RAM at power-on.


Can I power up my Arduino and MotorShield with four AA batteries? can I power up my Arduino UNO with four AA batteries? It's about 6V, will my arduino burn? And, if I power my Arduino, I have to power my Motor Shield too or not?

I want to make line follower. I have to know what I have to power up. I dont know, how many battery holders I need. I have: Arduino UNO, motor shield, two 6V DC motors

You won't damage the Arduino if you remove the power to the motors as even though you're using the same power supply to power the motots and Arduino (4 x 1.5 - 6V batteries) you're not powering it from the Arduino pins itself.

What exactly are you trying to accomplish here?  Post some more info.


Can I use GPS sensors in a country (India) that doesn't have its own GPS Sattelites? I am living in India. I want to work on Arduino Projects with GPS Modules. But only a few countries like US, Russia, China etc. have their own GPS satellites. India is working on it. So I am hesitating to buy GPS sensors. Can I work normally with GPS modules in my country as shown in Online projects in my country ?

Each of the countries listed has their own satnav system. GPS satellites cover the entire world and the US government allows anyone with a GPS receiver to use it, regardless of where on or above the surface they are located.