Why char 0x80 == 0xFFFFFF80? As far as I know a char is an 8 bit variable

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

void loop() {
  char x = 0x80;
  if(x != 0x80){
    Serial.println(x, HEX);
  }

  delay(1000);
}

To illustrate the reasons better let's look at the actual content of the data.

0x80 is 0b10000000 in binary. A char is a signed variable, which means that the most significant bit is the sign bit, with two's complement representation

So in 8-bit signed representation the value 0b10000000 is a sign bit and zero value - which is -128 in decimal notation, which is "-128 + the 7 least significant bits", or -128 + 0 in this case.

When you print a signed value on the Arduino as HEX there is no 8-bit specific function for it. Neither is there a 16 bit function. However there is a 32-bit signed function, which is the closest match available. So the compiler performs type promotion to 32-bit signed, then represent it as hexadecimal.

Now -128 in signed 32-bit is calculated in the same way - take the value of the most significant bit, negate it, and add the value of all the other bits to it.  With 32-bits the value of the most significant bit, in decimal, is 2147483648, so negate that into -2147483648. Now we need to make that into -128, so we need the difference between the two to add to it. That's 2147483520.

So you get the MSB + 2147483520, which in hexadecimal, is 0xFFFFFF80.

Of course, the compiler doesn't go through that whole routine - instead it uses something called sign extension. This method basically means copying the sign bit from the original smaller (char) type into every bit to the left of it in the larger type:

                           10000000 8 bit signed
                  11111111 10000000 16 bit signed
11111111 11111111 11111111 10000000 32 bit signed

All those are -128 in two's complement, just stored in different size variables. So when you come to print it, that is just what you get - the two's complement representation of -128 in the variable size that has been accepted by the print function.

You might find this site useful for experimentation and furthering your understanding of variable data storage.


Arduino SPI Communication with H3LIS100DL accelerometer I'm having trouble getting information off the accelerometer I'm trying to use. What code should I use to read the X,Y, and Z axis?  I've read the data sheet but I don't have any experience with SPI communication.

Spec sheet

The basic SPI operations looks like this. First read single register:

uint8_t readRegister(int index)
{
  digitalWrite(CS, LOW);
  SPI.beginTransaction(SPI_SETTING);
  SPI.transfer(READ | index);
  uint8_t res = SPI.transfer(0);
  SPI.endTransaction();
  digitalWrite(CS, HIGH);
  return (res);
}

And second write single register:

void writeRegister(int index, uint8_t data)
{
  digitalWrite(CS, LOW);
  SPI.beginTransaction(SPI_SETTING);
  SPI.transfer(WRITE | index);
  SPI.transfer(data);
  SPI.endTransaction();
  digitalWrite(CS, HIGH);
}

Some more details:

const uint8_t WRITE = 0x00;
const uint8_t READ = 0x80;

It is also possible to read/write a sequence of registers by providing the register index with the MS set. This will auto-increment the register index.

SPI_SETTING is left as an exercise (to be updated).

Cheers!


Save Data before Shutdown I am building a positioner and I store the current position to EEPROM when the move is complete. On start up, I want the positioner to return to the HOME position. I am running an UNO powered from the USB.
My problem is that if the Arduino is turned off, I would like to stop the move and store the current position before the Arduino dies.

Note that this would also be relevant to devices like thermostats which remember the set point through a power outage.

POSSIBLE SOLUTIONS

Store position in EEPROM at each step. No, that will wear out the EEPROM.
Connect a large capacitor from +5V to Gnd. When this falls below a set level, trigger an interrupt (ISR) that stops motion and stores current position in EEPROM.

QUESTIONS

Will #2 work, and how could I program it?
Any other ideas I am missing?

Thermostats would save the set point to eeprom once when the set point it set by the user. On startup it would just read the set point.

The analogue pins measure relative to VCC. So if you short the analogue pint to VCC the result will remain at max even as the voltage drops.

Instead use a diode to separate the measurement point from the power supply.

simulate this circuit – Schematic created using CircuitLab

As long as power is supplied the gpio input will be high. As soon as the power is removed the gpio pin will be low and the capacitor will need hold enough charge to save the position.

However what would happen if the positioner is manipulated when the arduino is off? Most devices have a callibration routine using end-of-travel detection or something similar they run on startup to find the home position.


How to enable exception handling on the Arduino Due? While the question here gives some hints, the solution provided there does not directly work on the Due, since it uses a different compiler and toolkit. Also, the Due has more than enough flash for most projects, so that the extra code required for exception handling is acceptable. But as with the AVR-based boards, "-fno-exceptions" is automatically added to the compiler flags when using the Arduino IDE, preventing any throw or catch instructions to compile.
How can I enable exception support on the Due?

First, we must make sure the "-fno-exceptions" compiler flag is overwritten with "-fexceptions". In addition, we must link a separate library that includes the compiler support functions for stack unwinding.
Navigate to C:\Users\<UserName>\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.12 and create a new file platform.local.txt with this content:

compiler.cpp.extra_flags=-fexceptions
linker.elf.extralibs=-lsupc++

recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" -mcpu={build.mcu} -mthumb {compiler.c.elf.flags} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group {compiler.combine.flags} {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -lgcc {linker.elf.extralibs}

The last line should match the corresponding line in platform.txt, with an extra {linker.elf.extralibs} at the end (upgrading the toolkit might update that line, so you may need to compare the other parameters).
These lines add the -fexceptions to the compiler command line and the supc++ library to the linker input (otherwise you'll get errors about unresolved externals). After these changes, you can rebuild your project and use exception handling.
Some usage hints
The exception support on the Due requires about 40k of extra flash memory. Given it has 512k, this is usually acceptable. A bit of extra RAM is also used, but that seems to be small enough as well.
Since there are no standard exception classes defined (and the ArduinoSTL library doesn't compile on the due out-of-the-box), you'll have to write your own exception classes, i.e something like this:
class Exception
{
  private:
  const char* _msg;
  public:
  Exception(const char* msg)
  {
    _msg = msg;
  }

  const char* Message() const
  {
    return _msg;
  }
};

Use as:

void ThrowExceptionFunc()
{
  throw Exception("Something bad happened");
}

void ValidateExceptionHandling()
{
  try
  {
    ThrowExceptionFunc();
    Serial.print("Exception was not thrown:");
  }
  catch(Exception& ex)
  {
    Serial.print("Exception happened:");
    Serial.println(ex.Message());
  }
}

Note that Unhandled exceptions will terminate the program. An unhandled exception will cause the due to output a corresponding message to the serial console and then enter a deadend fail state.


How to display an entire incoming string from the serial monitor in arduino ide? this is my first question in this forum.

I need to receive a string from the Arduino serial monitor and display it when the communication is over. I have a similar problem like the one discussed in this thread:

https://electronics.stackexchange.com/questions/45543/how-do-i-receive-an-entire-string-as-opposed-to-1-character-at-a-time-on-the-ard

Only I'm using the Arduino serial monitor instead of a RaspberryPi to send strings so I can't program the sender to attach an identifier like '\n' at the end of the string.

char inData[20];
char inChar=-1;
byte index = 0;

while (Serial.available() > 0){
  ending[1]=ending[1]+1;
  if(index < 19){

      inChar = Serial.read();
      inData[index] = inChar;
      index++;
      inData[index] = '\0';
      Serial.flush();
  }
  Serial.print(inData);Serial.print("\t");Serial.println();
}

What I receive in the console looks like this:

M
Me
Mes
Mess
Messa
Messag
Message

I need to display only the final string

Message

The code has to know when the incoming string ended and then display it once.

I'd really appreciate any help I can get.

If you really want a string. Try using Serial.readString(). It will return the full string.

The code could look like this:

if(Serial.available()
{
  string message = Serial.readString();
  Serial.println(message);
}


Instance does not name a type, in function void loop (8x8 matrix) Hey guys I'm doing a beginners project 8x8 matrix and I have some errors when compiling

The Errors are;

MyBlink:0: error: 'Instance' does not name a type
MyBlink.cpp: In function 'void loop()':

-MyBlink:40: error: 'row1' was not declared in this scope

 Instance code:
//the pin to control ROW
const int row1 = 2; // the number of the row pin 9
const int row2 = 3; // the number of the row pin 14
const int row3 = 4; // the number of the row pin 8
const int row4 = 5; // the number of the row pin 12
const int row5 = 17; // the number of the row pin 1
const int row6 = 16; // the number of the row pin 7
const int row7 = 15; // the number of the row pin 2
const int row8 = 14; // the number of the row pin 5
//the pin to control COl
const int col1 = 6; // the number of the col pin 13
const int col2 = 7; // the number of the col pin 3
const int col3 = 8; // the number of the col pin 4
const int col4 = 9; // the number of the col pin 10
const int col5 = 10; // the number of the col pin 6
const int col6 = 11; // the number of the col pin 11
const int col7 = 12; // the number of the col pin 15
const int col8 = 13; // the number of the col pin 16
void setup(){
int i = 0 ;
for(i=2;i<18;i++)
{
pinMode(i, OUTPUT);
}
pinMode(row5, OUTPUT);
pinMode(row6, OUTPUT);
pinMode(row7, OUTPUT);
pinMode(row8, OUTPUT);
for(i=2;i<18;i++) {
digitalWrite(i, LOW);
}
digitalWrite(row5, LOW);
digitalWrite(row6, LOW);
digitalWrite(row7, LOW);
digitalWrite(row8, LOW);
}
void loop(){
int i;
//the row # 1 and col # 1 of the LEDs turn on
digitalWrite(row1, HIGH);
digitalWrite(row2, LOW);
digitalWrite(row3, LOW);
digitalWrite(row4, LOW);
digitalWrite(row5, LOW);
digitalWrite(row6, LOW);
digitalWrite(row7, LOW);
digitalWrite(row8, LOW);
digitalWrite(col1, LOW);
digitalWrite(col2, HIGH);
digitalWrite(col3, HIGH);
digitalWrite(col4, HIGH);
digitalWrite(col5, HIGH);
digitalWrite(col6, HIGH);
digitalWrite(col7, HIGH);
digitalWrite(col8, HIGH);
delay(1000);
//turn off all
for(i=2;i<18;i++) {
digitalWrite(i, LOW);
}
delay(1000);
}

MyBlink:0: error: 'Instance' does not name a type

Once I deleted the line Instance code: on the first line both errors went away.

Cheers


Using SD card shield on Arduino Due I have a Seeed Studio SD card shield (V3) that I am trying to use on my Arduino Due. I am having trouble using the SD examples that come with the Arduino IDE.

They worked fine on my Arduino Uno by setting chipSelect to SS. Below is the code I used for the Arduino Uno. It is the same as the CardInfo.ino in the examples section under SD (except for the chipSelect).

CardInfo.ino

    /*
      SD card test

 This example shows how use the utility libraries on which the'
 SD library is based in order to get info about your SD card.
 Very useful for testing a card when you're not sure whether its working or not.

 The circuit:
  * SD card attached to SPI bus as follows:
 ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
 ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
 ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
 ** CS - depends on your SD card shield or module.
        Pin 4 used here for consistency with other Arduino examples

 created  28 Mar 2011
 by Limor Fried
 modified 9 Apr 2012
 by Tom Igoe
*/

// include the SD library:
#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = SS; //CHANGE HERE!!!!!!!!

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("\nInitializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
  pinMode(10, OUTPUT);     // change this to 53 on a mega

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card is inserted?");
    Serial.println("* Is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}

void loop(void) {

}

Here is a picture of my setup:

tl;dr

How do I make this shield work on my Due?

Looking at the pin configuration, the SPI pins are not in the same location as the UNO. Remove the Shield from Due and use cables to connect to the SPI pins


Controlling 5 DC motors with Arduino I am looking to purchase the correct hardware to be able to control 5 DC Motors from an Arduino (UNO preferred, MEGA if necessary).

The Specs of the Motors are as follows: 12 V nominal, 3 → 12 V dc, 794 gcm, 100 rpm, 0.394 W

What would be your recommendations for how to set this up? As I am fairly new to circuitry a circuit diagram would be helpful along with the recommendation of what shield or drivers to use. Thank You

There are currently no expansion boards (shields) for the Arduino platform that are designed to do what you're asking of it. At most you'll find shields that can support up to 2 maybe 3 motors. My recommendation for a beginner would be to experiment with a breakout board like this one: https://www.sparkfun.com/products/9457 It's compact and can easily control 2 of the motors you need, three together and you could control up to 6.


Smallest package possible reading microSD I have a project running on an arduino nano, and as part of it, I'd like to read from and write to a microSD card.  My problem is that the microSD shield for it doesn't fit my form factor (think slightly larger than a pen; definitely handheld).

I've purchased a PJS008-2003-0, and I'm wondering, assuming I have the soldering chops, is there any real reason I can't connect this directly?  What does the breakout board get me other than nicer connection points and a blinking light?  Do the example SD sketches rely on anything the shield provides, or will they work for me?

SD card need 3.3v for power and logic level. So most breakouts have a buffer chip to convert the logic levels from 5v to 3.3v.

PS, you could use an microSD to SD adapter, and solder some wires to its pads, if you are unable to solder the tiny pins on the part you ordered.


Is it possible to connect NRF24L01 to localhost in laptop without wifi router? I want to send data from arduino to my localhost port:8080(with ipython notebook) via modul NRF24L01 without WiFi router. Is it possible? If it possible, how to do that?
Thank  you...

It is possible to have 2 NRF24L01 radios to talk to each other without a WIFI router.

However, is it possible to get your notebook to talk to a NRF24L01?  Probably not unless you can write a device driver for it.

You could use two Arduinos each with a NRF24L01, and get one to receive the data and then send it via Serial to you laptop, but you would be better looking at an ESP8266, set that up as an access point, connect your laptop to that network and job done.

(By the way you won't be able to call you laptop localhost)


Getting weird characters from Arduino My arduino is connected to ultrasonic sensor and I am trying to read the value from it. When I tried running "tail -f > /dev/ttyACM0" my arduino is sending some weird characters that I am not able to decode

It would seem you failed to configure the port on the Linux side. By
default, it is configured to who-knows-what baud rate, and to a “cooked”
mode where the data is preprocessed by the kernel driver. You want
instead to set it to the correct baud rate and to “raw” mode. The stty
(meaning, “set terminal”) command does this:

stty -F /dev/ttyACM0 raw 9600

Replace 9600 with whatever baud rate your Arduino is using.

If you Arduino program attempts to read the serial port, it will see the
echo of the characters it sends. In that case you probably want to
disable this echo also:

stty -F /dev/ttyACM0 raw -echo 9600


Where do avrdude parameters get defined in the Arduino IDE? I am interested in learning how the Arduino IDE handles parameters in order to correctly upload hex files with avrdude.

I found this in boards.txt:

uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

There is this in platform.txt:

# AVR Uploader/Programmers tools
# ------------------------------

tools.avrdude.path={runtime.tools.avrdude.path}
tools.avrdude.cmd.path={path}/bin/avrdude
tools.avrdude.config.path={path}/etc/avrdude.conf

tools.avrdude.upload.params.verbose=-v
tools.avrdude.upload.params.quiet=-q -q
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.program.params.verbose=-v
tools.avrdude.program.params.quiet=-q -q
tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.erase.params.verbose=-v
tools.avrdude.erase.params.quiet=-q -q
tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uefuse:w:{bootloader.extended_fuses}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude.bootloader.params.verbose=-v
tools.avrdude.bootloader.params.quiet=-q -q
tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.platform.path}/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m

This line is particularly interesting:

tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

It seems like these variables are corresponding:

{cmd.path} --> tools.avrdude.cmd.path
{config.path} --> tools.avrdude.config.path
{upload.verbose} --> tools.avrdude.upload.params.verbose
{build.mcu} --> uno.build.mcu
{upload.protocol} --> uno.upload.protocol
{serial.port} --> ?
{upload.speed} --> uno.upload.speed
{build.path} --> ?
{build.project_name} --> ?

It seems these are likely used in the Java code for the IDE. There are obviously a few I am unsure of. I would guess these are considered user inputs in the IDE. Though I am by no means a Java or JavaScript programmer.

Where are these variables explicitly defined in the Arduino library? (e.g. {runtime.tools.avrdude.path}, {path}, {cmd.path} ....) Or how do they get defined by IDE?

There are 3(or 4) places that you need to look at to know how to upload.
There is the boards.txt file and the platform.txt file.
You can consider a platform.txt file line

tools.avrdude.path={runtime.tools.avrdude.path}

as (in linux in windows replace ${xx} by %xx%)

set tools.avrdude.path ${runtime.tools.avrdude.path}

and the board.txt for the selected board like

uno.bootloader.tool=avrdude

as

set bootloader.tool avrdude

The arduino ide uses the following string to know the upload command environment variable

tools.${bootloader.tool}.upload.pattern

This way it knows the command to upload is

"{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

{cmd.path} is hardcoded as tools.${bootloader.tool}.cmd.path which equals {path}/bin/avrdude
where {path} is to be understood as tools.${bootloader.tool}.path wich equals {runtime.tools.avrdude.path}.
{runtime.tools.avrdude.path} is defined by the boardsmanager based n the json file and the location where the boardsmanager extracted the download.

So that makes 3 files: boards.txt, platform.txt and json file and some hard coding.

A 4th file comes into play when you use the "other upload commands". These are located in the programmers.txt file.

IMHO Arduino IDE core team did not opt for the simplest solution to define these things. They also change the way they work from time to time.
If you use a makefile know that a lot of people have done this already so it may be a good idea to "reuse other peoples work" instead of "reinventing the wheel". It is not so easy or straightforward.

Note I know all these things because I implemented the Arduino eclipse IDE. As far as I know none of this is documented.


Replacing atmega8 with atmega328 on Arduino Single-Sided Serial Board i want to know that if i use atmega328-pu instead of atmega8 on this design provided by "https://www.arduino.cc/en/Main/ArduinoBoardSerialSingleSided3", will it works fine on this design or i have to use only atmega8 ?

Yes and no. It will work on this board, but won't get programmed by arduino IDE directly.

ATmega328 and ATmega8 are fully pin compatible. ATmega328 is like bigger and powerful in terms of onchip resources. However, if you want to program ATmega328 on the arduino board, you must install bootloader. Otherwise you will have to program it everytime using ISP programmers such as USBASP. This will connect to the ICSP socket shown on the above board.

Refer to: http://tutorial.cytron.com.my/2011/09/30/how-to-program-arduino-by-using-avr-usbasp-programmer/


Problem communicating between arduino UNO R3 and Mega 2560 via MAX485 I want to send data between Arduino Uno and Mega via MAX485.

When I set the data Enable pin to HIGH on Mega (to transmit data) and set the same pin on UNO to LOW (to receive data) I can read data from Mega into Uno properly. However, when I want to do it vice versa (send data from uno to mega) can't get any data from Uno into Mega. Tried different pins on both boards but still no answer.

This problem happens when I want to change data Enable pins to low or high inside loop(), I mean when I use for example Uno as permanent master and mega as permanent slave, it works properly but when I try to change them from slave to master on runtime, data cannot be sent from uno to mega!

PS: Im newbie on RS485 and MAX485. Here is my code in MEGA side:

#include <SoftwareSerial.h>'
SoftwareSerial mySerial(2, 3);
String inputS = "";
boolean stringComplete = false;
int i = 0;
bool b= false;

void setup() {
  mySerial.begin(9600);//Using SoftwareSerial Port
  Serial.begin(9600);
  pinMode(8, OUTPUT);//DE/RE Controling pin of RS-485
  digitalWrite(8, HIGH);//DE/RE=HIGH Transmit Enabled M1
}

void loop() {
  mySerial.println("MEGA:Hi");
  Serial.println("Hi Sent");
  digitalWrite(8, LOW);
  CheckAndReceive();
  if(stringComplete)
  {
  stringComplete = false;
  inputS.trim();
  Serial.print(inputS);
  Serial.println(": " + String(i++));
  inputS = "";
  }
  digitalWrite(8, HIGH);
    delay(1000);
}

void CheckAndReceive()
{
  while (mySerial.available()) {
    // get the new byte:
    char inChar = (char)mySerial.read();
    // add it to the inputString:
    inputS += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

This code is supposed to send a string to UNO and listen to it.

UPDATE:
UNO cannot send data to MEGA at all. I think there is a problem with my UNO

You have forgotten to add mySerial.flush().

mySerial.flush() waits for the transmission of outgoing serial data to complete.

Add it right after you have sent the data and want to change the DE pin status.


Interfacing MPU6050 with Arduino uno What is the meaning of "volatile bool mpuInterrupt = false; " in Arduino Program interfacing MPU6050?

The i2cdevlib has that declared in this file: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/examples/MPU6050_DMP6/MPU6050_DMP6.ino

That is the "dmp" example.
Inside the MPU-6050 sensor is a "dmp" and a FIFO buffer. The "dmp" is a processing unit that collects the sensor data, does some calculations and puts the data in the FIFO buffer. After that the Arduino is signalled with a interrupt.

In the Arduino, in the interrupt routine, the flag 'mpuInterrupt' is set. In the loop() that flag is checked and the amount of data in the FIFO buffer is read. When there is enough data, that data is read and used in the sketch.

Since the variable 'mpuInterrupt' is used in a interrupt routine and in the loop(), it is made 'volatile'. That tells the compiler that the variable can change at any moment, so the compiler can keep that in mind when creating binary code for the loop().


SCLK pulses not seen when using SPI on ESP32 I am using the following code in my esp32 using arduino IDE for spi communication which is an example code -

#include <SPI.h>

static const int spiClk = 1000000; // 1 MHz

//uninitalised pointers to SPI objects
SPIClass * vspi = NULL;
SPIClass * hspi = NULL;

void setup() {
  //initialise two instances of the SPIClass attached to VSPI and HSPI respectively
  vspi = new SPIClass(VSPI);
  hspi = new SPIClass(HSPI);

  //clock miso mosi ss

  //initialise vspi with default pins
  //SCLK = 18, MISO = 19, MOSI = 23, SS = 5
  vspi->begin();
  //alternatively route through GPIO pins of your choice
  //hspi->begin(0, 2, 4, 33); //SCLK, MISO, MOSI, SS

  //initialise hspi with default pins
  //SCLK = 14, MISO = 12, MOSI = 13, SS = 15
  hspi->begin();
  //alternatively route through GPIO pins
  //hspi->begin(25, 26, 27, 32); //SCLK, MISO, MOSI, SS

  //set up slave select pins as outputs as the Arduino API
  //doesn't handle automatically pulling SS low
  pinMode(5, OUTPUT); //VSPI SS
  pinMode(15, OUTPUT); //HSPI SS

}

// the loop function runs over and over again until power down or reset
void loop() {
  //use the SPI buses
  vspiCommand();
  hspiCommand();
  delay(100);
}

void vspiCommand() {
  byte data = 0b01010101; // junk data to illustrate usage

  //use it as you would the regular arduino SPI API
  vspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  digitalWrite(5, LOW); //pull SS slow to prep other end for transfer
  vspi->transfer(data);
  delay(500);
  digitalWrite(5, HIGH); //pull ss high to signify end of data transfer
  vspi->endTransaction();
}

void hspiCommand() {
  byte stuff = 0b11001100;

  hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  digitalWrite(15, LOW);
  hspi->transfer(stuff);
  delay(500);
  digitalWrite(15, HIGH);
  hspi->endTransaction();
}

I am able to see the toggling of the SS pin, but the SCLK pin does not show any pulses on the oscilloscope. It is a constant low. Should the pulses be given from an external source? If so, what is the purpose of this line - static const int spiClk = 1000000; // 1 MHz?

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

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

The ESP32 docs say:

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

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

So here is a working test routine:

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

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

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

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

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

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

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


Can I use Visual Studio instead of Arduino IDE? I think that Visual Studio is a great product! I find the Arduino IDE is limited in its features. For example the Arduino IDE does not have:

Code prediction
Error highlighting
Previews of #define values
Peek at code definition
Jump to code definition
and many more...

Since the Arduino ino & pde file types are basically C++, Can I use the Visual Studio IDE instead of Arduino IDE?

To be considered as a replacement, Visual Studio must be able to:

Save & open ino & pde files.
Compile my code.
Download my code.
Use existing/custom libraries from the Arduino IDE.
Detect and display an Arduino project.

I would consider these features as a bonus:

Arduino board selection.
Debugging

Variable watch window
Breakpoints
Step through code

Simulation
Open the Arduino Examples
Automatic board detection
Serial Monitor

I only use Visual Studio for Arduino programming.
Arduino Plugin for Visual Studio


Arduino Zero (ATSAMD21G) - I2C - continuous wrong data flow I encountered a strange behavior while running 2 way transmission tests  between 2 Arduino Zero (ATSAMD21G), one master and one slave. Wrong data is being continuously transferred both ways. The expected data is also being transferred in between. I have to filter out the received data to catch it (line 41 in Master's code and 33 in slave).

I'm using the stock wire libraries (being different for the 2 boards), along with Nick Gammon's "I2C_readAnything".

Master's code

Slave's code

I think this continuous flow doesn't allow the bus to be released. It might be what's making it impossible to communicate with a second master (and maybe causing my previous problem)

I also tried my code between a Mega 2560 (slave) and a Zero (master). Fake data is, this time, only being sent one way (from the Zero to the Mega only).

Is there some specific code to add to send data properly from ATSAMD boards? Is it a bug in the SAMD Wire library?

I also had to add a 1ms delay after sending data from the Master. It wouldn't go through otherwise. Shouldn't it be handled by the ATSAMD or the Wire library?

Start with a single byte, with a very small sketch, with both the Master and the Slave at 100kHz. When that is working 100% reliable, then you can try to transfer a struct.

The Slave RequestEvent function should always return valid data, not once every two seconds. The global variables that are used in receiveEvent or requestEvent and in the loop() should be made 'volatile'. Disable the interrupts in the loop() when reading or writing the global volatile struct.

With your sketch, you have to open the serial monitor for both the Master and Slave.

You could add more tests, for example testing the return value of Wire.endTransmissing, testing the 'howMany' parameter, testing the actual number that Wire.request returns.


Can I use an external power supply and still communicate with my computer over Serial? I read the following online:
If you plug in both USB power (say from a pc) and external power via the 2.1mm jack, the Arduino chooses power source automatically.

If the external 2.1mm DC is providing greater than 6.6V, the Arduino will take power from it instead of the USB.

Firstly, is this accurate?

Secondly, my real question:
If I am powering my Arduino via external DC, can I still communicate with my Raspberry Pi using serial via the USB?

Yes you can. It still leaves the data/ground lines intact, it just doesn't bridge the 5V line.

Arduino Uno Schematic v.3:

The USBVCC is directly from the 5V on the USB jack (well, technically there's a fuse there). It then goes through a transistor (T1) that only allows power through when there is no power coming from the 5V regulator (that regulates the VIN voltage).

The USB jack:

You can see pin 1 of the USB jack (5V) goes through the fuse to USBVCC. The next ones D+/D- are the data lines that go through resistors to the ATMEGA16U (used for USB to UART). The last one just ties into ground.


Simple 2 Servo Synch I have two servos connected to an Arduino, They work fine if i write to them one by one so the wiring is all correct. I have seen a lot of examples here but none are facing the same issue. I have a simple for loop with Servo.write() on two servos (Facing each other) one going clockwise and the other going counterclockwise. I just want them to rotate at the same time and i cannot connect them to the same signal line since their movement is opposite.
My Code Is:

 for(int pos = 0; pos < 90; pos += 2)
 {
     delay(200);
     int pos7 = 90-pos;
     pos7 = pos7*(-1);
     myservo6.write(pos);
     myservo7.write(pos7);
 }

What Is Happening
Both the servos go to the "same position" (if one is at 90 the other is at 0 etc.. ) Yet one goes there slow and the other goes super fast(not affected by delay). Even though my delay should affect both servos.

If i remove the delay they both go to the same position yet very fast. What i need is for them to move together slowly to the position.

The Arduino Servo class is intended to accept positive values only, in the range of 0-180.

In addition to reversing the values for one servo by subtracting from 90, your code is also negating the values by multiplying by negative one.

That results in an invalid argument to the Servo function.  It's unclear exactly what happens, but likely possibilities include an invalid pulse, or no pulse at all.

At the end of your for loop, you subtract 90 from 90 producing zero, and invert it to still zero.  Zero is a valid input to the Servo function, so a valid output is produced and the "reversed" servo finally has a position it can seek to.


Pass changing analog value from void loop to library .h file How would I go about passing a void loop analog read value to a library .h file?
I've tried it but it only reads the pot position as soon as I plug the arduino in and does not change once booted up.

arduino main sketch file code;

#include "Arduino.h"
#include "common.h"
#include "synth.h"
#include "serial-in.h"
#include "audio-out.h"

void setup() {
  Synth<0>::initialize();
  SerialIn<0>::open();
  AudioOut<0>::open();
}

void loop() {
  int val = analogRead(A0);
  int val1 = analogRead(A1);
  int val2 = analogRead(A2);
  int val3 = analogRead(A3);
  int val4 = analogRead(A4);
  while (true) {
    if (SerialIn<0>::available()) {
      uint8_t b = SerialIn<0>::read();
      Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
  }
}

.h file code

#pragma once

// #define private public  // for tests

#include "common.h"

// associations of units
#define IOsc        Osc
#define IFilter     Filter
#define IAmp        Amp
#define IEG         EG
#define IVoice      Voice
#define ISynthCore  SynthCore

#include "osc.h"
#include "filter.h"
#include "amp.h"
#include "eg.h"
#include "voice.h"
#include "synth-core.h"

template <uint8_t T>
class Synth {
public:
  INLINE static void initialize() {
    ISynthCore<0>::initialize();
    int val = analogRead(A0);
    int val1 = analogRead(A1);
    int val2 = analogRead(A2);
    int val3 = analogRead(A3);
    int val4 = analogRead(A4);
    // Preset
    ISynthCore<0>::control_change(OSC_MODE      , 0  );
    ISynthCore<0>::control_change(OSC_COLOR     , val);
    ISynthCore<0>::control_change(MOD_RATE      , 8  );
    ISynthCore<0>::control_change(MOD_DEPTH     , val1);
    ISynthCore<0>::control_change(LPF_CUTOFF_ENV, val2);
    ISynthCore<0>::control_change(LPF_RESONANCE , val3);
    ISynthCore<0>::control_change(ENV_A         , val4 );
    ISynthCore<0>::control_change(ENV_D_R       , 1 );
  }

  INLINE static void receive_midi_byte(uint8_t b) {
    ISynthCore<0>::receive_midi_byte(b);
  }

  INLINE static int8_t clock() {
    return ISynthCore<0>::clock();
  }
};

How would I go about passing a void loop analog read value to a library .h file?

What you wanted to do makes little sense. But it is certainly doable. The simplest would be to use an "extern" variable as a bridge.


Arduino audio frequency reader I have a simple project for my arduino : light some leds when i send a certain frequency from my smartphone through the jack output . For example ,
 I play a simple audio file generated with a frequency generator (it generates sinwaves, sawtooth, quadrate waves...) at 1kHz --> a red led turns on
I play another frequency (5kHz) --> a green led turns on.
I read similar questions , but they needed a precise reading of the signal frequency, so they had to convert from AC to DC and from 700mV to 2,5V, is it necessary in my case ? I can also prepare a track with a program called audacity with the current remaining always positive but oscillating between 0 and 0,7 mV.
How can i realize my project in the simplest way possible ?

Thank you

If you can properly bias your signal, say with a cap and a pot, you
could read it with a digital input. You can then time the rising edges
with micros(), either by polling the pin or using an interrupt. You
could achieve greater accuracy by using the “input capture” feature of a
16-bit timer, if you are using an AVR-based Arduino and are not afraid
of getting your hands dirty with low-level programming.

You need to get the right voltage range for this to work though. On an
Arduino Uno, for example, the thresholds for the input switching from
HIGH to LOW and back are typically around 2.1 and 2.6 V
respectively, so you must make sure that your signal amply covers this
range. If you can get 1 V peak to peak, that should be enough, and
you can then use the pot to tune the offset.


Can't upload code to an Arduino LilyPad using FTDI I've tried to upload my code to an Arduino LilyPad (328) using an FTDI basic breakout, but i get this:

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x29

I tried to install the latest FTDI drivers from the FTDI website, tried another PC, tried to install the CDM-2.08.28 driver (latest I think) and nothing.

If I change the PC port the USB Serial Port doesn't change (is always COM3).

Does the Loopback test work? Connect Lilypad's Reset to Gnd, connect D0 to D1, open the serial monitor, see if typed text is echoed back.  If, you have FTDI problems that you need to resolve.


Board won't show on one of my computers I have the same problem with these two boards: Ruggeduino (Uno compatible) and DFRobot Romeo 1 (Duemilanove compatible). On one of my Macs (a Macbook Pro running 10.11.4), I can see a new port  /dev/cu.usbmodem641 or /dev/a4005g3t depending on the board. On the other computer (a Mac Mini late 2014), they just won't show. Same cable, same boards, and no hub. I don't know where to look to see an indication of a failure of some sort.

These two ones use a type-b USB socket (printer style)

Also on the Mac Mini that won't see any of those boards, I can connect an EtherMega2560 (Arduino Mega 2560) which happens to use a micro USB socket. I don't know if that is related to the problem.

Both computers run the same OS (OS X 10.11.4) and the latest version of Arduino.

Here is a difference (found in /var/log/system.log):

On the working computer:

Mar  3 22:20:42 pc101 kernel[0]: AppleUSBFTDI: fInBufPool,kMaxInBufPool 8,64
Mar  3 22:20:42 pc101 kernel[0]: AppleUSBFTDI: Version number - 5.0.0, Input buffers 8, Output buffers 16

On the non working one:

cfprefsd[114]: BUG in libdispatch: 15E49a - 1718 - 0x0

..

My Ruggeduino stopped showing up as a serial device under El Capitan (10.11.6). I was able to fix this by installing/updating the VCP drivers for Silicon Labs USB devices available here:

https://www.silabs.com/products/mcu/Pages/USBtoUARTBridgeVCPDrivers.aspx

After installing the Mac driver the Ruggeduino shows up as SLAB_USBtoUART and works fine with the Arduino GUI.


Does old/low charge battery affects internal clock? Totally newbie in eletronics here, but could not find the answer for this one.

When a battery is nearly-exhausted, it's voltage and or amperage dims, right?

My question is if this kind of scenario (running low battery) would affect the arduino internal clock using only it.

I'm using arduino to a device that will operate remotely (with a 9V battery), and also logs intervals using the time function.

If battery is near-exhausted, then will this skew the numbers I get?

Let's assume by "internal clock" you mean the internal oscillator, as the arduino's processor does not have a built-in real-time clock (something that is meant to keep track of real time like seconds/minutes/hours.)

The arduino is not like a motor where it runs slower if a lower voltage is applied. If the voltage goes too low, the arduino will just reset. Once it resets, the program running in it just starts over again, unless the battery voltage is so low it can't even start up.

If you're feeding it with a 9V battery, you're going through the 5V linear regulator on-board, which is not very energy efficient. Keep that in mind if your goal is to create a project that is meant to run a long time on the 9V battery. See the notes at http://www.gammon.com.au/power for tips on reducing the power used by an arduino and/or ATMega-based project.


NodeMCU Light Sensor I'm using a -12E with three light sensors and a sketch I've successfully used with an Uno.  I cannot get the -12E to print anything but 0 or 1023 for a light level (0 when I connect the grounds, 1023 without grounds).

I've successfully printed from a single light sensor but now I'd like to try three.

I'm curious to know what I'm missing.  Any guidance would be appreciated.

Code is as follows:

const int photocellPin_0 = 16; // D0
const int photocellPin_1 = 5; // D1
const int photocellPin_2 = 4; // D2
int photocellReading_0;
int photocellReading_1;
int photocellReading_2;

void setup() {
  delay(4900);
  Serial.begin(115200);
  Serial.println("Startup");
  delay(100);
  pinMode(photocellPin_0, INPUT);
  pinMode(photocellPin_1, INPUT);
  pinMode(photocellPin_2, INPUT);
}

void loop() {
  delay(1000);
  photocellReading_0 = analogRead(photocellPin_0);
  photocellReading_1 = analogRead(photocellPin_1);
  photocellReading_2 = analogRead(photocellPin_2);
  Serial.println("-----NEW ON READING-----");
  Serial.print("Photo Sensor #1 = ");
  Serial.println(photocellReading_0); // the raw analog reading
  Serial.print("Photo Sensor #2 = ");
  Serial.println(photocellReading_1);
  Serial.print("Photo Sensor #3 = ");
  Serial.println(photocellReading_2);
  delay(5000);
}

This is based on an adafruit sketch I pulled off of some website (modified for three photo sensors) and I'd credit it if I could recall exactly where I got it from.

The ESP8266 ESP-12E has only one analog input, that is A0 (which tolerates a range 0-1 volt).

digitalRead() statements are not appropriate for a photocell within a potential divider since you will simply get a boolean result 0 or 1 from the connected pin.

You can read one photocell connected on A0 by analogRead( A0 ) assuming it is so connected within a potential divider that a maximum of 1 volt is presented to pin A0.

The Arduino Uno by contrast has 6 Analog inputs which tolerate up to 5 volts


TinyGPS++ Question about gps.encode(ss.read()) I am trying to make an oled gps display, however when looking at multiple examples and other people's code, I am seeing that people are using different methods. I see some code that has gps.encode(ss.read()); and other people use if gps.encode(ss.read()). I am confused on why this is. Also, people either use .isUpdated, or .isValid, when checking for location/speed, etc. On the TinyGPS++ page it talks about these, but does not say what should be used for certain applications.

From http://arduiniana.org/libraries/tinygpsplus/
Validity, Update status, and Age
You can examine an object’s value at any time, but unless TinyGPS++ has recently been fed from the GPS, it should not be considered valid and up-to-date. The isValid() method will tell you whether the object contains any valid data and is safe to query.
Similarly, isUpdated() indicates whether the object’s value has been updated (not necessarily changed) since the last time you queried it.
Lastly, if you want to know how stale an object’s data is, call its age() method, which returns the number of milliseconds since its last update. If this returns a value greater than 1500 or so, it may be a sign of a problem like a lost fix.


Split RGBW hex String into integers I have a program where the Arduino receives hex Strings that represent a RGBW color (similar to css for example). My goal is to create that color by using pwm, so I need to convert that one hex string into four integer values between 0..255 to use for the pwm.
Whats the best/easiest way to do this?

Example:

void incomingMessage(const MyMessage &message) {

    // h = hex value
    // message = e.g. (h) #112233AB
    redval = ?; // h11 => 17
    greenval = ?; // h22 => 34
    blueval = ?; // h33 = 51
    whiteval = ?; //AB = 171

    analogWrite(RED_PIN, redval);
    analogWrite(GREEN_PIN, greenval);
    analogWrite(BLUE_PIN, blueval);
    analogWrite(WHITE_PIN, whiteval);

}

I don't like using the String class because it can cause memory fragmentation. This would do it by just using C-style strings:

byte fromhex (const char * str)
  {
  char c = str [0] - '0';
  if (c > 9)
    c -= 7;
  int result = c;
  c = str [1] - '0';
  if (c > 9)
    c -= 7;
  return (result << 4) | c;
  }

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

  const char * test = "#112233AB";

  byte redval   = fromhex (& test [1]);
  byte greenval = fromhex (& test [3]);
  byte blueval  = fromhex (& test [5]);
  byte whiteval = fromhex (& test [7]);

  Serial.println ((int) redval);
  Serial.println ((int) greenval);
  Serial.println ((int) blueval);
  Serial.println ((int) whiteval);

  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

Output:

17
34
51
171

That does not do any validation (that the string is indeed 9 characters long, and contain hex characters) but I'll leave that for you to do. :)


GSM and GPS shield pin conflict I have an Arduino GSM shield and I plan to purchase an Adafruit GPS shield. The GPS module uses Pin 7 & 8 for Rx and Tx, but the GSM shield uses Pin 7 for Modem Reset.

Will the overlap on pin 7 affect it in any way? If it does cause issues, how can the problem be avoided?

Looking at the PDF for the Adafruit GPS shield, pin 7 is indeed hard wired to Rx and pin 8 is hard wired to Tx.

These can not be changed.

Looking at the guide for the Arduino GSM shield pin 7 is indeed reserved for modem reset:

  Digital pins 2, 3 and 7 are reserved for communication between the
  Arduino and modem and cannot be used by your sketches. Communication
  between the moden and Arduino is handled by the Software Serial
  library on pins 2 and 3. Pin 7 is used for the modem reset.

As this is the case, should you stack the two shields together, without modification, then the overlap of the Rx pin on the GPS shield will cause resets to the modem on the GSM shield.

So, it seems that your best option is to use the solution provided by RedGrittyBrick, to your previous question Arduino shield stacking, the Go-Between Shield

  You hear it all the time in the Arduino community, “will this shield
  work with my other shield?.” I think we’ve all been disappointed to
  find that two of our favorite shields compete for control of a digital
  pin here or a serial pin there. While there are sometimes some clever
  workarounds from elegant code modifications to aggressive
  ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution
  thus far: The Go-Between Shield.

Once you have used the Go-Between shield to reassign the Rx pin to something that the GSM shield does not use, (as 2, 3 and 7 are already used, let's say you use pin 6), then in the File -> Examples -> Adafruit_GPS -> Parsing sketch, you will need to change the line

SoftwareSerial mySerial(3,2);

to

SoftwareSerial mySerial(8,6);

instead of

SoftwareSerial mySerial(8,7);

which is recommended in the PDF.

I hope that this answers your question(s). Let us know how you get on.

Addenum

The schematic of the Arduino GSM shield:

The schematic of the Adafruit GPS shield:


How can I include examples in library? I have written a library for Arduino, my_library, consisting of my_library.h and my_library.cpp, both included in my_library folder. Actually the library is recognized from IDE Arduino and works fine.

I want to add some examples, let's say Example1 and Example2. How is that possible?

Should the examples be included in my_library folder?

or should be included in another folder inside my_library folder?

I tried several combinations but none worked. Do I miss something?

You need to create a folder called "examples" in your library folder. Within there, each in its own folder, you place your examples.

For example:

MyLib/
MyLib/MyLib.h
MyLib/MyLib.cpp
MyLib/examples/
MyLib/examples/Example1/
MyLib/examples/Example1/Example1.ino
MyLib/examples/Example2/
MyLib/examples/Example2/Example2.ino

Be sure to name the example's folder the same as the name of the example.


esp8266 cant make more than one request at time i am trying to make a get request, read that request and make another request with that read value. i havent shown it in this code but i want to make a request inside in a request. is it possible to make a request without ending one, if its, how do i do that?

here is the code :

#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "pw"

void conn();
void getreq();
void anothergetreq();

void setup() {
  conn();
  getreq();
}

void loop() {
}

void getreq() {
  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/users/1");

  int httpCode = http.GET();
  String payaload = http.getString();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  //here i presume got the value from payload, and making another request with it
  anothergetreq("posts/1");
  http.end();

}
void anothergetreq(String p) {

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/"+p);

  int httpCode = http.GET();
  String payaload = http.getString();

  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  http.end();
}

void conn() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

here is the output:

Connected with IP: 192.168.1.100

HTTP CODE: 200
PAYLOAD: {
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}
HTTP CODE: -1
PAYLOAD:

https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#bearssl-client-secure-and-server-secure

  Secure clients and servers require siginificant amounts of additional
  memory and processing to enable their cryptographic algorithms. In
  general, only a single secure client or server connection at a time
  can be processed given the little RAM present on the ESP8266

you have two BearSSL::WiFiClientSecure instances at time. it is simple to change your code to first free the first SSL client object.


Data transfer using SPI Sorry for my code is long and my English is not good.

I'm working with 8x8x8 LED cube project using Arduino nano. I tried to understand code, but I don't understand how cube[][] data write on pins.

I just want to know, how write the data from cube[8][8] to hardware using SPI. code download using this link.

Thanks in advance.

My code is here :

#define AXIS_X 1
#define AXIS_Y 2
#define AXIS_Z 3
#define REFRESH_RATE 120

int CUBE_SIZE = 8;
int SPI_CS = 10;// This SPI Chip Select pin controls the MAX72xx
byte value[8];

volatile unsigned char cube[8][8];
volatile int current_layer = 0;

void setup()
{
  Serial.begin (115200);
  Serial.println("jolliFactory 8x8x8 jolliCube Demo example 1.0");

  pinMode(SPI_CS, OUTPUT);

  SPI.begin();

  maxTransferAll(0x0F, 0x00);   // 00 - Turn off Test mode
  maxTransferAll(0x09, 0x00);   // Register 09 - BCD Decoding  // 0 = No decoding
  maxTransferAll(0x0B, 0x07);   // Register B - Scan limit 1-7  // 7 = All LEDS
  maxTransferAll(0x0C, 0x01);   // 01 = on 00 = Power saving mode or shutdown
  maxTransferAll(0x0A, 0x0F);   // Set Brightness Intensity

  setUpInterrupts();
}

// Get the current status of a voxel
unsigned char getvoxel(int x, int y, int z)
{
    if (inrange(x,y,z))
    {
        if (cube[z][y] & (1 << x))
        {
            return 0x01;
        } else
        {
            return 0x00;
        }
    } else
    {
        return 0x00;
    }
}

void maxTransferAll(uint8_t address, uint8_t value)
{
  digitalWrite(SPI_CS, LOW);

    for ( int c=1; c<= CUBE_SIZE;c++) {
        SPI.transfer(address);
        SPI.transfer(value);
    }

  digitalWrite(SPI_CS, HIGH);
}

void maxTransferOne(uint8_t whichMax, uint8_t address, uint8_t value)
{
  byte noop_reg = 0x00;    //max72xx No op register
  byte noop_value = 0x00;  //value

  digitalWrite(SPI_CS, LOW);

  for (int i=CUBE_SIZE; i>0; i--)   // Loop through our number of Max72xx ICs
  {
    if (i==whichMax)
    {
      SPI.transfer(address);
      SPI.transfer(value);
    }
    else
    {
      SPI.transfer(noop_reg);
      SPI.transfer(noop_value);
    }
  }

  digitalWrite(SPI_CS, HIGH);
}

void maxTransferLEDCube(uint8_t address)
{
  digitalWrite(SPI_CS, LOW);

  for (int i=0; i<CUBE_SIZE; i++)   // Loop through our number of Max72xx ICs
  {
      SPI.transfer(address);
      SPI.transfer(value[CUBE_SIZE-i-1]);
  }

  digitalWrite(SPI_CS, HIGH);
}

void setUpInterrupts()
{
  cli();//stop interrupts while we set them up
  //set up an interrupt with timer1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  OCR1A = (16000000/REFRESH_RATE/1024/CUBE_SIZE -1);
  TCCR1B |= (1 << WGM12);
  // Set to CS10 and CS12 so we have the 1024
  TCCR1B |= (1 << CS12) | (1 << CS10);
  TIMSK1 |= (1 << OCIE1A);
  sei();//re-allow interrupts
}

ISR(TIMER1_COMPA_vect)
{
  for(byte y = 0 ; y < CUBE_SIZE ; y++)
  {
    byte b = 0;

    for(byte x = 0 ; x < CUBE_SIZE ; x++)
    {
      //form data byte
      b = b << 1;

      if (getvoxel(x,y,current_layer)==1)
      {
        b |= 1;
      }
    }
        value[y] = b;
  }

  maxTransferLEDCube(CUBE_SIZE - current_layer);

  current_layer++;

  if (current_layer == 8)
    current_layer = 0;
}

First, you need to know how the LEDs are arranged. There are 8 layers, each with 8 rows, each with 8 LEDs.

Each LED is represented as a single bit inside unsigned char cube[8][8]; - the first [8] is the array of layers, the second [8] is the array of rows, and the unsigned char holds 8 bits to represent the state of the 8 LEDs in that row.

Each LED layer has one MAX7219 8x8 LED Matrix Controller. To tell it what to do you need to give it a Command byte and a Data byte. So to tell it to light up LEDs 1, 2, and 7 on the fourth row, you need to tell it 0x04 0x86. You send this command by setting CS LOW, sending the 16 bits of the Command+Data, then setting CS HIGH.

Each MAX7219 is connected one after the other in an SPI string. To command all of them at once you need to set CS LOW, send 16 bits for each MAX7219 (128 bits in all), then set CS HIGH. If you only want to command one MAX7219, you need to send a NOP Command+Data (0x00 0x00) to all the others.

The way the program works is:

setup()

a. Initialise the Serial port, and print a message.
b. Set the CS pin as an OUTPUT, then initialise SPI.
c. Initialise all the MAX7219 chips by sending a series of commands -
the same Command+Data to each of them (maxTransferAll()).
d. Initialise the Timer interrupt (setUpInterrupts()).
loop()
This isn't shown in the code. Presumably it alters the cube[8][8] array to make the special effects.
TIMER1_COMPA_vect (the interrupt handler)
Every time the timer ticks, the handler will command all of the MAX7219s to show the next row of LEDs.  This will last until the next timer tick, when the next row will be displayed. If this is done fast enough, the human eye's "persistence of vision" will not see the rows flickering.

For each row (`y`) in the `cube` array
   Set `b` to 0
   For each bit ('x') in the `cube` data
      If the bit is set (`getvoxel(...)`) set a bit in `b`.
   Store `b` in the `value[y]` array

value now holds the bytes needed as Data for the next row for each of the MAX7219 chips.

    Send value over SPI using `maxTransferLEDCube(...)`

Since the cube displays the same row for each layer simultaneously, the Command doesn't have to change, only the Data does. That's what the value array holds: the Data to be sent to each MAX7219 chip.


Difference between Wire.setClock() method and TWBR method for changing I2C Frequency I want to change the I2C frequency of my Arduino Mega 2560. I did find two methods. One method is to change the TWBR variable after Wire.begin(). The other one is to use Wire.setClock() after Wire.begin().

Whats the difference between the 2 methods? which one is better? Can I set any I2C frequency I want?

Whats the difference between the 2 methods?

The difference is that one is more portable than the other. The "direct register set" will not work very well on an Arduino Due.

There is no speed or foot-print advantage with the "direct register set" as this is often only done once in the setup of the sketch.

  Which one is better?

If better is portable, maintainable, readable, etc then the answer is simple - use the API and not "direct register set".

  Can I set any I2C frequency I want?

No - obviously there are some restrictions. First, the CPU frequency is scaled so it cannot generate all possible frequencies. Second, the I2C device(s) and bus will set restrictions on the maximum frequency. Longer wires and several devices will add capacity and require lower frequency. Also the device with the lowest frequency puts an upper limit. Always check the data sheets for the I2C devices.

Cheers!


L298N motor driver and battery issues I'm trying to build an Arduino 4WD smart car. so i connected my l298N motor driver module with my v4 shield and used a 4 x 1.5v AA batteries to try and power my 4 motors up. i connected 2 of the motors in parallel so i can use 1 L298N to power it on. initially it worked but then a few minutes later it stopped moving. i thought my connections were bad so i redid all the connections but it didn't work so i changed the battery to 9v. with this the motors worked for a few seconds then stopped but was making noise so i tried powering the motor driver with my Arduino but it didn't come on. I tried powering the motor driver module with my Arduino but the driver module didn't come on.i decided to use my bread board and l293D IC to control my motors it didn't work but the motors were making noise. I changed my motor to one that i removed from a PlayStation controller but nothing still.i did research on the internet and was advised on this tutorial (https://create.arduino.cc/projecthub/maxxlife/arduino-4wd-car-cf5fd0) to not use AA batteries but no explanation why. so i checked other tutorials and saw people using AA to control 1 or 2 motors. Why shouldn't i use AA batteries? does anyone please think they know the solution to my problem? thank you
This is how my kit looks https://www.ebay.com/itm/NEW-4WD-Robot-Smart-Car-Chassis-Kits-car-with-Speed-Encoder-for-Arduino-M26/201561877173?_trksid=p2047675.c100009.m1982&_trkparms=aid%3D777000%26algo%3DABA.MBE%26ao%3D1%26asc%3D36860%26meid%3Dc76077722d4348e88152fa6c7f32c005%26pid%3D100009%26rk%3D1%26rkt%3D1%26sd%3D181329341315
Also should i change my use Li-ion battery 18650 x2 instead of the 6LR61 9v battery i used

Rule #1 9V batteries a power supply they are NOT. In your case you are looking at small voltages for the motor power. Your choice of a driver is not the best as you will have from 1.2 to 2.4 volts across the L298 depending on the loading. This is directly from the ST data sheet. Try the TB6612FNG instead, taking advantage of the device’s use of MOSFETs. The TB6612 may be a little more expensive, but it will be clearly worth it.


Attiny : Is it possible to analog read on PB1? I'm trying to read an analog input on the Attiny85 physical pin 6 (PB1, PWM), but analogRead(PB1) always returns 1023. Is it even possible to use analogRead on this pin?
I'm fairly new to this so sorry if it's an obvious answer.
Thanks!

PB1 has no analog input. So no, you can't read analog with it.
For analog you must use any of PB2 through PB5.


Arduino UNO + ESP8266 WiFi Relay by LC Technology I have Arduino Uno, and recently obtained ESP8266 WiFi Relay by LC Technology. I tried to look up some information about that on the net, but all the answers / suggested solution didn't work for me. Let me briefly explain the problem.

I have connected this module to arduino in a very simple way:

TX -> pin 7
RX -> pin 6
5V -> IN +
GND -> IN -

Simple code:

#include "Arduino.h"
#include <SoftwareSerial.h>

#define TxPin 7
#define RxPin 6

SoftwareSerial ESPrelay(RxPin, TxPin);

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

    readRx();

    ESPrelay.println("AT");
    readRx();
}

void loop() {
    Serial.println(ESPrelay.read());
    // this above is constant -1
}

void readRx() {
    String msg = "";
    while (ESPrelay.available()) {
        char rxByte = ESPrelay.read();
        msg += rxByte;
    }
    Serial.println(msg);
    delay(500);
}

I can see WiFi AP created by the module - so I think module itself works fine - communication between Arduino and module is somewhat broken.

I tried all different AT commands, but none of them seems to take an effect (tried switching modes and connecting to home WiFI, but no luck) also, no response is returned. Could someone try and help me debug this issue?

I tried changing 9600 to 115200 when communicating, but no luck with this either.

Serial connection requires connecting transmit TX pin to receive RX pin. Your SoftwareSerial pins ar pin 6 RX and pin 7 TX. So your wiring should be esp8266 TX to Uno pin 6 and esp8266 RX to Uno pin 7.

Connect 5 V and ground to the pins header, not to screw terminals. The IN terminals are for powering the relay coil.

Call read readRx() in the loop(). Add delay before sending "AT" in setup to let the esp8266 time to boot.


Pulldown resistors and multiple switches Maybe this is a question for Electronics SE but I’m not a member there yet so hopefully someone will have an answer here.

I did an experiment with having some push-to-make buttons connected to my Uno. I copied the circuit from the aduino.cc website and all worked exactly as expected. Here is my schematic of the circuit as I have it now:

The pins are both held LOW by the Pulldown resistor until the switch is closed, when they go HIGH.
All well and good. But I’ve just been looking at the circuit and something puzzles me. I can see a direct connection from Switch 1 to Pin 2 VIA the resistors and the Ground connection – and vice versa, S2 to P1. See my pathway in Red here:

Now, to be clear, this is NOT happening – but I just want to understand why not. Is it just that the 2 resistors in combination provide enough resistance to stop the opposite pin from going HIGH? In which case, this Pulldown resistor is actually serving 2 completely different functions in the circuit…?

Call the resistors R1 and R2, the negative terminal Ground, and the positive terminal V+.  The junction of R1 and R2 is connected to Ground.  This holds the resistor ends at the junction to zero volts relative to ground.  Ignoring P2 for the moment, the other end of R2 is open circuit to V+ when S2 is open.  Applying Ohm's law, we have a finite resistance in series with an infinite resistance, so zero volts across R2 when S2 is open.  Thus one sees that voltage across R2 is not affected by voltage changes across R1.

P2 as an input is not completely an open circuit; typically its effect is similar to a multi-gigaohms resistor to some voltage between Ground and V+.

Edit:
More directly, observe that the voltage at the Ground ends of R1 and R2 is zero and remains at zero no matter what S1 and S2 do.  Thus, operation of S1 does not affect voltage at P2, and operation of S2 does not affect voltage at P1.


How can Arduino source code be tested automatically (continuous integration)? I'd like manage my Arduino source code (projects and libraries) under source control with continuous testing. How can I automatically compile the code with continuous integration tools, to make sure each version compiles cleanly? In the best case one should be able to configure builds for multiple processors, optionally run unit tests and check for maximum binary size.

Newest version of Arduino ide has a command line interface to build and upload code. But you can obviously do it by makefile and avrdude.
Now, you have compiled your code BUT you need testing.
As simulator are complex,incomplete, expansive and.. Just a simulation, and because the chip are relatively cheap, building a board witch will make HW interaction AND check the results its the fastest and easiest way.
On that "special" board you may upload something like an interpreter witch take a test from the PC and execute it, something similar to firmata for arduino.
At least that is how I would build it.
And as far as I know there are no know implementation of this, even if I'm quite sure many industries should and probably do that.


Can I measure the current (mA) of my project with just a multi meter? I have a project and wish to choose the correct battery back for it such that it will last the required amount of time between each recharge of the battery pack. I am using an Arduino Duemilanove with various attachements and shields.

I can measure that the draw on the project at the point the USB connects from my PC to the Arduino board (by attaching the multimeter to the Vcc and GND solder points on my Arduino board) which reads 5V DC as expected. Is there a way I can meausre the current (without any additional equipment) ?

I suspect somehow using Ohms law and measuring the resistance between two points would be the answer (knowing the voltage is 5V) but I can't work it out (as in where to measure) with my lack of any electrical knowledge.

No, you won't get the right result measuring resistance. Integrated circuits contain lots of semiconductors which are inherently non-linear.

You need to somehow put your multimeter in series with the power supply, set to the mA range. The easiest way I can think of is to use an external battery (7v or higher) and make up a custom cable with standard barrel jacks. As your board appears to have a linear voltage regulator, the current measured will be very close to the current consumed when powered from the USB port.


Programming Other Atmel chips using Arduino Is it possible to burn Arduino code on any other third party Atmel products using an another Arduino ? And if its possible then how ?

Is it possible to burn Arduino code on any other third party Atmel products using an another Arduino ? And if its possible then how ?

Do you mean if the "Arduino as ISP" sketch and an Arduino would work to flash another Atmel AVR MCU? If so the answer is yes but I guess that you also want to generate code for the new MCU. In that case there is some work to be done before that is possible.

Start by reading about how to install additional cores and the guideline for a custom core. Then select an custom core to study. Here you will find the files you need to provide to support a new AVR based MCU.

Cheers!


Arduino-compatible wireless technology which can be suitable for transmitting data Introduction

I've been meaning to build a vehicle using arduino components and LEGO. I have a mechanical clamp built with arduino which will be locked on top of a custom LEGO build (It should be made out of LEGO blocks and arduino sensors). In my mind, it resembles a crawler.

Question

I've been looking for a way of controlling it remotely.
I only have experience with IR controllers but I'm not sure if this technology would fit for my project.

What I'm looking for is a technology wich could transmit data to an Arduino board (thus, an emitter and a receiver component) which, in my case, could comfortably handle a veichle.

Plus, it should have a range of action of at least 5 meters (15 ft).

If such technology exists, do you know any controller which could do the job for me?

You can use radio transmitter/receivers, they are typically called RF (Radio Frequency) modules.

Typical examples are nRF24L01+ (2.4 GHz), or RF 315/433 modules (on 315/433 MHz).

There are more possibilities, but these are the most used on Arduino and libraries are available.


Multiple IDE instances I recently moved all in for Linux and have no intentions of going back to Windows, but programming for Arduino is a little annoying as I cannot find a way to have multiple instances.

In Windows you create individual shortcuts for several Arduino IDE instances. When you launch these from the desktop they are autonomous, meaning you can set a board/port combination for each one.

I have yet to find a way to do that in Ubuntu. Is there some form of isolation I can use? I tried using workspaces but they all still see just the one setting.

I do not want to have a bunch of VMs and switch from one to the other unless that is the only option left.

Is there some way I can emulate the Windows autonomous shortcut approach in Ubuntu?

There is nothing special about it, it just works.

I strongly suggest to remove everything that is Arduino related from the repositories and have a minimal Java environment installed.

It is no problem to have a gcc build environment together with Arduino though. Even a gcc-avr build environment from the repositories is no problem. But don't install any Arduino or Java-rxtx from the repositories.

You can download the linux version and unpack it in a folder.
Go to that folder where you unpacked the Arduino files and right-click on the 'arduino' file to create a shortcut. Move that shortcut to your Desktop.
Depending on the flavor of Ubuntu that you have, you can also create a starter and fill in the whole path of the 'arduino' file.

Then you can start the Arduino IDE, and just click/activate that shortcut or starter again for another instance of the Arduino IDE. They will work independent of each other. You have to set the right board for each instance of course. A third one or more is also possible.

If you have trouble with shortcuts or starters, then you can even open a terminal and go to the unpacked files, type "./arduino" to start it. Open an other terminal (or new 'tab' in the terminal) and do the same.

You don't have to makes copies of the Arduino files, you don't have to make multiple shortcuts or starters. Just start a new instance by activating the shortcut or starter once more.

I recommend to use only the newest version (at the moment 1.8.3). But if you need to run an older version then you can download and unpack older versions in seperate folders. Be careful that you can not run different versions of the IDE at the same time. The Arduino IDE before 1.6.x differs too much from 1.8.x. All of them share the same ~/.arduino15 folder with settings and downloaded files, which can cause trouble when running a new version, then an older version and then a newer version again.


How can I use arduino board for AC mains? I want to use LDR to control a light bulb (12W) which runs on AC supply using Arduino.

Is it possible to do this?

If yes, how?

Try the PowerSwitch Tail II.

This is suitable if you are living in the USA (120VAC power).
You will find 240VAC versions as a kit on that web page as well.


I think I just bricked my Arduino. Any ideas how? I think I have a short circuit in my Arduino Uno R3. The symptoms are:

It does not seem to be responding as before.
The orange "L" LED does not blink on boot-up, but just stays on continuously.
If I plug in a 12V source, then the voltage between the 5V and GND pins starts out around 5V, but then starts dropping rapidly. In the meantime, the underside of the board heats up a lot. If I plug in the USB source, the voltage between the 5V and GND pins stabilizes at around 4.28V ... but again, nothing seems to work.
After all this, I also checked continuity between the 5V and GND pins, and heard a beep. However, subsequent reading told me that this is not a reliable (or well-advised) test.

It seems like I have a short on my Arduino, right?  Any idea of how this could have happened?  I can only think of the following possibilities:

I was running the Arduino off a lead-acid 12V battery. At some point, the negative terminal wire disconnected and there was some sparking at the battery when I reconnected it (the pattery was also powering other things). Could this have damaged the Arduino?
I am using the Arduino to run 3 IR LED . To minimize wiring, I had wires these LED in series, rather than in parallel, which (at least at first) seemed to work. Is there any possibility this would have damaged it?

Thanks for any help.

See my answer here. A 12V battery doesn't necessarily provide you with 12V any more than a 1.5V battery provides 1.5V.

See here for example. A 12V lead-acid battery may well provide 12.7V which is out of spec for the Uno.

See the page about the Uno.

You have too much voltage going into the voltage regulator, it tries to dissipate it, it gets hot and either shuts down or fails.

I suggested in the answer above to use a buck converter to down-convert the voltage, and my answer (which was accepted) said that "it is working like butter".


Arduino programmers for hire? How do I best connect with Arduino programmers who are willing to design small projects for some extra cash?

The Arduino Forum has a Gigs and Collaborations section where such questions are welcome.


Arduino ADC read bad value I have an Arduino device and I'm trying to read two voltages. The first one is the Arduino Vcc by using the bandgap value 1.1V (this requires raw access to registers since it's not implemented in analogRead). The other one is checking the battery voltage using the badgap as a reference. I want both of them because I'm doing a study on the battery life when using a step-up converter.

I'm using these pieces of code:

// Read bandgap with Vcc as reference - this will give use the Vcc
ADMUX = DEFAULT << 6 | 14;
delayMicroseconds(250);
bitSet(ADCSRA, ADSC);
while(bit_is_set(ADCSRA, ADSC))
    ;
word x = ADC;
Serial.println(x);

// Read A1 with 1.1V bandgap as reference - this will give battery voltage
ADMUX = INTERNAL << 6 | 1;
delayMicroseconds(250);
bitSet(ADCSRA, ADSC);
while(bit_is_set(ADCSRA, ADSC))
    ;
word x = ADC;
Serial.println(x);

The problem that I have is that separately they seem to work well, however when using them together the first piece of code ruins the reading for the second one. The culprit is the line ADMUX = DEFAULT << 6 | 14. This sets up the default reference (chip voltage) and reads channel 14 (which is the 1.1V). I can't figure out why after using this line changing back with ADMUX = INTERNAL << 6 | 1 doesn't work.

The datasheet says:

  The first ADC conversion result after switching reference voltage
  source may be inaccurate, and the user is advised to discard this
  result.

Then you could try to take each reading twice, looping over four ADC
readings:

Read bandgap with Vcc as reference, discard the value.
Re-take the same, keep the value.
Read A1 with 1.1V bandgap as reference, discard the value.
Re-take the same, keep the value.


Do I need to worry about voltage, coming from ground, and effecting an analog input? I am building a project that includes an analog Input and several digital Inputs and Outputs.  All of them connect to ground in some way.  Do I need to worry about voltage, coming from the digital outputs, going to ground, and effecting readings on the analog input?  If so, how do I deal with this?

The arduino has build in pull up resistors, it is not a residue voltage coming from ground more than a "not 100% 0 volt" resistor.

Even though there is built in pull-up resistors one can add additional resistance to the arduino to make sure it will not show a false positive.

From what i have learned, you cannot experience voltage comming from ground (if everything is properly wired), if you want to make sure. Place a diod in the direction of the power flow, to prevent this.


strtok problem while parsing String Here is my code. The incoming string is "*CRB12344,Temp25,Humidity55,CC5#"

I am unable to get value of Temp which is 25 and Humidity which is 55 and CC which 5. It only display the value of CR i.e B12344 (in this case). May be issue with strtok function?

String inputString = "";
boolean stringComplete = false, StartCapturing = false;

char inData[50];
char inChar, IncomingWeight;
char IncomingString[50];
const int httpPort = 80;

char *i, *k,*p;
String CardID;
int Temprature, Humidity, TC, CC;
byte SendData = 0;

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

void loop()
{
  serialEvent();

  if (stringComplete)
  {
    inputString.toCharArray(IncomingString, 50);
    Serial.println();
    Serial.println(IncomingString);

    i = strstr(IncomingString, "CR");
    {
      if (i)
      {
        p = i+2;
        CardID = strtok(p, ",");

        Serial.print("Card Number :");
        Serial.print(CardID);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "Temp");
    {
      if (i)
      {
        Temprature = strtoul(i + 4 , NULL, 10);
        Serial.print("Temprature :");
        Serial.print(Temprature);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "Humidity");
    {
      if (i)
      {
        Humidity = strtoul(i + 8 , NULL, 10);
        Serial.print("Humidity :");
        Serial.print(Humidity);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "TC");
    {
      if (i)
      {
        TC = strtoul(i + 2 , NULL, 10);
        Serial.print("Total Count :");
        Serial.print(TC);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "CC");
    {
      if (i)
      {
        CC = strtoul(i + 2 , NULL, 10);
        Serial.print("Current Count :");
        Serial.print(CC);
        Serial.println();

      }
    }

    stringComplete = false;
    inputString = "";
    delay(10);
  }

strtok() is a destructive function. It replaces the token with an end-of-string marker (\0). Thus once used the original string is irevocably lost.

Your first use of strtok() changes the string from:

*CRB12344,Temp25,Humidity55,CC5#\0

to:

*CRB12344\0Temp25,Humidity55,CC5#\0

Thus any future references to InputString only see up to the end-of-string marker:

*CRB12344\0

Instead you should use strtok() in a while loop to slice the string into tokens and examine what the token is:

char *tok = strtok(IncomingString, ",");
while (tok) {
    if (strncmp(tok, "*CR", 3) == 0) { // tok is *CRB1234
        // ... whatever ...
    } else if (strncmp(tok, "Temp", 4) == 0) { // tok is Temp25
        // ... whatever ...
    } else if (strncmp(tok, "Humidity", 8) == 0) { // tok is Humidity55
        // ... whatever ...
    } else if (strncmp(tok, "CC", 2) == 0) { // tok is CC5#
        // ... whatever ...
    }
    tok = strtok(NULL, ","); // Note: NULL, not IncomingString
}


Modifying normal doorbell to get notification I'm really not used to Arduino and I would like to know if it would be possible to tweak my doorbell, most specifically the bell itself, to embed a small arduino that would be able to send a notification "somewhere" (well, if it can connect to wifi and send an HTTP request I can handle the rest).

I'm guessing that there will be electricity in the bell itself (to.. ring it I guess) so I could use that to power the Arduino.

My goal is definitelly not to create a "smart" doorbell but to upgrade a tiny bit the one we already have. My biggest problem is that when I am in the office, I can barely hear it and if I turn music on, it becomes impossible.

Before launching myself in this, I'd like to know if it is at all possible. I can (try to) provide more information if needed.

Thanks.

EDIT: I'm guessing that the bell rings when it gets an electric signal when the button at the door is pressed. My goal would be to hook up to that signal to get the arduino to send an HTTP request. Now, my arduino knowledge is very limited and I'd like to see if anyone could give a tiny bit of guidance on how to proceed (which one, which module, ...)

EDIT2: As requested, here is a picture of the bell part:
[![bell][1]][1]

In the center there is a copper coil so I would guess that when someone presses the button, the little hammer (pointy thing going up) hits the 2 metal plates (up and down). I could also see that there is a third cable (purple) hidden behind that is not currently used but I have no clue what it is for or if there is power at all on this thing...

EDIT3: I realized that I have a Friedland D780 on the fuse box (so right next to all the power I can need for an Arduino). It is unclear if I could get the pulse from here though. Anyone?

I can't upload a picture with my phone but I'll add it ASAP...

[1]: https://i.stack.imgur.com/pdgbs.jpg

Many (most?) household doorbell systems in the US are powered by a simple transformer that converts 120V AC household electric supply to a lower voltage AC. Often 16V AC or 24V AC.

The coil and hammer form a device called a solenoid. When the coil is energized, the hammer (often also called a plunger) is forced in one direction, either up (against gravity) or against a return spring, striking one of the plates. When power is removed, gravity or the return spring pull the plunger back to the rest position, striking the other plate, forming the familiar ding-dong sound.

Power is applied or removed extremely simply -- by the momentary, normally-open pushbutton at your door. When you press the button, the solenoid is energized, and when you release it, the device returns to the normal state.

With regard to powering your Arduino, it is important to understand the difference between AC and DC power. The Arduino requires DC (direct-current) of either a regulated 5V DC into the 5V pin, or unregulated 7-12V DC into the VIN pin, or the regulated 5V DC from a USB device.

I don't know your level of electricity understanding, but there exists quite a bit of information on the difference between AC and DC power. Suffice it to say, you would need some additional circuit to rectify and filter and regulate the 16-24V AC into something between 5V and 12V DC.

Then, there is the issue of the loss of a good power tap while the button is pressed. If you measure the voltage across the contacts of the pushbutton while it is not pressed, you will likely find the full 16V AC or 24V AC, but if you measure those contacts while the button is pressed, you will read 0V AC. This means that tapping off of the pushbutton wires is not a good way to power a device that needs to remain on while reacting to the button press. Whether or not you could tap power off of the solenoid terminals is dependent on the voltage drop across the coil, and still you have the issue to convert the AC to DC at the proper voltage.

If this doorbell is near the ceiling, you will likely find the transformer mounted in the attic space above the ceiling near the doorbell (if there is attic space -- depending on your specific setup).  If there is a power outlet in this attic space, you could plug in a good quality AC-DC 5V adapter there to power the Arduino in the attic. The Arduino will need to remain electrically isolated from the doorbell circuit. To detect the pushbutton press, you could use a current transformer measuring the current flow through either of the 16V AC wires coming off of the transformer (measure with one of the the analog inputs of the Arduino), or with an Opto-isolator, with the transmitter connected to the doorbell circuit in a way that delivers a small current (10mA or so normally) to the transmitter side of the opto-isolator, and read the receiver side with a digital input pin on the Arduino.

Unfortunately, interfacing with a doorbell that uses AC power will require some good planning and evaluation of your doorbell system and how much additional circuitry you are willing to apply.

If you aren't careful, working near the transformer can be very dangerous to your life. Working with 16-24V AC will not be as dangerous to your life, but can easily damage the Arduino beyond repair in the flash of an eye. Take great care.


How to download files from a user/password protected web server (user:passw@ip:port) I need to do a GET request in the form: user:passw@ip:port/streaming/channels/1/picture  to capture a still frame from an Ip camera.
Is there a way to do this with the ESP8266HTTPClient.h library?

The samples show a GET request as: http.begin(host,port,url);
What I need to do is get the user:passw@ put in before the host:url

use the http.setAuthorization(user, passw) method.


Script on pc only gets 640 characters via serial I experience that if the Arduino (Teensy 3.2) writes a rather long stream of characters to serial, the python script on the other end only receives the first 640 characters. I have found this result both by printing chars, printing lines and by using ArduinoJson's prettyPrintTo(Serial).

Note, that it does not matter what chunks of characters I read in the Python scripts, whether it is read(5) or read(1000).

With the Arduino Serial Monitor, I get all the data, ie more than the 640 characters.

From what I can understand, it is not possible for a sketch to write "too fast" or "too much" to the serial, so there must be something on the pc side receiving the data. However, the Python script for some reason does not get all the data.

What is the problem here? Where should I look for the problem/solution? Perhaps this is more a Linux or Python question, but I will try here.

Sketch - printLines()

void printLines() {
  for (int i=0; i<100; i++) {
    // length below is 40 incl end of line character
    Serial.printf("abcdefthijklmnopqrstuvxyz123456789--%03d\n", i);
  }
}

void setup() {
  Serial.begin(9600);
  delay(500);
  printLines();
  //printChars();
  //printJson();
}

void loop() {}

Sketch - printChars()

void printLines() {
  for (int i=0; i<1000; i++) {
    Serial.write('x');
  }
}

Sketch - printJson()

void printJson() {
  StaticJsonBuffer<10000> jsonBuffer;
  JsonArray &root = jsonBuffer.createArray();
  for (int i=0; i<700; i++) {
    root.add(i);
  }
  root.prettyPrintTo(Serial);
}

Python script

import serial

ser = serial.Serial('/dev/ttyACM0')
ser.timeout = 0.5

# PARAMETERS:
# (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
num_chars = 100
num_iterations = 10

chars_read = 0
for i in range(num_iterations):
    s = ser.read(num_chars)
    chars_read += len(s)
    print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
        % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))

Terminal output

jan@jan:~/Desktop/batlogger/localserver$ sudo python localserver.py
### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
### i: 2, reading 100 chars, char 200 to 299, len(s): 100, total chars: 300
### i: 3, reading 100 chars, char 300 to 399, len(s): 100, total chars: 400
### i: 4, reading 100 chars, char 400 to 499, len(s): 100, total chars: 500
### i: 5, reading 100 chars, char 500 to 599, len(s): 100, total chars: 600
### i: 6, reading 100 chars, char 600 to 699, len(s): 40, total chars: 640
### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 640
### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 640
### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 640

You are not using a serial connection, you are using a USB CDC/ACM connection, and that is a very very different thing.

With a serial connection when you send data it gets sent regardless of whether there is anything listening for it - the TX IO pin toggles high and low regardless.

However, with a CDC/ACM connection it's only possible to send data when there is something actively listening at the remote end - that is, when the port /dev/ttyACM0 has been opened by an application.

Until that port has been opened any data sent will remain in internal buffers.  These buffers are 64 bytes each in size (that's the size of a CDC/ACM packet), and there are (I would guess) 10 of them on the Teensy3.  After these buffers are full, because there is nothing receiving the data, there can never be any more room made for more data, so instead of blocking like a serial connection does it just discards the data.

So you have filled the buffers with 640 bytes of data and thrown away the rest.  That data just sits there.

Then eventually you open the /dev/ttyACM0 port and the Teensy3 is now able to send CDC/ACM packets through the USB.  And it has 10 of those packets sat there waiting to go out, so it sends them.  So you receive the 640 bytes of data that you had buffered up.

Your mistake is basically not waiting for the port to be opened before sending data to the remote end.  You can test the state of the port (kind of, but that's a whole other subject) by examining the Serial object:

if (Serial) {
    // ... the port is open
}

In general you can usually just wait at the start of your program before starting anything else with a simple while:

while (!Serial); // Wait for the port to be opened


Sending data by nRF24L01 with Arduino Can I send data using nRF24L01 with Arduino through multiple pipes?
As by using the RF24 library, I can send data through just one pipe and receive on the 6 pipes that nRF24L01 has.

Yes, but the nRF24L01 can only transmit one message at at time, since it only has one buffer.

So roughly speaking, for each message

Set the transmit pipe address (if different than the last one)
Send data
Wait for completion (and ack or failure, if in that mode)


use more then one timer I'm working on Arduino uno and trying to use more then one timer.
I'm using timer1 for my software watchdog (I needed bigger interval for that, so my program won't reset itself after 8 seconds).
In addition, I'm using timer2 for regular interrupt like turn off pin after 8 seconds.
The problem is that the timer1's interrupt override timer2's interrupt.

Is it possible to to use both of them?

In general, once an embedded processor's interrupt fires, the interrupt routine clears the interrupt.  Usually inside the interrupt routine.  Failure to clear the interrupt normally inhibits further interrupts.

That said, in the Arduino paradigm, this is "taken care of" by the Arduino Timer library described here.  In the example code:

/*
 *  Timer1 library example
 *  June 2008 | jesse dot tane at gmail dot com
 */

#include "TimerOne.h"

void setup()
{
  pinMode(10, OUTPUT);
  Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
  Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}

void callback()
{
  digitalWrite(10, digitalRead(10) ^ 1);
}

void loop()
{
  // your program here...
}

...you can see that the example does not actually contain "the" Timer interrupt routine but rather a callback() routine which the Timer library calls when the Timer interrupt occurs.  Code to clear the Timer interrupt is missing and assumed to be in the Timer library.

Consider this if you are writing you own interrupt routine instead of using the Arduino's Timer library.

I'm going to have to call foul on myself.  Clearing interrupts in their own interrupt routine is very common.  But looking at this page, where the Atmel timer hardware is directly controlled (that is, the normal Arduino Timer library is not being used) and the real interrupt handler exists in the sketch, I see where this is not done.  So, for the Atmel, there must be at least one timer mode where the timer interrupt does not have to be clear for the interrupt to happen again.

If you are using the Arduino's Timer library consider this warning from the Timer's library web page linked to above:

  Be careful about trying to execute too complicated of an interrupt at
  too high of a frequency, or the CPU may never enter the main loop and
  your program will 'lock up'.

Finally, hardware timed interrupts are normally reserved for operations which are time sensitive and occur much faster than executing code can handle.  For events that happen on the order of seconds, most applications setup 1 timed interrupt to count off a convenient interval.  Say 1 second.  Code is used to keep count and call the proper functions at the intended time.