i can't work toggle for my small project i build my small project from a few component as this photo
after finish code and project . i work run for Proteus and then the project not run perfectly because my code need toggle for data entered . i cant work toggle for data .i want help .please

this my code arduino

#define CLK 10
#define CLKI 9
#define LD 8
#define SO 11
#define SER 12

byte ledstates;
byte copy=0;
int rec=0;
unsigned long bt_leds_timestamp=0;
byte bt_leds_activated=0;

void setup(){
Serial.begin(9600);
pinMode(CLK,OUTPUT);
pinMode(CLKI,OUTPUT);
pinMode(LD,OUTPUT);
pinMode(SO,INPUT);
pinMode(SER,OUTPUT);
}

void loop(){
if (Serial.available()>0){
message();
}
if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
ledstates &= ~bt_leds_activated;
shift_out(ledstates);
bt_leds_activated = 0;
}
shift_In();
shift_out(ledstates);
}

void message(){
if(Serial.available()){      // Send data only when you receive data:
char data = Serial.read();        //Read   the incoming data & store into data
Serial.print(data);          //Print Value inside data in Serial monitor

switch (data){
  case 'A' :
    bt_leds_activated |= 1;
    break;
  case 'B' :
    bt_leds_activated |= 2;
    break;
  case 'C' :
    bt_leds_activated |= 4;
    break;
  case 'D' :
    bt_leds_activated |= 8;
    break;
  case 'E' :
    bt_leds_activated |= 16;
    break;
  case 'F' :
    bt_leds_activated |= 32 ;
    break;
  case 'G' :
    bt_leds_activated |= 64;
    break;
  case 'H' :
    bt_leds_activated |= 128;
    break;
  default   : return; }
  }
  ledstates |= bt_leds_activated;
  shift_out(ledstates);
  bt_leds_timestamp = millis();

  }

  void shift_out (byte copy){
  digitalWrite(LD, LOW);
  shiftOut(SER,CLK,MSBFIRST,copy);
  digitalWrite(LD, HIGH);
  delay(100);
  }

  void shift_In(){
  digitalWrite(CLKI,HIGH);
  digitalWrite(LD,HIGH);
  digitalWrite(LD,LOW);
  digitalWrite(LD,HIGH);
  digitalWrite(CLK,HIGH);
  digitalWrite(CLKI,LOW);
  byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
  digitalWrite(CLKI,HIGH);
  for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
    if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
        ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
    }
  }
  copy = buttonstates;
  delay(10); // delay for debouncing
   }

Currently you are shifting in the button states and directly shifting them out again to the LEDs. Thus the state of the LEDs follows exactly the state of the buttons.

As jsotola explained in the comments, you need to seperate what you get as input (buttons and serial) from what you set as output. For this you need 1 or more variables to hold the state of the LEDs (your output) and the state of each input (for example each button). The last is what you have in the copy variable. It resembles the state of the buttons input. Now create a new variable byte ledstates;. The shift_out() function has to be called with this variable instead of with copy.

Now that input and output are seperated, you can look at the desired behavior for the input. As 1 button press (pressing and releasing) should toggle the state of the corresponding LED, you have to look for a LOW-to-HIGH transition. A common way is to save the current state of the buttons in a variable. Then, in the next execution of shift_in() you can check, if the previous state (as saved in the variable) and the new measured state do a LOW-to-HIGH transition (previously LOW, now HIGH). This is a button press, that you can use to toggle the corresponding LED bit in the newly created ledstates variable. Save the new measured state in the copy variable. (Btw: You should rename the copy variable to something more describing)

Also you need to consider a mechanism, that you haven't had to bother with the previous code: Button bouncing. A mechanical switch or button will not make one single clean transition, when being pressed. The mechanical contact will bounce a bit, resulting in very fast HIGH-LOW transitions, until the button is settled. If you don't consider that in your program, you will get many transitions and thus toggling the LED many times with only one button press. There are many ways to tackle this (and all of them can be easily googled). I would go with the "don't sense any further transitions after the first for a fixed time" way. This can be done by a simple delay() call at the end of your shift_in() function (not so elegant with some caveats) or by using millis() to create a non-blocking timeout (in the best case for each button individually) (Look at the BlinkWithoutDelay example, that comes with the Arduino IDE. It is worth learning this principle).

So you have something like this (not the full code, just some hints):

byte copy;
byte ledstates;

void loop(){
    if (Serial.available()>0){
        message();
    }
    shift_In();
    shift_out(ledstates);
}

void shift_in(){
    digitalWrite(CLKI,HIGH);
    digitalWrite(LD,HIGH);
    digitalWrite(LD,LOW);
    digitalWrite(LD,HIGH);
    digitalWrite(CLK,HIGH);
    digitalWrite(CLKI,LOW);
    byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
    digitalWrite(CLKI,HIGH);
    for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
        if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
            ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
        }
    }
    copy = buttonstates;
    delay(10); // delay for debouncing
}

As mentioned above we have seperated input and output. Now it is easy to also implement a fitting bluetooth control. You want the corresponding light go on on serial input (through bluetooth) and go out after a specific time automatically. For such a thing using millis() with a timestamp is the best option. First we take the message() function. We define 2 variables at the global scope (outside of any function at the start of the program) to hold the timestamp of our last serial communication and a byte to hold the LEDs, that where activated via serial. In the message() function we now set the corresponding bit in this last variable. If the serial data was not valid, we simply return from the function (this makes the code shorter). At the end of the function we ensure, that every LED that was set in our variable gets also set in our ledstates variable, which then will be shifted out. And lastly we save a timestamp with the millis() function, which returns the number of milliseconds since the startup.

unsigned long bt_leds_timestamp=0;
byte bt_leds_activated=0;

void message(){
  if(Serial.available()){      // Send data                   only when you receive data:
    char data = Serial.read();        //Read   the incoming data & store into data
    Serial.print(data);          //Print Value inside data in Serial monitor

    switch (data){
      case 'A' :
        bt_leds_activated |= 1;
        break;
      case 'B' :
        bt_leds_activated |= 2;
        break;
      case 'C' :
        bt_leds_activated |= 4;
        break;
      case 'D' :
        bt_leds_activated |= 8;
        break;
      case 'E' :
        bt_leds_activated |= 16;
        break;
      case 'F' :
        bt_leds_activated |= 32 ;
        break;
      case 'G' :
        bt_leds_activated |= 64;
        break;
      case 'H' :
        bt_leds_activated |= 128;
        break;
      default   : return; }
  }
  ledstates |= bt_leds_activated;
  shift_out(ledstates);
  bt_leds_timestamp = millis();
}

Now the corresponding LEDs get turned on, but not off. So we need to put the following code in the main loop() function:

if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
  ledstates &= ~bt_leds_activated;
  shift_out(ledstates);
  bt_leds_activated = 0;
}

This code checks, if any LED was activated via bluetooth (the first part of the if condition evaluates to true, if bt_leds_activated is different than zero) and if a certain time (here 2s aka 2000ms) has passed since the timestamp was taken. When the time has come, then the LED bits from bt_leds_activated, which we set earlierare cleared inledstatesto turn the LEDs off. Then this is shifted out to set the actual state of the LEDs for us to see. Finally we resetbt_leds_activated` to zero, since we don't have any more LEDs to turn of automatically, until new data arrives.

This has 1 caveat: When you send new data over bluetooth within these 2s, the timeout for the LEDs previously activated via bluetooth will also be resetted, so that they will light longer. The way around that is to use 1 timestamp for each LED, but I thought this as to complicated for now. Don't want this, you can implement that part yourself just like I did with all of them together.

Note: I haven't tested this code in any way.


Use Arduino to detect low battery state and shut it down I wanted to know if it is possible to monitor a battery that is driving the Arduino and check its voltage. When the voltage drops below a certain level (i.E below 3.0V) it should shutdown and disconnect itself from the battery by using a relay or something. When the battery is full enough again it should power up again. Is that possible without any external sensors just by using the Arduino's inputs?

It is not entirely beyond possible, in fact quite possible in theory.

I think the saying 'in theory, theory and reality are the same, but in reality they are not' is appropriate here.

So to monitor voltage, a simple voltage divider circuit can be used, and the Arduino can monitor that, and release a relay controlling the power line. The same relay could be wired to also reconnect when voltage reaches a threshold. I think the circuit actually requires 2 (or more) relays, and technically is it a kind of sensor, but since you indicated a relay was ok, it could work. So given those requirements, do you really need someone to draw it out, or were you just curious?

Simple battery monitoring from http://arduinotronics.blogspot.com/2012/04/voltage-monitor.html


Shift Register w/ Internal Pullups? Is there a chip that is just a parallel in / serial out shift register but with integrated internal pullups?

I could use a full-blown I/O expander but I really just need more momentary button inputs. I don't need outputs and I would rather not bother adding resistors or with writing commands to initialize the chip.

Logic integrated circuits such as shift registers normally do not contain pull up resistors on their input(s).  This is because they are normally connected to a totem pole driver.  Such a driver eliminates the need to avoid floating inputs.

Also, pull up resistors require current when the input is driven toward the opposite power rail.  Even though adding internal pull up resistors may not change the overall behavior of the chip, designers will avoid parts if they unnecessarily add to the over all power demand.

Based on your comments and your question, consider an old ps/2 keyboard. It is essentially a switch matrix with a built in decoder chip which may fullfill your requirements. The chip scans the switch matrix, debounces the switches and converts button presses & button releases into a serial stream of data.

Added later...

Here is a description about connecting a ps/2 keyboard to an Arduino.  Included are schematics, code examples and supporting library.

(USB keyboards are not well suited for this purpose as they require a USB Host.  As most Arduinos do not have this, a USB Host shield is required.)


Using modulo for negative values I want to wrap a random number using modulo, so that values exceeding 11 starts over from 0 and greater. However, i would also like numbers less than 0 to dividend 11 or less.

Please correct me if i'm wrong, but as far as i can tell the modulo operator only dividends values exceeding the divisor. If so, how can i write code that also dividends values less than 0?


Arduino Nano, DS3231 RTC clock module and 4 cascaded FC-16 led matrix modules Like I said in the title, I am using a DS3231 real time clock module and 4 cascaded FC-16 modules(they are basically MAX7219 led matrices based modules). My goal is to display a timetable, a schedule for a classroom on the matrices. The purpose of the DS3231 module is to keep track of time(mainly hours) from 8:00AM to 20:00PM, to display the hour on the matrix and to change the subject when it hits even hours.
Eg: when it's 8:00AM we have subject A, when it's 10:00AM we have subject B etc

And after that I have to use a ESP8266 wifi module to change the schedule from distance.

EDIT1:
I managed to display the hour on the matrix, but now I really can't figure out how to display the text in 4 rows. I have 4 FC-16 modules and I want to put each of them on top of the other so I can have 4 rows of text. I managed to do this by inserting space between words but this is not optimal. I want this to be automated so the person changing the text in the program doesn't have to do the spacing thing by themselves.

#include "RTClib.h"
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

const uint16_t WAIT_TIME = 1000;

#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 16

#define CLK_PIN   13
#define DATA_PIN  11
#define CS_PIN    10

MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

RTC_DS3231 rtc;

//char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  P.begin();

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

 if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
//     If the RTC have lost power it will set the RTC to the date & time this sketch was compiled in the following line
   rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  }
}

void loop () {
    DateTime now = rtc.now();

    char buffer[] = "hh:mm";  // hours and minutes
    P.print(now.toString(buffer));  // display

   // Serial.println();
    delay(1000);
}```

how do I display the time from the DS3231 clock module on the FC-16
  led matrix modules?

You can use the DateTime::toString() method to convert the
current time to a string in the format of your choice, then P.print()
to display that string on the LED matrix:

void loop() {
    DateTime now = rtc.now();
    char buffer[] = "hh:mm";  // hours and minutes
    P.print(now.toString(buffer));  // display
}

  how do I use that hour of the day so that the microcontroller knows
  what text it should display next?

Condition your logic on now.hour().


What's the relation between arduino standard library and esp8266 library? Can I only use the Arduino standard library, without touching any esp8266 related header files?

I tried to connect to WiFi , succeeded with ESP8266WiFi.h header, but failed with  Arduino library WiFi.h.

I follow this https://www.arduino.cc/en/Tutorial/ConnectWithWPA WiFi connecting tutorial but the board seems to reboot repeatly (I don't understand the error of course. I know nothing about hardware).

My board is ESP8266 V3 ESP-12N F NodeMcu Lua CP2102

The WiFi shield and an ESP8266 with any of several popular WiFi services firmwares are different pieces of hardware, each of which can provide WiFi services to another device connected to it, such as an Arduino Uno. Their interfaces are different, despite that they could be used to do similar jobs - offloading the WiFi communications from the Arduino - and the two libraries are written to drive each of them, respectively.


powering arduino with a voltage divider to increase lifespan I have a chinese arduino nano that I'm planning to use to open a door using a numeric keypad.

My power source is 12V and I want it running 24/7. I have read that the first thing to fail on an arduino is the voltage regulator due to the heat of lowering the voltage to something the arduino can use.

I have think of buying two big resistors of around 1W each to build a voltage divider and only feed 7V to the Vin pin of the arduino, so it will increase its lifespan.

Is this a good idea?

Terminating voltage by dropping it over large power resistors is a bad idea, efficiency wise. There are better options.

Switch-mode Buck (=step down) converters are usually far more efficient than linear regulators. A linear regulator dumps the excess voltage in a resistor which converts the energy mainly into heat. A switch-mode converter works by switching on/off an inductance at the right time, which is far more efficient.

For step-up/step-down DC-DC converter theory look here, here and here. For a comparison for switch-mode against linear regulators look here.

A step-down converter module like the ones with a LM2596 should be good enough for you. See here on ebay.


What does it take to compile Linux on Arduino, if at all possible? Is it possible to run Linux on Arduino? If yes, what steps and limitations need to be considered? If not, what are the limitations that prevent this?

Linux is a very complex operating system, but it may be able to fit on an Arduino. Things to consider:

There is no current AVR port of the source code.
You would have no graphics, instead access the terminal over UART.
The filesystem driver would have to be rewritten to access internal flash or an external SD card.
It would be extremely slow! The ATmega328 would run at 16 MHz, or about 20 MHz max (overclocked). Most Linux machines run at a minimum of 400 MHz, and more with graphics.
You would probably need some extra RAM, probably a good idea to use an ATmega2650 (the one in the Mega), which has 16 times the RAM of the Uno. You could also use a Due (6x as fast as the Uno, more RAM).
You may have to write special USB drivers for OTG (on the Due) or MAX3421EE (Mega ADK, USB host shield).

In short, it would take a lot of time and effort, and probably would be too slow for everyday use. If you really want Arduino Linux, check out the Yún.


Changing I2C address of MPU-6050 Is it possible to change I2C address of MPU-6050 ?

I am trying to connect a bunch of MPU-6050 to my Arduino.

Almost all of them are running on the same address. Few are running on different address.

Can anyone tell me how to change I2C address of MPU-6050 if it is possible ?

The MPU-6050 has an address pin, marked as A0, which can be used to set the LSB (least significant bit) of the address. So if you connect A0 to ground, the address will be 0b1101000, if you connect it to Vcc it will be 0b1101001. You can find this information in the table under capter 6.4 in the MPU-6050 datasheet (page 15). Normally this pin is getting hardwired, but you can also connect A0 to a digital output pin of your Arduino and dynamically change the address of the MPU.

So with this pin you can have 2 different MPU-6050's on the bus. If you need more, you can keep all MPU's on one address, while pulling the MPU, that you want communicate with, to the other address. I described this principle at the end of my answer to this question. It is about a different chip, but the principle is the same.

It is important, that you cannot have multiple devices with the same address on one I2C bus, unless you never communicate with that address. When you try to use an address, where multiple devices will answer, the I2C bus most likely will get stuck, or the data will get corrupted. As long as such an address is never called, everything is fine.


How to debug Arduino using Atmel studio? I have an Arduino Yun board and an Atmel ICE programmer/debugger. There are 6 pins on the Arduino Yun to connect to Atmel ICE for programming only, but I can't find the pins for debugging. Anyway to do so? Which pins on the Arduino should I connect to Atmel ICE?

I found another very easy way to debug the arduino board with atmel studio without even using an external debugeer like the atmel ice debugger. It's an extension called vMicro which can be added within atmel studio (visual studio as well) you connect the arduino board over the micro USB to the computer and specify the parameters in the vMicro toolbar in atmel studio and that's it!
 It's ready to debug! Finally I think atmel ice is thought for other boards maybe, since debugging can be done without it easily!


Smallest microcontroller? I am looking for a microcontroller that is small (like a attiny10) which is the smallest one I could find.
Requirements I need: analogRead on 1 pin, 7 pins for analogWrite to micro leds so in total 10 pins (ground, power, analogRead, analogWrite). It's circuitry has to be basic no adding extra things like a crystal oscillator etc.. This will allow me to send a certain code to the recieving pin and then the microcontroller decide which led to turn on.

I don't know whether it's really the smallest you can find but... The
ATtiny84 has an ADC, more digital pins than you need, and is
available in 3 mm packages (UFBGA and VQFN). There is also an
Arduino-compatible core available for it.


CH340 Nano avrdude: stk500_getsync() not in sync resp=0xa4 I'm trying to upload some code to an non-arduino nano with the CH340G chip, and the avrdude refuses to let me upload. The error I'm getting is:

Using Port                    : COM4
Using Programmer              : arduino
Overriding Baud Rate          : 115200

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xf6

avrdude done.  Thank you.

I've tried installing the drivers for the CH340 chip following this guide but have had no luck. I've also tried uploading to my arduino uno and my arduino micro (both are arduino brand) with no problems. I'm running Windows 10, Arduino IDE 1.8.5

Any ideas?

Arduino has recently changed to using a different bootloader on their official Nano boards that communicates at 115200 baud rather than the previous 57600 baud. Support for these new boards was added in Arduino AVR Boards 1.6.21. The new Nano board definition is not compatible with old Nanos and likely most 3rd party Nanos so backwards compatibility is provided via the Tools > Processor > ATmega328P (Old Bootloader) menu selection.


Streaming audio to ESP8266 over WiFi I am thinking of making a wireless speaker using the ESP8266 chip. I have some questions regarding this.

Which pin of the ESP8266 chip can be used as I²S output? I have an ESP chip of this type :

Which ESP chip would be the best choice for this purpose?
I know about the MAX98357A which is used to convert digital I²S data to analog. But, for stereo output I need to use 2 of those. Is there any alternative to this chip which supports stereo output by default?
I have found many tutorials which shows how to play audio from SD card of ESP8266. But, how can I stream audio over standard WiFi connection?

Which pin of the ESP8266 chip can be used as I²S output?

I uses GPIOs 2, 3, and 15. You only have GPIO2 available, and that's also one half of the UART interface.  Also you usually need to generate a "master" clock (usually something like 256x the bit clock) for oversampling. So you can't with that module.

  Which ESP chip would be the best choice for this purpose?

ESP32, without a shadow of a doubt.

  I know about the MAX98357A which is used to convert digital I²S data to analog. But, for stereo output I need to use 2 of those. Is there any alternative to this chip which supports stereo output by default?

Yes, there are plenty. The search term you want is "CODEC". Personally I use the TLV320DAC3101.

You never use two separate mono CODECs for stereo, since I²S is a (normally) stereo protocol for connecting to a stereo CODEC. Reliably splitting a stereo I²S stream into two mono ones is not easy.

  I have found many tutorials which shows how to play audio from SD card of ESP8266. But, how can I stream audio over standard WiFi connection?

By implementing a suitable protocol, and that depends entirely on what your audio is and how it is generated.


ESP8266 not working. No response Hello. I have begun working with an ESP8266 and an Arduino Uno. The connection I used is shown below, except I am using an Arduino Uno. The rest of the connection is the same.
The code I'm using is:
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

void setup() {
  Serial.begin(9600);
  ESPserial.begin(9600);
  Serial.println("");
  Serial.println("Remember to to set Both NL & CR in the serial monitor.");
  Serial.println("Ready");
  Serial.println("");
}

void loop() {
  if (ESPserial.available()) {
    Serial.write( ESPserial.read() );
  }
  if (Serial.available()) {
    ESPserial.write(Serial.read());
  }
}

But the serial monitor is only printing:

Remember to to set Both NL & CR in the serial monitor.
Ready

What to do?

ESP8266 WiFi modules typically have a baud-rate of 115200. This not only won't work with a 9600 baud host but SoftwareSerial can't go that fast. Or, more precisely, it can generally push out characters at that speed but it can't keep up with incoming ones. See this answer for how to change the speed of your module to 9600 baud.

Short answer: You have to reconfigure your ESP module to 9600 baud to use it with SoftwareSerial. You can do it blind (transmit a baud-change command to it at 115200 baud, even though you won't be able to read the reply). Once done, it will remain at 9600 baud and successfully communicate in both directions.


First Start Arduino Uno When I started connecting my Arduino Uno for first project: LED to pin 13, resistor, breadboard, USB connected to Windows Laptop, the orange on-board LED flashes every second and the LED on the breadboard did the same.
What program is driving this?
I had NOT uploaded any program.
Please explain.

It is a preloaded sketch and will be overwritten when you upload your first sketch into the Arduino.

Typically it's the Arduino Blink sketch which can be found here:

https://www.arduino.cc/en/Tutorial/Blink

Which has the following (functional) content:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}


why does it use A0 to define analog pin 0 in some case and why use 0 directly? https://www.arduino.cc/en/Tutorial/AnalogInput

https://www.arduino.cc/en/Tutorial/Knob

For first line of both examples(not in comments), it define the same pin, analog pin 0, but they use different values. why and can use A1, A2, etc. to define other analog pins?

The answer is in the source code. Keep in mind that for this answer, I'm assuming you have a standard Arduino Uno. For other Arduino platforms the values are different but the situation is the same.

If you look at the analog pin definitions in hardware/arduino/avr/variants/standard/pins_arduino.h, you'll find these lines:

static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
...

Which tells you that if you call analogRead(A0), it is equivalent to calling analogRead(14). So, really, the question is "How can calling analogRead(0) work?"

The answer to that is in hardware/arduino/avr/cores/arduino/wiring_analog.c. If you wade through the defines, you'll see that at the top of analogRead, there is the following code:

if (pin >= 14) pin -= 14; // allow for channel or pin numbers

The result is that passing either 0 or A0 results in 0 being used in the analogRead code.


How to wire and use a L6219 motor driver I have 4 of these L6219 motor drivers and I dont know how to wire them. They have almost no wiring diagrams and when there is something, I cannot understand it.
And I forgot I also need help sending data to it; I would like if I could use an arduino for that.
Also this was from a motor driver soldering kit and in the box I also found a pic18f4450 microchip well maybe we can use that somewhere too but for now. I need help wiring and using a l6219 motor driver. And also can I even use an Arduino with these drivers?
Thanks!

If you want an idea of how to connect it there is a nice instruction for the evaluation board complete with a schematic. You will find it here.
https://static5.arrow.com/pdfs/2008/03/06/semi_ap/manual/st/ds/an6219eval.pdf If you go to: https://www.datasheetarchive.com/l6219%20microstepping-datasheet.html
you will find a lot of Links to more information. I believe this was designed originally as an automotive part. This is IC form is not a plug and play, you will need to do more research to better understand it. It looks like it could be a fun project and you could tell us exactly how to use it.  It should work fine with most 5V I/O Arduinos such as the Uno and Nano.


How to run my buzzer for few more seconds after switching off This is a basic level lazer alarm project. When anyone crosed or kept their hands on the lazer. buzzer starts working but when they took their hand from lazer light buzzer stops. But i want even after taking hands my buzzer should work for few (15-30) seconds .so please help me by giving idea..

If you are using a digital buzzer, you can do:
digitalWrite(buzzerPin,HIGH);
delay(1000);
digitalWrite(buzzerPin,LOW);


Serial read SSID and PASSWORD WiFI connection failed in ESP32 Trying to get Wifi SSID and password dynamically from serial monitor and connecting to WiFi, tried the below program, but wifi is always in Connecting state only, it is not getting connected after receiving input from serial monitor.

#include <WiFi.h>

#define BAUDRATE 115200

char ssid[50];
char pass[50];

void setup() {
  Serial.begin(BAUDRATE);
  Serial.println();
  Serial.print("Enter your WiFi credentials.\n");
  Serial.print("SSID: ");
  while (Serial.available() == 0) {
    // wait
  }
  Serial.readBytesUntil(10, ssid, 50);
  Serial.print(ssid);
Serial.print("donessid");

  Serial.print("PASS: ");
  while (Serial.available() == 0) {
    // wait
  }
  Serial.readBytesUntil(10, pass, 50);
  Serial.print(pass);
 Serial.print("donepass");

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("Connecting....");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void loop()
{}

Is your Serial Monitor setting set to "Both NL and CR"? Change it to "Newline" should works.

What happened is if your Serial Monitor has a setting of "Both NL and CR", when your press Enter, it generates a \r\n, the Serial.readBytesUntil(10, ssid, 50) picked up that \r at the end of the array, when you use it as SSID, it is not a valid SSID.


Weird Arduino timer behaviour I am trying to output something every one second with the following code.

volatile uint64_t timerCounts = 0;
double timenow,pretime;
void setup()
  {
     Serial.begin(19600);
     noInterrupts();
     TCCR2A = TCCR2B = 0;
     TCNT2 = 0;
     OCR2A = 124; //Zero Relative 125
     TCCR2B = B00001101;  //prescaler = 1024
     TIMSK2 |= (1 << OCIE1A);
     interrupts();

     Serial.print("Begin... \n");
  }

  //**********************************************************************
  //  Timer2 Interrupt Service is invoked by hardware Timer 2 every 0.008s
  //  16Mhz / 125 / 1024 = 125 Hz    0.008s

  ISR(TIMER2_COMPA_vect)
  {
     timerCounts++;
     if (timerCounts == 125){
        Serial.print("1s");
        timerCounts = 0;
     }
  }  // end of TIMER2_COMPA_vect

  void loop()
  {

  }

In the above code, I have set the OCR2A(output compare register) to 124``, which is well below 256(2^8). A user defined counter is also used.

However, when I execute the programme, the interval between consecutive outputs is less than 1 second.

When I change it to timer 1, the interval becomes roughly 1 second.
When I change it to timer 0, the interval becomes longer than 1 second.

Anyone knows why?

Thanks.

OCR2A doesn't do anything because the timer is in 'normal' mode. In normal mode the timer will just count to 256, not 125. Which would mean the you get a serial.print every 2.05s.

You need to use CTC mode. Do this by setting the WGM21 bit to 1.

TCCR2A = _BV(WGM21);


Serial1 is not reading the Xbee on a Arduino Due I am trying to test simple communication between a Xbee on my Arduino Due and a Xbee linked to XTCU. I attached jumper wires from RX and TX to RX1 and TX1 (Serial 1 hardware port) but I cannot send or receive data between the Xbees. I tested the Xbees previously with an Arduino Zero talking to the XTCU and it worked flawlessly.

Extra information: I am using a Xbee Shield on my Arduino Due (as shown in the picture)

char c,d;

void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
Serial1.begin(9600);

}

void loop()
{
// put your main code here, to run repeatedly:
if (Serial1.available())
{
 c = Serial1.read();
 Serial.print(c);
}
else if (Serial.available())
{
 d = Serial.read();
 Serial1.print(d);
}

}

My wiring is attached. What am I doing wrong?

I fixed my problem. I stupidly left the Xbee Shield on DLINE instead of UART. Now there is communication between the radio modules. I have another question. When I type a character into XTCU, it "receives" the exact character from the Arduino Due. I have used this basic code with other Arduinos before and this has never happened.

Extra information: The serial monitor solely prints out received data.

I attached an example.


Arduino Uno & Wemos (0.66” Across) OLED Shield As I wrote in title, I have Arduino Uno and Wemos (0.66” Across) OLED Shield which i bought along wemos d1 mini.

For some reason I want to use it with uno. but there are just 0.96 tutorials internet and I don't know which pins to connect. I would appreciate any help.

PINS UNDER blue stick are

TX
RX
D1
D2
D3
so on..

The first thing I see when googling "0.66 lolin oled" is the link to https://wiki.wemos.cc/products:d1_mini_shields:oled_shield and their Get started guide. This yields the libraries to be used with it:

for the OLED: https://github.com/mcauser/Adafruit_SSD1306/tree/esp8266-64x48 with the dedicated test sketch
for the A & B buttons: https://github.com/wemos/LOLIN_OLED_I2C_Button_Library


Arduino Nano, nodeJS serial I tried to make a 2 way communication between my Arduino and a PC(running linux mint) using NodeJS:
My Arduino code:

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

void loop() {
  if(Serial.available()) Serial.println(Serial.readString()+"\r");
}

My NodeJS code:

var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyUSB0',{
  baudRate: 9600,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
  parser: SerialPort.parsers.readline('\r\n')
});

port.on('open',function(){
  setInterval(() => port.write('Test'),1000);
});

port.on('data',(data) => console.log(data.toString()));

There is possible encoding error, but I cannot seem to find and fix this. Thanks in advance

You don't need to revert to sending single bytes. Line oriented
protocols work well with both Arduino and Node.js. The only difficulty
is that you have to decide what line terminators you want to use, and
then consistently use them.

I tend to use CR for the PC → Arduino stream and CRLF for Arduino
→ PC. Using different line terminators is kind of odd, but this
convention plays well with terminal emulators: the emulator usually
sends CR when you hit <Enter>, and expects CRLF in return. Also,
Arduino's Print::println() sends CRLF.

Here is a simple test demonstrating this convention. Node.js side:

var SerialPort = require('serialport'),
    port = new SerialPort('/dev/ttyACM0', {
        baudRate: 9600,
        parser: SerialPort.parsers.readline('\r\n')
    });

port.on('open', () => setInterval(() => port.write('Test\r'), 1000));
port.on('data', console.log);

Notice the different line terminators in readline() and write().

The Arduino side:

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

void loop() {
    static char buffer[128];
    static size_t pos;

    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\r') {                       // line terminator
            buffer[pos] = '\0';                // terminate the string
            Serial.print(F("Arduino received: "));
            Serial.println(buffer);            // echo received message
            pos = 0;                           // reset buffer position
        } else if (pos < sizeof buffer - 1) {  // regular character
            buffer[pos++] = c;                 // buffer it
        }
    }
}

Here you may notice that Arduino has no equivalent of
parsers.readline(), so I had to implement it (comparing the incoming
character to '\r'). Note that explicit buffering of the incoming
message is a standard way of handling line-oriented protocols on
Arduino. Stream::readString() does not work well for this purpose, as
it waits for incoming bytes until it times out.
Stream::readStringUntil() may work better, but I prefer to avoid it
just because it returns a String, which relies on heap allocation.


How to implement a 2D lookup table? This is my first post to this forum.  I am fairly experienced in electronics, but am in the process of learning C, Arduino coding, and how to use microcontrollers in general for various applications.

I have a toy-like 5 degree of freedom (DOF) robot arm that is currently controlled using the OEM hand-held switch box.  It is a basic electromechanical robot arm to illustrate the fundamentals and it uses DC motors to drive the joint motions.  The direction of motion is controlled by changing the polarity of the applied voltage.  The manufacturer did offer an "interface board" and SW to be able to hook up the arm and control it using a computer program.  However, this approach was fairly dated and their SW was not compatible with windows 8.1.  I wanted to experiment and use an Arduino Uno Rev 3 and 5V DC relay PCBs to develop my own interface system.

Basically, the HW aspect was straightforward and is working fine.  The Arduino SW also is working fine.  I am playing around with 2 variations of the program: 1) One program that simultaneously moves up to 3 joints and 2) A sequential joint movement program where each joint only moves after the other has finished moving.  One note about the simultaneous program is that I am using the "internal" batteries in the robot's base (only 3V each direction) and thus can not realistically move more than 3 joints at the same time without putting too much load on the source voltage.

Ok, now to my question! As it stands now, the program works well, but is not intuitive.  Each joint has 2 relays associated with it: one for each direction of travel.  There are 5 joints total in the robot arm.  I am able to use the program easily since I know directly (from setting up the HW and then the SW) which relays correspond to which Arduino pins and of course which relays correspond to each joint.  I'd like to make the program more intuitive where instead of "2,2,0,0,3,4" input string for example, the user would do something like "B,CCW,S,CW"  where B is for B = base, CCW = is counter clockwise etc.

Please note that in the numerical only input string "2,2,3,4" for example, the 2nd value corresponds to the duration in seconds that the relay will be ON (and thus the joint moving).  The robot arm is not very sophisticated in that it doesn't have encoders for position feedback.  The simplest way (and the method which the OEM interface board uses) to interface this arm and make a program where the arm will move in a "hands-off fashion" was to use relays and program delays (to create time durations of joint movement".  The numerical only input works really well currently and it was very easy to use examples to figure out how to parse a comma separated string.

I understand (I think) from looking at the examples how to parse a comma separated text string and pull from it the input values.

BUT, I am uncertain how to use those input values and then associate them in the SW with the correct relays (Arduino Pins)!

I have already tried seeking help with this but am unable to understand this thread:  http://forum.arduino.cc/index.php/topic,94701.0.html

Basically, I need a 2D table where the joint and direction are input and then the SW associates one particular relay with those inputs. Please see the table below for a graphical example of what I tried to say above.

One possible solution that I dread and saw mentioned was to use a ton of if else-if statements....  I dread this since I want to be able to input any joint in any order and thus it seems like when the code parses the input string for the ith relay, it would have to check ALL of the conditions to see which joint it is, which direction etc.  For example, I think I could minimize the # of if statements needed if I only entered in the input commands in a certain order: base first, shoulder next, etc.  Doing so however, limits the intuitiveness of the program.

Thank you all for reading this!  I hope this isn't too challenging!

I suggest you turn this into a simple 1D table by using two different
separators, for example ‘:’ between joint and direction, and ‘,’ between
consecutive movements. Then, instead of “B,CCW,S,CW” you would type
“B:CCW,S:CW”. For parsing the string, you split at the commas, and
consider the pieces between the commas as single items. In other words,
“B:CCW” would be the name for relay 2, and you do not try to split it
further.

Here is a simple method to map the strings to the relays:

const char * const relay_names[] = {"", "B:CW", "B:CCW", "S:UP",
    "S:DN", "W:CW", "W:CCW", "E:UP", "E:DN", "G:OP", "G:CL"};

// Return the relay number.
int get_relay(const char * name)
{
    for (int i = 1; i <= 10; i++)
        if (strcmp(name, relay_names[i]) == 0)
            return i;
    return -1;  // meaning invalid
}


Arduino: command not found After installing the Arduino IDE on MacOS (1.8.5), I am trying to run some commands in the terminal to flash the firmware on an Uno R3.

I have successfully connected and uploaded through the GUI, but would like to use the command line for the johnny-five API (https://github.com/rwaldron/johnny-five/wiki/Getting-Started).

However, when running

arduino --install-library "Firmata,Servo"

I get the following error:

  -bash: command not found

How do I install the command line interface?

Instructions to installing and binding the Arduino CLI can be found at

https://github.com/arduino/arduino-cli#getting-started

Once you install the binary, copy the executable into a directory which is in your PATH environment variable (such as /usr/local/bin/).

Note: You may have to rename the binary to arduino-cli.


Can't upload to Arduino Mini via Arduino USB 2 Serial Converter I bought an Arduino Mini and also an Arduino USB 2 Serial Converter.
While trying to program the Arduino Mini, I get this error:

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00

After doing some research I tried many things like changing the settings, serial port, made sure I'm using the right Arduino etcetera.

Some points to consider:

I tried burning the bootloader using my Arduino Uno.
Uploading sketches to the Arduino Mini using my Arduino Uno works (so problem is not directly with the Mini).
I am pressing the Reset button before uploading. I also tried hooking a capacitor and the Reset wire directly. No change.

The wiring (I also tried connecting TX of Mini to RX of serial converter, and vice versa):

The Arduino USB 2 Serial converter was defect (even though brand new). I bought a cheaper (7 Euro) FTDI to USB and I can now upload.


Library for working with a 4-digit 7-segment indicator SH5461AS Good day. Tell me an excellent library for working with a 4-digit 7-segment indicator.
I am currently using #include <fDigitsSegtPin.h>
But it does not allow you to display letters, does not allow you to put dots in the right place.
I think it is not flexible.
I want it to be easy enough to control the indicator and have sufficient freedom to choose segments (numbers, letters, dots, dashes). I tend to use the library: "SevenSeg library".
Tell me a really good option for my goal, and so that, as always, this library does not slow down all the code
I am using an indicator of the form:

This one  tm1637 sounds good. I was thinking to use it next time.
Edit 1:
Lately posted image suggests that it is without a separate display controller chip, then this library should work.
Edit 2:
This library specific to the SH5461AS display: Library
Include these three libraries:
#include "Segment.h"
#include "Digit.h"
#include "Display.h"

Print needs to be in the loop:
void loop() {
  d.print("1.234"); // Must be looped!
}

For disabling decimal points:
#define DISABLE_DP

The library's Github has very good documentation too


How to convert this sketch to keep only one if-else statement? int ldrPin = A0;
int rainPin = A1;
int smokePin = A2;
int greenLED = 6;
int redLED = 7;

// you can adjust the threshold value
int thresholdValue = 500;
int LightSensorThreshold = 500;
int RainSensorThreshold = 500;

void setup() {
  pinMode(ldrPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);

  pinMode(rainPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);

  pinMode(smokePin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  int lightSensorValue = analogRead(ldrPin);
  Serial.print(lightSensorValue);

  if(lightSensorValue < LightSensorThreshold){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

  int rainSensorValue = analogRead(rainPin);
  Serial.print(rainSensorValue);

  if(rainSensorValue < RainSensorThreshold){
    Serial.println(" - It's wet");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - It's dry");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

  int smokeSensorValue = analogRead(smokePin);
  Serial.print(smokeSensorValue);

  if (smokeSensorValue < thresholdValue) {
    Serial.println(" - Smoke");
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, HIGH);
  }
  else
  {
    Serial.println(" - No Smoke");
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, LOW);
  }
  delay(100);

}

First find the duplicated code.

E.g. the fragment

  int lightSensorValue = analogRead(ldrPin);
  Serial.print(lightSensorValue);

  if(lightSensorValue < LightSensorThreshold){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

is repeated three times.

Then find within the duplicate code fragments, the differences, which are:

the pin number
the value to check against.
the two texts

Then make a new function containing one duplicated code fragment, and replace the differences, by variables which you pass in the function as arguments:

void checkSensor(int pin, int sensorLimitValue, char* okText, char* warningText)
{
  int sensorValue = analogRead(pin);
  Serial.print(sensorValue);

  if(sensorValue < sensorLimitValue) {
    Serial.println(okText);
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  else {
    Serial.println(warningText);
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  delay(500);
}

And call respectively:

checkSensor(ldrPin       , LightSensorThreshold, " - light"   , " - dark");
checkSensor(rainSensorPin, RainSensorThreshold , " - it's wet", " - it's dry");
checkSensor(smokePin     , thresholdValue      , " - Smoke"   , " - No Smoke");

I switched the green/red values, because I assume when the value is lower than the limit, the green LED should be on, and otherwise the red LED.

Btw, why not use smokeSensorThreshold instead of thresholdValue to keep it consistent with the other duplicated code fragments?


ATTiny85 433Mhz with sleep I would like to micromize my Arduino project and move it to ATTiny85. The first step was using sleep functions because I just want it to run once a day. Now I need to connect the 433Mhz stuff but I'm getting into a fight with cores vs. libraries vs. missing functions.

No matter what core and library combination I pick, there always seems to be something missing.

/home/thijs/Documents/Arduino/libraries/VirtualWire/VirtualWire.cpp:260:18: error: 'WGM12' was not declared in this scope
     TCCR1B = _BV(WGM12) | _BV(CS10);

I have tried Tiny cores, high lowtech cores and Manchester and VirtualWire libraries. I don't want to dive into the libraries and make them 'suitable' for ATTiny because I have more than one project.

How do I approach this dependency problem?

[edit]
Found a better core here:
https://github.com/SpenceKonde/ATTinyCore

The error you posted has nothing to do with an Arduino core. This is just plain avr-libc stuff. In order to use this kind of functionality, you need to

#include <avr/io.h>

In the Arduino core, it is common to have this done by default. But if this is not the case with your chosen core, just add the #include yourself in the program.


Is the supply voltage made available anywhere on the Arduino Uno Board? I need to power an OpAmp based circuit that will be connected to my Arduino Uno input. Since I have a 12V adapter for the Arduino board, I want to draw power from it for this opamp(LM358).

Does anybody know if there is any way I can do this from the Arduino board(pins?)is as opposed to having to solder wires directly to the bottom of the DC jack?

The Vin pin is available (next to Gnd) pins.


Arduino Uno not appearing under ports I have an Arduino Uno attached to my MacBook Air running the Arduino IDE 1.6.4.

The Arduino was visible in the Serial port section this morning, but then it just disappeared. The ON light on the Arduino still comes on, but I cannot connect to it through the port section. I attached the Uno to another computer and it did not appear there either. However, when a different Arduino is connected to my computer it does show up. I also tried using a different IDE version, and it did not appear there either.

All of the other topics I found regarding this were saying it is the OS's fault, but since I was able to see the other Arduino, I am pretty sure it is not. I updated the FTDI drivers, and I tried using a powered hub and it is still not there.

UPDATE:

When I took the chip out of the UNO that is not appearing and put it into a working UNO, I was able to see it, is it possible that the Serial port is just not working, and if so how would I fix that

Any help would be appreciated.

If the Arduino doesn't show up on multiple computers, and others do, it may be bricked, or dead. You might try reflashing the chip, and hope that solves your issue. If it doesn't, chances are it's toast.

If however the device simply doesn't show up on one computer, but does on another. It's either a software issue, or a USB issue with that computer.

If winblows OS, try reinstalling, or updating the drivers for the USB, as well as the Arduino. And check your power management on the USB as well. I've seen Windows USB poop the bed if a device is connected / disconnected, or restarted several times in rapid succession. When this happens, sometimes Windows will think the port or device is faulty, and simply stop responding to its presence.

If *nix, make sure you've configured it properly.


ESP8266 not working properly It's the first time I use an ESP8266 and I didn't manage to get a proper response in the Arduino serial monitor. I only see weird characters, when I move the 3.3V wire.

You can see the connections in the following picture:

The code I run is the following one:

#include <SoftwareSerial.h>
SoftwareSerial BT1(3, 2); // RX | TX

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

void loop()
{
    String B= ".";
    if (BT1.available())
    {
        char c = BT1.read();
        Serial.print(c);
    }
    if (Serial.available())
    {
        char c = Serial.read();
        BT1.print(c);
    }
}

Maybe it's something really stupid. I am a total beginner, so I appreciate any help.

EDIT: I think power supply is 3.3V

SOLUTION: the problem was the power supply. I tried exactly the same using the 3.3V from the arduino instead of the power supply and it works perfectly!

You may well have killed the ESP by supplying it 5v, you have to have a logic level shifter, as Juraj says.

Assuming it's not dead then your next problem is there have been posts about that hardware setup and SoftwareSerial doesn't work at high speed. I can't tell you what it is that doesn't work because turning the speed of the link cures the problem, try 9600 maximum.

[Edited to be less accusational, which was not the original intent]

[Update]

Please see the datasheet here:
https://www.mikrocontroller.net/attachment/231858/0A-ESP8266_Specifications_v4.pdf

The table in section 8.4.4 says that the maximum input voltage is 3.6V
Just after that it says all digital pins are "protected from over-voltage with a snap-back circuit". This snap back voltage is typically 6V.  So does that mean the GPIO are safe up to 6V?

(It might be that this datasheet has been superseded, I am unable to access the EspressIF site at the moment).


HC-05 with ELM327 mini OBD2 Bluetooth adapter connection problem I am using Arduino Uno and HC05 Zs-040 Bluetooth module to establish a connection with ELM327 mini OBDII Bluetooth adaptor.

I have tried more than 15 different sequences of AT commands and most of them works successfully and HC05 reply with "ok" with no errors.

When I switch off the power from the HC05 and reconnect it again to connect automatically to the MAC address stored in it during configuration, the HC05 connects to the ELM327 OBDII adaptor for a time interval ranges from 2 to 5 seconds then the connection is lost.

I was able to notice that from the LED blinking on the HC05. This process of connection and disconnection is repeated automatically and the LED on the HC05 blinks in different patterns.

Also, I was able to connect to the ELM327 OBDII adaptor using a python script and it connects to it (I did that at the same time when the HC05 was trying to connect to OBDII adaptor which confirms that the connection between HC05 and the adaptor was not established).

In addition, I was able to connect to ELM 327 adaptor using Torque application and Bluetooth terminal application and both work fine.

Can anyone help me figuring out why does the connection is lost as soon as it is established?

I faced a similar problem when working with HC-05 module with an Android terminal application and connection was lost after some time and many it was just not able to connect.
Upon some hit and trials I found that it was just an power issue with HC-05 and as soon as I tried it out by reducing load on HC-05 by connecting it alone on 5V supply from Arduino and switching others to a 3V supply it worked like butter and I didn't faced any problem till now.

This worked for me try this out.


Inserting myself in serial communication I am assigned on a project involving Arduino and Raspbery PI. I have plenty of experience with Arduino and 0 with Raspbery or Linux. Person working quit and there are some problems that need me to start debuging.

The project involves control of input and output by Arduino and a touch screen and SMS aplication in Raspbery. They comunicate with standard Serial port using USB.

I want to read that communication on my PC terminal. What would be the simplest way of inserting myself without modifying anything on Raspbery?

You may be able to sniff the communication from the Raspberry Pi itself,
with no extra hardware. Assuming the program on the Pi can be configured
to use a serial port other than /dev/ttyACM0, a sniffing
program could create a pseudo-terminal pair, then forward data back and
forth between /dev/ttyACM0 and the master pseudo-terminal, while
logging everything. If you point your Pi application to the slave
pseudo-terminal, you have your man-in-the-middle logger:

Arduino --(/dev/ttyACM0)-- logger --(pseudo-tty)-- application

The interesting thing about a slave pseudo-terminal is that, as far as
the application is concerned, it behaves exactly like a regular serial
port.

There seem to be quite a few implementations if this idea. C.f. the
answers to these other stack exchange questions:

How can I monitor serial port traffic?
Sniff serial port on Linux

Just as an example, the README of
interceptty states:

  interceptty is designed to sit between a serial port (or other
  terminal device, or program, or socket, or something connected to a
  file descriptor) and a program which is communicating with that
  device, recording everything that goes back and forth between the two.
  It does this by opening the real device, creating a pseudo-tty, then
  forwarding everything between the two, recording whatever it sees.


Adafruit motorshield disconnected but getting current from Arduino my Adafruit motorshield is getting current from Arduino board even after disconnected from battery. I was planning to give separate dc power from 6 AA cells to motor shield but not sure if extra current will enter into Arduino and damage it. I have Ultrasonic sensor connected to motorshield which is getting +5v from board (may be Arduino).

Please suggest how to solve this problem.

Thanks

If all else fails, read The Manual

The manual indicates that it is intended that the MS electronics may be operated by the Arduino power supply while using a separate external supply for the motor.

Pages 37 to 39 explain about powering options.
The Arduino and the shield interconnect all of : 3V, 5V, Vin.
3V may not be used by the shield.

Arduino Vin to MS V+ is broken by jumper "PWRJMP" - purple rectangle in diagram below.
Arduino 5V to MS Vcc is not interrupted by a jumper - See labels in red squares below.

You did not say what version shield you had or which Arduino or what you mean by "disconnected from battery" or supply any links to relevant documents. ALL of these things will help people to help you better.

Assuming latest MS version,

adafruit motor shield v1.2  - discontinued.

github v1.2 schematic this appears to be pre V2 BUT is linked to from a ference in the V2 manual so is probably "more or less correct".

adafruit motor shield v2 manual - probably what you have

adafruit current MS page

This probably tells you what you need to know.  Manual page 37-38

How to set up the Arduino + Shield for powering motors

Servos are powered off of the same regulated 5V that the Arduino uses. This
is OK for the small hobby servos suggested. If you want something beefier, cut the trace
going to + on the servo connectors and wire up your own 5-6V supply!

The DC motors are powered off of a 'high voltage supply' and NOT the regulated 5V.
Don't connect the motor power supply to the 5V line. This is a very very very bad idea unless you are sure you know what you're doing!

There are two places you can get your motor 'high voltage supply' from. One is the DC jack on the Arduino board and the other is the 2-terminal block on the shield that is
labeled EXT_PWR. The DC Jack on the Arduino has a protection diode so you won't be able
to mess things up too bad if you plug in the wrong kind of power. However the EXT_PWR
terminals on the shield do not have a protection diode (for a fairly good
reason). Be utterly careful not to plug it in backwards or you will destroy the motor
shield and/or your Arduino!


How do I get sensor values using transmitter and reciever I used an HC-SR04 sensor and connected it to an arduino board (BOARD1) with a 433 mhz transmitter and the other board (BOARD2) is connected to the 433 mhz receiver but I don't know how to see the sensor value readings from the (BOARD1) and seen in the serial monitor.
HERE IS THE CODE OF THE TRANSMITTER
#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile

RH_ASK driver;
int echo=11;
int trig=9; int sensorval;
void setup()
{

    Serial.begin(9600);   // Debugging only

   driver.init();

}

void loop()
{
    digitalWrite(trig,LOW);
   delayMicroseconds(10);
   digitalWrite(trig,HIGH);
   delayMicroseconds(10);
   digitalWrite(trig,LOW);
   delayMicroseconds(10);
   sensorval=pulseIn(echo,HIGH);
     const char *msg = sensorval;

    driver.send((uint8_t *)msg, strlen(msg));
    driver.waitPacketSent();
    delay(200);
}

HERE IS THE CODE OF THE RECEIVER
#include <RH_ASK.h>

#include <SPI.h> // Not actually used but needed to compile

RH_ASK driver;
const int sensorval;
void setup()
{
    Serial.begin(9600);   // Debugging only
    driver.init();

}

void loop()
{
    uint8_t buf[4];
    uint8_t buflen = sizeof(buf);

    if (driver.recv(buf, &buflen)) // Non-blocking
    {
    Serial.print("message Received: ");
 Serial.println((char*)buf);
    }
}

First: A short excourse about c-strings
In C a string is an array of characters. Such an array is defined with
char msg[10];

10 being the size of the array. Every valid c-string needs to be terminated with the null character \0. This character is not printable, thus you don't see it normally. But the standard string functions (like printf(), strlen(), etc) use the null character to find the end of the string. So when handling strings as char arrays, you absolutely always need to terminate the string with the null character. The standard functions are incrementing through the array, until they find the null character. If it is missing, they don't stop at the end of the array.
Needing the null character also means, that the above char array can only hold 9 characters (since the 10th is the null character).
The standard functions for creating a string (like printf() and its siblings) already terminate the string correctly with the null character.

You are obviously trying to send an ASCII encoded string. But sensorval is not a string, it is of type int (a number). In C/C++ one does not simply implicitly convert a number to a string (please insert the image of boromir from Lord of the Rings here in your head). You actually have to say the compiler how to convert the number to a string. Also sensorval cannot itself hold that string (as it is an integer number). For that you need a char array (often called c-string) for saving all the characters of your string.
So first we need to define the char array to hold our string:
char msg[10];

This creates a char array with 10 elements, each one can hold a character of your string. So you have space for 9 characters. If you need more, you can increase that number.
Now we need to build a string in msg, that represents the value of sensorval. For that we can use sprintf(), which lets us format a string out of data and save it in a char array.
sprintf(msg, "%d", sensorval);

The first parameter is the char array to put the string in. The second parameter is called format-string. That is a string literal, that defines the format. %d represents an integer value; it is a placeholder for the actual data and describes, how it should be formatted (you can read about the different format options in the C++ documentation if you search for printf()). The following parameters (here only one) are the data values for the placeholders in the format string. Let's take an example: Assume sensorval is 1000. Then msg will be:
1000\0

The \0 being the null character.
So in your code you would replace
const char *msg = sensorval;

with
char msg[10];
sprintf(msg, "%d", sensorval);

What you have done in your code:
This line
const char *msg = sensorval;

will NOT create a string. You are defining msg as a pointer to a constant character (a pointer is a variable, that holds the address another variable in the memory, use google terms like "C pointers" for more info). And then you set the pointer to sensorval, which of course is not a valid pointer (valid meaning pointing to something reasonable here). It just points somewhere in the memory.
The example, that you got it from uses:
const char *msg = "hello";

This works, because the compiler takes all string literals (the strings enclosed by the double quotes) and puts them fixed into the memory, somewhat like a variable without a name. So here the compiler instructs the microcontroller so save the string "hello" in the memory. With the above line we define a pointer to the place in the memory, where this string is saved.
So this works good for string literals, but not, if you first need to actually build the string.


How to send a pitch bend MIDI message using arcore? I'm new to MIDI and started playing with an Arduino Leonardo and arcore.
Based on the example code, I can easily send noteOn/noteOff/controlChange messages, but I can't seem to send a pitch bend message.

Having a look at this table:

0xE0    Chan 1 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE1    Chan 2 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE2    Chan 3 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE3    Chan 4 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE4    Chan 5 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE5    Chan 6 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE6    Chan 7 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE7    Chan 8 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE8    Chan 9 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE9    Chan 10 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEA    Chan 11 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEB    Chan 12 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEC    Chan 13 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xED    Chan 14 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEE    Chan 15 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEF    Chan 16 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)

I've tried to send a message like so:

MIDIEvent pitchwheel = {0xe0, 127,127};
MIDIUSB.write(pitchwheel);

but this didn't work and I'm not sure what I'm missing/doing wrong.

Any hints/tips will be helpful.

arcore creator Ralf Kistner provided the answer:

// The pitch bend value is a 14-bit number (0-16383). 0x2000 (8192) is the default / middle value.

// First byte is the event type (0x0E = pitch bend change).
// Second byte is the event type, combined with the channel.
// Third byte is the 7 least significant bits of the value.
// Fourth byte is the 7 most significant bits of the value.
void pitchBendChange(byte channel, int value) {
  byte lowValue = value & 0x7F;
  byte highValue = value >> 7;
  MIDIEvent event = {0x0E, 0xE0 | channel, lowValue, highValue};
  MIDIUSB.write(event);
}


Powering LED strips with two power banks and they randomly change different colors when i use the second power bank So for one of my projects i want to power LED strips with power banks but once i try use the second power bank the LEDs half way through patterns jump to random different colors and then go back to the code im using to make sure they work, I dont think its a code issue as when i plug the power into my MEGA it works fine. I would use the MEGA to power the strips but i need 3 power sources to keep my strips at maximum brightness. would this be a voltage drop issue?

When I connected it to my 3 usb port power bank it works perfectly fine so it might be different currents causing it to jump im not to sure if im correct but its definitely something to do with using another power supply is causing my LEDs to randomly change multiple different colors randomly i just cant see if its a current or voltage issue. Any help would be greatly appreciated.

block diagram link

These are USB power-banks? You need a way to tie the grounds together somehow. Try tying all the ground lines from your LED strips together and also connecting a wire from one of the LED strips to a ground line on your Arduino.

The USB connections should connect ground between the power bank and the device it's connected to, so by tying the grounds on the LED strips together, that should connect the grounds on the power banks as well.


unable to install usbserial driver for GPRS shield with mac air vs. 10.9 Despite all my efforts and web crawling I can not install the necessary driver to connect my Arduino uno R3 to the GPRS shield from seeedstudio. I have attempted downloading the VCP driver from http://www.ftdichip.com/Drivers/VCP.htm
I have tried the solution offered here https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac for Yosemite and beyond through the AppleUSBFTDI driver as well as the solution offered by FTDI's script. Any help will be greatly appreciated. Please let me know if I can provide any more information.

The USB serial connection is provided by the Arduino, not the shield, and the naming pattern for an Uno on OSX will not be tty.usbserial### but rather something else (tty.usbmodem### perhaps?).

If I recall correctly, an Uno does not require a driver on OSX though older/unofficial FTDI based boards (as well as unofficial boards based on yet other fixed function chips) do require drivers.

(On Linux it is typically /dev/ttyUSB# for fixed function and /dev/ttyACM# for an Uno, both using kernel module drivers shipped with most distributions.  On Windows they are all COM# and drivers are typically required)


Comparison of an Arduino's performance? How does an AVR-based Arduino's CPU performance compare to a vintage PC (Apple II, PC-XT, TRS-80, et.al.)?

How many megaflops of number crunching can one get out of an AVR-based Arduino?

OK, so I just ran some really old benchmarks on a LightBlue Bean (AVR 328p Arduino at 16 MHz).  The Bean ran the Byte Sieve benchmark slightly slower than a VAX 11/780.  The Bean also ran some of my old floating point computations about 2X faster than the 11/750 (this VAX model has no FPU to be fair to the AVR).  That puts the Bean's math performance at somewhere around 70 kFLOPs (with few divides in the mix).  A DEC VAX is several times faster than vintage 8-bit personal computers, an IBM PC-XT being roughly 1/3 to 1/2 a VAX "MIP" in benchmark performance, with an Apple II being slower still.


Can I connect more than one IR receiver to an Arduino Uno? I want to use #include <IRremote.h> to receive information from an infrared remote control. It works perfectly with one IR receiver.

But I want to put three or four IR receivers:

IRrecv irrecv6(pin6);
IRrecv irrecv7(pin7);
IRrecv irrecv8(pin8);
IRrecv irrecv9(pin9);
IRrecv irrecv10(pin10);

And:

void setup() {
  Serial.begin(9600);
  irrecv6.enableIRIn(); // Start the receiver
  irrecv7.enableIRIn(); // Start the receiver
  irrecv8.enableIRIn(); // Start the receiver
  irrecv9.enableIRIn(); // Start the receiver
  irrecv10.enableIRIn(); // Start the receiver
}

Inside the loop function, I am checking each pin to see if there is any data received. But only the last pin (which means pin 10 above) is receiving the data and others are not.

That library only supports one IR receiver at a time. Try this fork that seems to have added multiple receivers support.


Why send my Arduino sometime Hex and sometimes the wrong? Hi i have an Arduino mega 2560 i send data from the Arduino over USB to PC. That works when i test a simple Serial.print("Hello"); but that is not that what i need. I send a timestamp as a longe Value and the databyte as a short Value. When i send the timestamp as BIN like that:

      //Initialisisation

const int RX = 0;
const int TX = 1;
const int RX1 = 19;
const int TX1 = 18;
unsigned long currentMillis;

void setup()
{
  pinMode(RX, INPUT);   //Readpin for USB
  pinMode(TX, OUTPUT);  //Writepin for USB
  pinMode(RX1, INPUT);  //Readpin for bus
  pinMode(TX1, OUTPUT); //Writepin for für bus

  Serial.begin(38400);   //open interface for USB
  Serial1.begin(4800);   //open interface for bus

  while (!Serial & !Serial1 &! Serial2)
  {
    ;//wait for serial port connect.
  }
}

void loop()
{
  //Ask if the timestamp over 8 hours, when yes,
  //send the time to the pc and reset currentMillis.
  currentMillis = millis();
  if (currentMillis >= 28800000)  //milli() 8 hours is a 4 byte  timestamp 28.800.000 millisec.
  {
    unsigned long timestamp = currentMillis;
    sendBinaryTime(timestamp);
    currentMillis = 0;
  }//end if

  //if the businterface available, read a byte
  //and send it with the timestamp to the PC.
  //If the businterface not available send an error.
  //short incomingByte = Serial1.read();
  //sendBinaryValue(incomingByte);
  if(Serial1.available()>0) //if the bus (serial1) available?
    {
      short incomingByte = Serial1.read(); //read the next byte from _rx_buffer
      sendBinaryValue(incomingByte);
      sendBinaryTime(currentMillis);   //sendBinary send a long over the bus
    }//end if
}//end Loop()

//Methods for sending long values

void sendBinaryValue(short incomingByte)
  {
    int temp = (incomingByte & 0xFF00)>>8;
    Serial.println(temp, HEX);
    temp = (incomingByte & 0x00FF);
    Serial.println(temp, HEX);
    return;
  }

void sendBinaryTime(unsigned long currentMillis)//send milliseconds after every byte
{
  int temp = (currentMillis & 0xFF000000)>>24; //send 16 bit of the low value
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x00FF0000)>>16;      //send 16 bit of the high value
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x0000FF00)>>8;
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x000000FF);
  Serial.print(temp, BIN);
  return;
}

All is fine i haven´t any error. But i want the timestamp as DEC so i have changed the code to:

       void sendBinaryValue(short incomingByte)
 {
   int temp = (incomingByte & 0xFF00)>>8;
   Serial.println(temp, HEX);
   temp = (incomingByte & 0x00FF);
   Serial.println(temp, HEX);
   return;
 }

void sendBinaryTime(unsigned long currentMillis)
{
 int temp = (currentMillis & 0xFF000000)>>24;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x00FF0000)>>16;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x0000FF00)>>8;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x000000FF);
 Serial.print(temp, DEC);
 return;
}

Now when i look on the serial monitor i get an error.
Here you can see it:

I send an A as ASCII sign that must be Hex 41 and i receive a Hex 5 but why? When i send the timestamp as BIN i get the 41 and haven´t any problem.

I hope someone can help me with friendly wishes sniffi

I have found several problems with your program, although they may not
be related with your primary problem:

while (!Serial & !Serial1 &! Serial2)

You mean while (!Serial || !Serial1 || !Serial2), although this is
only useful with virtual serial ports, like on the Leonardo. On the
mega, all of these ports are real hardware ports.

void sendBinaryValue(short incomingByte)

The way you name the parameter is misleading: a short is not a byte,
it's two bytes.

int temp = (incomingByte & 0xFF00)>>8;

You are bit-shifting a signed number, which is going to do a sign
extension. This is probably not what you want.

Serial.print(temp, DEC);

You are printing several numbers one after the other with no separator.
This is going to cause ambiguities: you cannot know whether "345" means
"3 45" or "34 5".

Finally, I don't get the purpose of your functions. Why don't you just
print the numbers like this?

Serial.println(incomingByte, HEX);
Serial.println(currentMillis);


Programming bluetooth module JY-MCU v1.06 I have a popular bluetooth module JY-MCU version 1.06 (picture below). Before i insert it to my arduino project I want to configure the name, bound speed and the pass code using usb-to-serial link. But I am facing a problem where the device does not respond to commands. Please let me explain.

I send the module to programming mode by applying +5V on 'key'

Then I send commands using CoolTerm program:

AT+NAMEmyArduinoProject
> OKyour set name

Ok. setting the name works as expected. But that is the only thing that worked for me. Other commands give no response:

AT

AT+BAUD2

AT+VERSION

AT+VERSION?

Maybe you had this happen to you? I am I sending wrong commands or doing something wrong? Please help me to figure out how to control this module.

OK, I figured it out. It looks like CoolTerm was sending wrong line endings. Thus the only command that worked was name change as it interpreted the extra symbols as part of the name specification. Now I am using in built Arduino serial communication and it works like a charm!


How do I order the gcc compiler to generate -S flag in Arduino IDE How can I set the Arduido IDE to generate the -S flag to gcc to see the machine code in Arduino? (the sketches)

Compiler flags are defined in the platform.txt of the board you have selected in the Tools > Board menu. You can also add compiler flags via a build.extra_flags property in the boards.txt entry for the selected board.


Extract arduino collected data periodically I'd like to extract data collected by a battery powered arduino for example once a day without stopping it and not using SD card.

It's posible, when I want to extract the collected data, to connect a laptop through the USB and then get data because Arduino is, at regulat time intervals, calling 'Serial.println(...)'?

This is a bit crude, but I think you could use an FTDI cable (which is a USB to UART converter) to have a program in your laptop talk to the Arduino using its UART (serial) interface.

To do it, you could plug the USB side of a FTDI serial cable to your laptop. The other end of the cable has a plug with 6 pins, 2 of which are the TX and RX serial signals. You could plug those two signals to pins D0 and D1 (RX & TX) of your Arduino using male-to-male jumpers.

In terms of software, you could code the Arduino sketch to listen on the serial port for a command from your laptop. When the command arrives, it would output the stored data (could be comma separated values with CR+LF as end of line). Your laptop would then listen for the answer and retrieve the data.


What is the best delay to use between characters sent to the serial port I have an Arduino Uno. It's role is to echo back what it receives.
But if I send it a stream of ascii characters it starts to error after the first one. Occasionally it gets the second character correct but often not.
If I delay each character then it works ok. I couldn't see this limitation mentioned in the SoftwareSerial library: https://www.arduino.cc/en/Reference/SoftwareSerial
The Arduino is running the following code:

#define BT_RX_PIN 16 // A2
#define BT_TX_PIN 17 // A3
#include <SoftwareSerial.h>
SoftwareSerial OtherSerial(BT_RX_PIN, BT_TX_PIN);

void setup()
{
  Serial.begin(9600);  // not used
  OtherSerial.begin(9600);
}

void loop()
{
  if (OtherSerial.available()) {
    char value = OtherSerial.read();
    String stri = "Received: ";
    stri += value;
    OtherSerial.println(stri);
  }
}

The limitations do say "If using multiple software serial ports, only one can receive data at a time.".  I don't have multiple software serial ports though I do have an instance of the "normal" serial port but I'm not sending any data to it... but perhaps even just initialising it is enough to disrupt seamless communication with the SoftwareSerial port?
Using the following test code for serial communication from a Raspberry Pi (using logic level conversion to go from 5V -> 3.3V and visa versa):
import time

def write(msg, delay):
  for char in msg:
    with open("/dev/ttyAMA0", "w") as f:
      f.write(char)
      time.sleep(delay)

write("hello", 0.01)

I got the following results (repeated 10 times at each delay time and averaged):
Delay (ms)   |   Success rate
10           |   100 %
9            |   100 %
8            |     0 %
5            |     0 %
1            |     0 %

A delay of 9 ms between each character means the communication rate falls from ~ 960 characters per second (9600 baud / 10 bits per 7 bit character) to ~ 100 characters per second (1 / (1 / 960 characters per second + 9ms)).  Is this right?  Perhaps I'm doing something else wrong / set it up wrong in software / hardware?

SoftwareSerial has a considerable overhead. It can often send at 115200 successfully but 9600 is about its limit for receiving, and you're trying both send and receive. In addition, for each character your code receives, it transmits considerably more than that 1 character (11 characters, by my count). It isn't too surprising that it would fall behind. You will need to either reduce the size of what you echo or reduce the rate at which you send characters to it (which is what you accomplished with your delay) so that the transmission (echo) rate can keep up.

Update:

The OP reports success with continuous reception by, and transmission from, the Arduino at 57600 baud (but not at the same time). The transmission rate would be consistent with my experience transmitting at 115200 baud (blindly and for short bursts, to reconfigure ESP8266-01s that were shipped with a preset 115200 rate.


code optimazation 6x6 Matrix I planed a 6x6 matrix with a Arduino Nano as controller.
Its only possible to let one LED in the matrix lighten up.
Any idea how I get the Code smaller? (Im a C Noobie ^^)

~Nico

Circuit diagram:

Code:

void setup() {
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(16, INPUT);
  pinMode(17, INPUT);
}

void loop() {
  int value1 = digitalRead(14);
  int value2 = digitalRead(15);
  int value3 = digitalRead(16);
  int test = digitalRead(17);
  int x1 = 2;
  int x2 = 3;
  int x3 = 4;
  int x4 = 5;
  int x5 = 6;
  int x6 = 7;
  int y1 = 8;
  int y2 = 9;
  int y3 = 10;
  int y4 = 11;
  int y5 = 12;
  int y6 = 13;

  // put your main code here, to run repeatedly:

  if (test == HIGH) {
    digitalWrite(x1, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x1, LOW);
    digitalWrite(x2, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x2, LOW);
    digitalWrite(x3, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x3, LOW);
    digitalWrite(x4, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x4, LOW);
    digitalWrite(x5, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x5, LOW);
    digitalWrite(x6, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x6, LOW);

  }
}

You can use arrays to hold sets of row pin numbers or column pin numbers, which then allows use of for loops for pinMode() settings and for testing LEDs one after another, as shown in code below.

Note, using enum { ... }; for integer-constant declarations is slightly more compact than a series of const int statements.  When a constant name in an enum does not have an = and value after it, it is given a value one larger than the previous constant.  So, for example, the first enum in the following code sets x2 to 3, x3 to 4, etc.

enum { x1=2, x2, x3, x4, x5, x6};
enum { y1=8, y2, y3, y4, y5, y6};
const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
const byte colPins[] = { y1, y2, y3, y4, y5, y6};
enum { nRow = sizeof rowPins / sizeof rowPins[0] };
enum { nCol = sizeof colPins / sizeof colPins[0] };

void setup() {
  for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
  for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
  for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
}

void loop() {
  byte test = digitalRead(17);
  if (test) {
    for (byte x=0; x<nRow; ++x) {
      digitalWrite(rowPins[x], HIGH);
      for (byte y=0; y<nCol; ++y) {
        digitalWrite(colPins[y], HIGH);
        delay(15);
        digitalWrite(colPins[y], LOW);
      }
      digitalWrite(rowPins[x], LOW);
    }
  }
}

Note, subroutines and functions can be used to modularize code and (typically) reduce its volume.  See code sample below.  In the code as is, the subroutine doesn't particularly reduce volume, but definitely adds modularity.  You may find it useful to look up refactoring.

enum { x1=2, x2, x3, x4, x5, x6};
enum { y1=8, y2, y3, y4, y5, y6};
const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
const byte colPins[] = { y1, y2, y3, y4, y5, y6};
enum { nRow = sizeof rowPins / sizeof rowPins[0] };
enum { nCol = sizeof colPins / sizeof colPins[0] };

void setup() {
  for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
  for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
  for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
}

void lightup(byte x, byte y, unsigned int howLong) {
  digitalWrite(rowPins[x], HIGH);
  digitalWrite(colPins[y], HIGH);
  delay(howLong);
  digitalWrite(colPins[y], LOW);
  digitalWrite(rowPins[x], LOW);
}

void loop() {
  byte test = digitalRead(17);
  if (test) {
    for (byte x=0; x<nRow; ++x)
      for (byte y=0; y<nCol; ++y)
        lightup(x, y, 15);
  }
}


Need to make an action just once when condition is reached I'm making a device for the visually disabled that makes a sound when the water in a bowl reach certain levels.

I've already made the sensors for three levels of water and if statements to make the sound, but I need the sound to be played just once for every level change and it loops over and over.
How can I make it to sound just one time?

Here is my code:

#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
  }
  else if (mid >50){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
  }
  else if (low > 50){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
  }
  delay(100);

A possible solution to your problem can be the following:

#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;
bool first = true;
bool second = true;
bool third = true;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }
  delay(100);

In this way the sound for each level will be played only once. I hope this is what you were looking for.


Read gyro output values with other programming languages I have a large quantity of gyro values and I read them through the Arduino serial monitor. I'd like to know how I can use these values in other programming languages (such as C/C++/Java) after the values are read. Are there particular  libraries for the Arduino that could help me in this way?

If your Arduino sketch is printing the data as ASCII numeric strings (human-readable), then any language with support for reading and writing to a serial device can interact with your Arduino on the port it is connected to, and collect the gyro data as it is being sent.


Powering SD breakout board with 3.7V battery So in a previous post I asked if I could charge an SD card breakout board with a 3.7V LiPo battery, and I got a positive response, so I did it.

The problem is that it seems not to be enough, since, with the exact same wiring, if I supply it with my Arduino Uno, it works perfectly, but when I change the supply to the battery it gives an error. The following text is the result of an Arduino example script:

When connected with the Arduino:

Initializing SD card...Wiring is correct and a card is present.

Card type: SDHC

Volume type is FAT32

Volume size (bytes): 2696937472
Volume size (Kbytes): 2633728
Volume size (Mbytes): 2572

Files found on the card (name, date and size in bytes):
SYSTEM~1/     2017-04-27 15:20:04
  WPSETT~1.DAT  2017-04-27 15:20:04 12
  INDEXE~1      2017-04-27 15:20:14 76
TEST0.TXT     2000-01-01 01:00:00 49050
TEST1.TXT     2000-01-01 01:00:00 60231
TEST2.TXT     2000-01-01 01:00:00 1044
TEST3.TXT     2000-01-01 01:00:00 34831
TEST4.TXT     2000-01-01 01:00:00 189736
TEST5.TXT     2000-01-01 01:00:00 12419

When connected to the battery:

Initializing SD card...initialization failed. Things to check:
* is a card inserted?
* is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

or

Initializing SD card...Wiring is correct and a card is present.

Card type: SD1
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

I've tried to supply the breakout board both through the 3V and 5V input. Can anyone notice what am I doing wrong?

You haven't connected the grounds together in your circuit. You need to connect all the grounds together so every connection has a return path back to where it came from.  That means connect together:

An Ardino GND pin
The GND pin of the SD card breakout board
The negative (or ground) pin of the battery


Error Outputting Values Arduino Serial.print I am experimenting with the following program I found online (with slight modifications):
int x;
void setup() {
 Serial.begin(9600);
 Serial.setTimeout(1);
}
void loop() {
 while (!Serial.available());
 x = Serial.readString().toInt();
 int y = x + 1;
 Serial.print(y);
}

I am encountering an error in Serial monitor output; if I input 1, I get 21 printed. I think what's happening is that every digit in a number gets incremented by 1, and then 1 is put at the end for some reason. For example, if I input 234, my output is 3451. I think the error lies with the line  x = Serial.readString().toInt();, but am unsure how to fix this. Thank you!

There's two problems here.
First, you don't enter "234", you enter "2" followed by "3" and finally "4". Your really small timeout doesn't give the digits enough time to arrive.
Second, your line ending is being received and interpreted as "not a number" which is returned as 0 by .toInt().
What you need to do is:

Don't set a short timeout - you can remove that line entirely.
Use .readStringUntil('\n') to read up until your line ending in one go.


MISO pin issue in SPI I have interfaced sd card and ADS1262 (ADC module) with Arduino mega board and sharing the SPI control pin i.e. SCK, MISO and MOSI.
I have found that sd card is not initialized and ADS1262 is giving garbage value.
Now if I remove the MISO pin of sd card then ADS1262 is giving right (although SD card is not initialized.)
Vice-versa, if I remove the MISO pin of ADS1262, sd card is initialized and working perfectly (although ADS1262 is giving garbage value.)

Certainly, there is issue of MISO pin. How can I share MISO pin with both slaves so that both can work properly.

Any comments please.

I am using shifter - TXS0108E.

For SPI interfacing, I have tested two slaves with Mega board and found the below result when MISO is connected with both slaves and MISO pin is removing one by one from slaves.

From Above result, I thing it may be the problem of MISO pin.

I am not getting the idea, how to solve the problem in SPI interfacing in multiple slaves.

Schematic:

You probably want to use two SPI busses. If you absolutely need to use one bus, attach a digital out pin to each of the CS pins, one on the 1262 and one on the SD card. When you need to talk to one of the deviced, pull its CS line low to enable it.


Is it possible to configure FRAM memory for use as stack and heap? I'm using the Adafruit I2C FRAM breakout board with my Nano and it works as advertised, but every time I write a variable to this thing I have to use library function calls with addressing. This makes it run slower than I want it to, especially since I'm using the memory to keep camera pixel information and I need to process it quickly.
As user Majenko put it:

A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.
A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.
So for a read and write it's 38+48 = 86 bits.
Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.
At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.
If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

It's much faster to write entire arrays at a time, but I need to write the data int-by-int as the data is encountered, since my whole reason for using the breakout board was to avoid needing local buffer space.
So is it possible to somehow configure this so that my I2C bus writes to the FRAM memory autonomously just like it does with the stack/heap in the onboard SRAM memory? Because then I could just declare my arrays as normal and let the processor take care of it, and then I would be so happy.

No, you can't use SPI or I2C memories to store stack or heap data in AVR microcontrollers, as the AVR MCUs do not allow to map memories connected to the SPI or I2C buses. In other words, there is no way to tell the MCU that you connected a SPI or I2C memory, and how to use it, automatically. Therefore you can only use such memories to manually store/read data, by manually issuing all the correct command sequences, which will be very slow (as you wrote you are already doing by calling some libary functions).

Instead, you can use an external PARALLEL memory, connected to the external memory bus, which is present on SOME AVR microcontrollers (unfortunately, the ATMEGA328 has no external memory bus). Still you'll get a much slower performance with respect to the internal memory.

Finally, Arduino is not a  good platform to process (or store/read) pixel data from a camera, due to severe computing power and memory limits. Even if there are more powerful Arduino (or Arduino-compatible) boards, which feature much more powerful processors (e.g. Cortex M3 or M4), you would probably need to program them using a very optimized C (and not C++!) code, or even ASM. But at this point, there would no reasons to use an Arduino-compatible platform, instead of an another one, possibly much more powerful or even cheaper.