.elf and .hex equivalency? (code, eeprom, fuses, and lock bits all in one) I have all configurations (eeprom data, fuses, lockbits) of my ATMega168A together with the code in my C files. The compilation creates an elf file that I use as an all-in-one programming file for production.

Just as a tryout, I converted the elf file to hex with avr-objcopy and saw that the code and configurations are still there (why wouldn't they).

My question is, if the two files are equivalent in case of using them for all-in-one programming. Is there any critical data stripping taking place between elf-to-hex conversion that could affect the actual programming?

Also, I tried again to convert the hex file to bin and saw again the same thing but of course with zero-padding. Except for the obvious different of file size, is there any practical difference when using the bin file and the hex file? Does this padding create any problems? (For example trying to write 0 to addresses that do not exist).

Thank you in advance.

My question is, if the two files are equivalent in case of using them for all-in-one programming. Is there any critical data stripping taking place between elf-to-hex conversion that could affect the actual programming?

Nothing critical, but data stripping does take place. Everything that is in the HEX file is in the ELF file. That is - all the compiled machine code and data.

Basically everything that gets written to the chip is in the HEX file, and the HEX file can be created from what is in the ELF file - ergo the ELF file contains everything that is in the HEX file.

However, not everything that is in the ELF file goes into the HEX file.

The ELF file contains a huge amount more information. Mostly that information is geared towards debugging. There are things like the names and locations of all the symbols in the code - that is, the functions and variables, etc. There are breakdowns of all the assembly instructions grouped by source code file and line number.

None of that is relevant for the Arduino environment, but when you're using professional tools to do your development you can use them for realtime debugging and tracing of your program while it's running on the real hardware.

None of that is relevant to putting your program on the chip. It's all used by the PC.


Change format preferences for Arduino IDE in Linux How can I change Arduino IDE preferences for formatting? I found the preferences file: <user>/.arduino15/preferences.txt, but there are no lines that control IDE formatting. In Windows there is a special file for formatting: <ArduinoIDE_folder>/lib/formatter.conf.

It happened, that my formatter.conf was in /usr/share/arduino/lib/. So I copied it to /home/<user>/.arduino15/ folder and made changes that I needed. And also:

  Copy it in the same folder of file "preferences.txt" and modify the copy. This way, you won't lose your custom formatter settings when upgrading the IDE.


Voltage changes but digitalRead always HIGH I developed simple push button project
I used wemos D1 mini
I connected D3 pin to pull down 1K resistor.

I used multimeter to measure D3 pin voltage.

When i push the button, D3 pin voltage changes from 0.x volt to 4.x volt

But digital read on D3 always return HIGH.

Please help me find the problem. Thanks in advance

This in my sketch :

int ledPin = D2; // choose the pin for the LED
int inPin = D3;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status

void setup() {

  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
}

void loop(){

  val = digitalRead(inPin);  // read input value
  if (val == HIGH) {
    digitalWrite(ledPin, LOW);
  } else {
    digitalWrite(ledPin, HIGH);
  }
}

The problem is that when the button isn't pressed, the voltage at pin D3 is just floating. Since there is nothing attached, the voltage at the pin can be anything. To prevent this, you use a pull-down resistor, so that when the button isn't pressed, the voltage at D3 is pulled to ground, and you will get a LOW using digitalRead.

simulate this circuit – Schematic created using CircuitLab


How to make ESP8266-1S module work on Arduino Uno? I currently have an Arduino Uno with an ESP8266-1S. However I can't make them work... I use the ESP8266wifi.h library and its connection functions do return a true (returns true when received a valid IP), but I can't find it in my network...

When I send 'AT' ending with CR and NL on 115200 baud I still don't get a response.

Also, do I have to connect RX with RX and TX with TX or RX to TX and vice versa?

And also, do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX.

So this is how my board looks like:

So what am I doing wrong?

do I have to connect RX with RX and TX with TX or RX to TX and vice versa?

If you want to do serial communication between a sketch running on the Arduino and the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to TX on the ESP8266.

If you want to do serial communication between the Serial Monitor on your computer through the USB port on the Arduino to the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to RX on the ESP8266.

TX stands for Transmit and RX stands for Receive. So it makes sense that you should connect the transmit pin to the receive pin in the first case. But why connect transmit to transmit and receive to receive in the second case? The reason is that you are not communicating between the main microcontroller (ATmega328P on the Uno) and the ESP8266. You are communicating between the USB-serial chip on the Uno (usually ATmega16U4 on the official Arduinos or CH340 on the clones) and the ESP8266. The main microcontroller is not being used at all, you're just using the Arduino as a bulky and inconvenient USB-serial adapter.

In fact some people will go so far as to remove the ATmega328P from their DIP Unos for this purpose. The RX pin on the USB-serial chip is connected to the TX pin on the main microcontroller as well as the TX header pin and vice versa for TX pin on the USB-serial chip. This means by connecting the ESP8266's TX pin to the TX pin on the Uno's header you are actually connecting it to the RX pin on the USB-serial chip. I would highly recommend getting a USB-serial adapter made for this purpose rather than trying to use an Arduino. You can buy FTDI FT232 or CH340 breakout boards on eBay or Aliexpress for < $2 USD w/ free shipping.

  do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX

This is actually two questions. Let's address the easy one first. The TX pin of the ESP8266 is going to put out around 3 V. Even though the ATmega328P is running at 5 V this will still be seen as a high so no level conversion on that pin is necessary.

Now for the question of whether it's needed on the ~5 V level from the Arduino to the ESP8266 RX pin. There's a lot of disagreement on the question of whether the IO pins on the ESP8266 are 5 V tolerant. We certainly know that it's possible to connect the ESP8266 to 5 V levels as there are many projects published online that do this but the question is will this will shorten the life of the ESP8266?

The datasheet for the ESP8266 does not say the inputs are 5 V tolerant. There is a statement on the ESP8266 forum from a member of the Espressif (creator of the ESP8266) staff:
http://bbs.espressif.com/viewtopic.php?t=1145

  We donot recommend you to apply 5V to IO.

We have a comment from someone on Facebook named "Teo Swee Ann" who appears to be the CEO of Espressif:
 https://www.facebook.com/groups/1499045113679103/permalink/1731855033731442/?comment_id=1732364133680532

  i can reply officially here: it is 5V tolerant at the IO. while the supply voltage is at 3.3V.

So there is conflicting information and none of it has been presented in the most official manner, such as actually putting it in the datasheet. One thing we do know for sure, you will not harm the ESP8266 with 3.3 V levels. So the safest option is to avoid giving it 5 V inputs. However, as you are currently struggling just to get the most basic communication working the extra complication introduced by adding level shifting circuitry may not outweigh the possibility of reducing the life expectancy of your ESP8266.


Using pointers with Arduino I am learning about pointers.

I was wondering how the memory address is defined in programming. I get different outputs depending on the format I choose for memory address. So I was wondering if it is correct to assume that the format of the memory address is defined by the programmer. I get different results for memory address when I use Serial.print( (long) &ptr1, DEC); and Serial.print( (long) &ptr1, HEX);

 #include <stdio.h>
 int counter = 0;
   void setup() {
    Serial.begin(9600);
   int test1 = 10;
   float test2 = 3.14159;
   char test3[ ] = "This is a character array";
   int *ptr1;
   float *ptr2;
 char *ptr3;
  ptr1 = &test1;
Serial.print("The integer value is stored at ");
Serial.print( (long) &ptr1, DEC);

 Serial.print("The integer value is stored at ");
  Serial.print( (long) &ptr1, HEX);

  }
 void loop() {

    }

My output is:

The integer value is stored in  2296

The integer value is stored in  8f8

You're printing the address of the pointer, not the contents of the pointer.

Say you have the memory map of:

100 20       test1 low byte
101 0        test1 high byte
102 100      ptr1 low byte
103 0        ptr1 high byte

test is located at address 100 and takes two bytes. ptr1 is located at 102 and takes two bytes. ptr1 contains the address of test (100) and test1 contains the value 20.

The different possible combinations of prints are:

Serial.println(test1);  => 20 (contents of test1)
Serial.println(&test1); => 100 (address of test1)
Serial.println(ptr1);   => 100 (contents of ptr1 = address of test1)
Serial.println(&ptr1);  => 102 (address of ptr1)
Serial.println(*ptr1);  => 20 (contents of address pointed to by ptr1).

(note: some of those will require a cast in order for the C++ to select the correct println() overload function.)


Error with Sparkfun MP3 Shield and Arduino Due playing music files The code worked on my Ardino Uno. I plugged it up the exact same way and am now getting an error.

Here is the error I get when I try to upload my code to the due:

Arduino: 1.8.5 (Windows 10), Board: "Arduino Due (Programming Port)"

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In static member function 'static void SFEMP3Shield::refill()':

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:1984:7: error: 'sei' was not declared in this scope

   sei();

       ^

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2006:9: error: 'cli' was not declared in this scope

     cli(); // allow transfer to occur with out interruption.

         ^

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In member function 'void SFEMP3Shield::SendSingleMIDInote()':

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2053:7: error: 'cli' was not declared in this scope

   cli(); // allow transfer to occur with out interruption.

       ^

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2067:7: error: 'sei' was not declared in this scope

   sei();  // renable interrupts for other processes

       ^

exit status 1
Error compiling for board Arduino Due (Programming Port).

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Here is my code:

#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>

SdFat sd;
SFEMP3Shield MP3player;

const uint8_t volume = 10; // MP3 Player volume 0=max, 255=lowest (off)
//10 for normal 50 for testing

const uint16_t monoMode = 1;

void setup() {
  initSD();
  initMP3Player();
}

void loop() {
  if(!MP3player.isPlaying()){
    MP3player.playTrack(1);
  }
}

void initSD() {
  if(!sd.begin(SD_SEL, SPI_HALF_SPEED))
    sd.initErrorHalt();
  if(!sd.chdir("/"))
    sd.errorHalt("sd.chdir");
}

void initMP3Player() {
  uint8_t result = MP3player.begin();
  MP3player.setVolume(volume, volume);
  MP3player.setMonoMode(monoMode);
}

The library is written for the Uno, not the Due. It relies on two instructions that are only available in the AVR compiler.

Newer versions of the core provide a pair of macros, interrupts() and noInterrupts() that should be used in place of sei() and cli() respectively, which should be provided by the Due's core as well to make it cross-platform. However that library has never been updated to work with those macros.

You could replace the sei() and cli() calls in the library with interrupts() and noInterrupts(), however that may not make it work, since it was written with the Uno and other AVR based chips in mind.


Errors seen whilst compiling with AdaFruit Motor Shield ("invalid library") Whenever I compile a sketch, change the Tools > Board selection, or open/close Boards Manager/Library Manager I get the following message in the console:

> WARNING: Spurious .github folder in 'Adafruit Motor Shield library' library
> WARNING: Spurious .github folder in 'Adafruit Motor Shield V2 Library' library
>
>
> Invalid library found in
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master:
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master
> Invalid library found in C:\arduino-1.6.8\libraries\robotarm:
> C:\arduino-1.6.8\libraries\robotarm Invalid library found in
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master:
> C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master
> Invalid library found in C:\arduino-1.6.8\libraries\robotarm:
> C:\arduino-1.6.8\libraries\robotarm

Arduino IDE 1.6.6 and higher are picky about what you have in your libraries folders. There are two general valid library formats, the old "pre-1.5" format and the newer 1.5 format, the specification of which is at https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification.

Any folder in any of the Arduino libraries folder that doesn't follow a valid library format will cause the "Invalid library" message. Common causes of this issue are:

Putting a sketch folder in the libraries folder. Libraries may
contain example sketches but a sketch by itself is not allowed.
Libraries that are in a subfolder, rather than the library folder
being in the root of the libraries folder as required.

Now lets look at your specific messages:

Invalid library found in C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master: C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master

By looking at the Adafruit-Motor-Shield-for-Arduino repository we see that it's not a library but the PCB design files for the shield and thus has no business being in the libraries folder. Please move it to a different location.

Invalid library found in C:\arduino-1.6.8\libraries\robotarm: C:\arduino-1.6.8\libraries\robotarm

Without being able to see what's in this folder I can't say exactly the problem. If you will provide a directory listing I could update this answer with specific directions. As it is now, that folder is doing you no good in the libraries folder.


Arduino web server: redirect to mobile site on SD card? Is there any way to have an Arduino web server redirect the client to a file on the SD card only if the client is using a mobile browser?

(My arduino server is already successfully serving pages on http://192.168.0.180, and successfully processes GET requests).

I was thinking of having this javascript code on the main page that's served by the arduino:

<script type="text/javascript">
  <!--
  if (screen.width <= 800) {
    window.location = "http://192.168.0.180?mobile";
  }
  //-->
</script>

My first thought was that maybe it's possible for the server to process that GET request and then serve a page from the SD card, instead of the regular page it serves.

Do you think this is possible, and how would you recommend to do it?

Yes, it is perfectly possible. you just have to look at the right bits.

Fundamentally there is no difference between an Arduino and any other website, it's just somewhat simpler in how it operates.

All browsers follow the same rules - if they didn't they wouldn't work on the web.  Two of the rules you are interested in are:

Browsers identify themselves along with their OS.
Browsers respond to the "result" code the website provides in a specific way.

Besides the GET request a browser also sends a list of headers.  These contain lots of extra information about the request, including the domain name of the website that is being accessed (so the web server knows which site you want - it's not one webserver per site, that would be impractical.  For instance, the request to show this page from Firefox on Linux has these headers:

Host: arduino.stackexchange.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.6.0
Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: (I won't bore you with this lot)
Connection: keep-alive

The header of note is the User-Agent: one.  That tells the web server that I am using firefox from a 64-bit Intel Linux computer.  If I were to do it from my Android phone it would tell you it's from Chrome on Android.

By looking for that header and parsing it for certain keywords you can find if you're serving to a mobile device or not.

Now the second bullet above - browsers respond to the response code in different ways.  Normally you send the response code 200 which means "I accepted your request and here is the page you asked for".  Another response code that is useful is code 301 which means "The page you asked for isn't at this address any more - here is the new address you should go to instead".  That will then cause the browser to go to the newly provided address instead.

So instead of responding with

HTTP/1.0 200 OK
Content-type: text/html

<web page content here>

You could instead respond with:

HTTP/1.0 301 Moved Permanently
Location: http://myarduino.local/mobile

And the browser will redirect to the new address you give in the Location: response header.

The full list of response codes is here: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

If you want to avoid the overhead of a browser redirect you can just serve different data to the browser depending on what the User-Agent header specifies.  After all, it's entirely down to you what is sent as the content of the page.  Whether you get that from purely programmatical means, or by reading a file off an SD card, is entirely up to you.


Port manipulation in Arduino using byte value I'm trying to write PORTB and PORTD in ATmega328P using byte system like this,

    //  PD7  PD6  PD5  PD4  PD3  PD2  PD1  PD0
    //  N     N    N    N    N    U    U    U
    //  7     6    5    4    3    2    1    0
    //======================================
    //  PB7  PB6  PB5  PB4  PB3  PB2  PB1  PB0
    //  X     X    1    1    1    1    1    1
    //  C     C    13   12   11   10   9    8
    //======================================
    //C-Crystal Pins/U-Un used/N-Used/X-unknown value

    byte pins[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};

    //uint16_t style1=1365; //10101010101
    //uint16_t style2=682;  //01010101010

    void setup() {
      for (int i = 0; i < 11; i++) {
        pinMode(pins[i],OUTPUT);
        PORTD=B00000000;
        PORTB=B00000000;
      }

    }

    void loop() {
      PORTD=B10101000;
      PORTB=B00101010;
      delay(1000);
      PORTD=B01010000;
      PORTB=B00010101;

    }

According to this , Port value should be swapped.
But, It's still remaining given value of the code before delay()

What is the problem in this code?

What is the problem in this code?

No problem, it does change the bits of port D and B from 0B10101000 and 0B00101010 to 0B01010000 and 0B00010101 respectively.

However, microseconds later loop() runs again and changes them back to  0B10101000 and 0B00101010 for a full second.

To better see what's happening, add a second delay(1000); statement, placing it just before the closing brace.


Sending data to UART using Atmel Studio with Attiny84 I want to send data to TFDI. It can be hello world or any value of variable. But I can't do. I haven't found example code on the internet. Some examples doesn't work. I am using Atmel Studio.

The ATTiny84 does not have a hardware UART peripheral. Instead it has a USI (universal serial interface), which does not have all the capabilities needed for UART ("serial") interface.

You don't need to burn the Arduino bootloader to use libraries, that were written for the Arduino IDE. You only might need some of the definitions, which you can get by including the arduino.h file.

I think your best bet is to use existing libraries, like the SoftwareSerial library. There are also lots more libraries, that provide bit banged serial interfaces. You can also get them running in Atmel Studio, by including the source files. This is the easy way.

If you want to go the hard way, you might be able to program a hybrid software/hardware UART interface by utilizing some functions of the USI. In a search I found this site, which is about implementing UART with the USI. They also link to Atmel's Application Note  AVR307, which is a good source for understanding this. From this starting point you might also find a ready to go implementation for the USI. If not, you will have to do the work yourself.


Big endian or little endian? I need to pass a 16-bit long address (for an external EEPROM) to a function (twi_writeTo) in a buffer.
I am currently doing this

byte buffer[2];
buffer[0] = (byte)(eeaddress >> 8);
buffer[1] = (byte)(eeaddress & 0xFF);

where eeaddress is an unsigned int with the address.

I then do

int8_t ret = twi_writeTo(eeprom_i2c_addr, buffer, 2, 1);

Before I tried

int8_t ret = twi_writeTo(eeprom_i2c_addr, (uint8_t*)&eeaddress, 2, 1);

but that returns garbage. Probably the byte order is swapped. Is that the case?
And if so, is there a better way than copying the two bytes to a buffer?

If it's the byte order that causes a problem that's likely compiler specific and I don't think one can change it. Even if it were possible, changing the global endianness might break libraries that depend on it, so you likely can't escape using a function to swap the variable.

If you know you only need one value at a time you could write something like the following code, with a global buffer (untested but in principle should work (and I know global variables are evil, but should work for an Arduino project)):

byte buf[2];

byte* reverse(int val) {
    buf[0] = (byte)(val >> 8);
    but[1] = (byte)val;
    return buf;
}

So you could use it like:

int8_t ret = twi_writeTo(eeprom_i2c_addr, reverse(eeaddress), 2, 1);


GPRS shield - Hayes commands to identify a faulty SIM connection I'm currently battling with a LinkSprite GPRS shield (it's based on the SIMCom SIM900 chip) and seem to have absolutely no luck trying to connect to the network.  I've got two SIMs, both of which should be active, but I cannot get the connection light on.

I've got a serial connection going and it's responding to various AT commands, but I can't connect:

  AT+COPS=?

is working, and giving me a list of networks, so I think my antenna is good, but

  AT+COPS=-whatever-

immediately gives me +CREG: 3.

I'm now wondering whether there's a fault with my board, and that it's not seeing the SIM cards.  A few commands that I thought would work aren't, for example:

  AT+CPIN?

just returns ERROR

Similarly, when trying to read SMS data:

  AT+CMGL="ALL"

returns ERROR.

Have I proved that the board isn't seeing the SIM, or is there something definitive I can try?

Thanks in advance!

Having exchanged the board for another one (that works!) I can now confirm that the calls above (e.g. AT+CMGL) should work if there is a working SIM connection.


I am working on a thermometer and humidity why am i getting this error Arduino: 1.8.9 (Windows 10), Board: "Arduino/Genuino Uno"

In file included from C:\Users\Admin\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.cpp:15:0:

C:\Users\Admin\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.h:36:29: fatal error: Adafruit_Sensor.h: No such file or directory

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

This indicates your IDE is missing the "Adafruit Unified Sensor" library as outlined here.

To install it, select "Tools" -> "Manage Libraries" and search for "Adafruit Unified Sensor". You can install the library by selecting it and pressing "Install".


Trying to run two simultaneous loops that do the same task with different delay cycles I'm trying to control a pellet stove auger motor in such a way that I can use a toggle switch to do High/Low (H/L) - so the way that I have it now is:

 void setup() {
   // initialize digital pin 13 as an output.
   pinMode(13, OUTPUT);
   pinMode(12, OUTPUT);
}

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

Which is just LED on/off but it also controls another relay that controls the blower motor - what I'm trying to set up is a H setting that would be the 2850 delay-ON - and then have say: pin 11 have a delay-OFF of 7000, and have pin 13 still resetting to the delay-ON of 2850.

What I mean is:

loop A: pin12 on -delay 2850 pin12 off -delay 11250
loop B: pin13 on -delay 2850 pin13 off -delay 7000

I saw and tried the code for 'multi-blink' - as the one I use is pretty much modified 'blink'.

Any assistance would be awesome - I run the one I show above now, on my pellet stove and it was recently -31.4 and worked like a charm, but I'd like to be able to have a high/low option.

PS: I also have a coffee roaster control project as well... help on that one is always appreciated as well.

The Arduino Simple Timer library (and other similar timer libraries) are made for exactly this kind of application. Your setup() routine calls the SimpleTimer library, naming a callback-function and how often it should get called. Your loop function must then call timer.run() reasonably frequently (where
reasonably frequently" depends on the timing accuracy and jitter tolerance of your application). timer.run() will call each of your callback-functions at its appropriate time. You write the callback-functions to do whatever you need them to do when the timer calls them.

There are one-shot timers and repeating timers - it sounds like your application could one of each per LED: One that fires periodically, to to call a turn-on-LED12 function every (ON_TIME_12+OFF_TIME_12) ms, and a one-shot that calls a turn-off-LED12 function, started by the turn-on-LED_12 function for (ON_TIME_12) msec. Same for LED13, ( ..., etc.)

Your loop function is free to do whatever else, as long as it calls timer.run() frequently enough that your application can meet its timing requirements.


Arduino Christmas light project with dimmer I have an existing project using an Arduino Yun that controls Christmas lights with relays to turn them on/off. There are currently 13 separate rows of lights on the (60 foot) tree, each plugged into a wall wart that's controlled by its own relay.

I'm considering adding the ability to dim the lights, so I wanted to figure out the best way to do it. The lights can all be dimmed "in unison" - there's no need for 13 seperately controlled dimmers. But I have to be mindful not to cause any "buzzing" in the audio equipment on stage where the tree is.

I've read about PWN, zero cross, and other terms and saw the zero cross tail from powerswitchtail.com that seem useful in the typical project. I'd like to be able to pull this off with no more than 2 "dimmers" for the whole project, if possible.

Where do I start, and how do I do it?

I can think of a couple of ways to approach this:

Use a DMX dimmer, something like this 4-channel dimmer, or
Use an household X10 dimmer.

DMX is used for stage lighting and there is some information on controlling DMX devices with an Arduino in the Playground where there is also some information on the hardware interface and shields, it looks pretty simple. DMX is a differential RS485 interface.

X10 is used for home automation, the signaling is done over the AC line. There is some information on using X10 and an Arduino library in the Tutorials.

Both seem like viable approaches, if you're working in a theater it is likely that they might already have DMX equipment and it would be as simple as hooking up to the gear in the house. Then you'd only need to add a shield or build the interface hardware.


LED strip and SD card My problem is simple yet extremely problematic. For some reason, I cannot interact with an SD card and a LED strip at the same time with my arduino. After hours of testing multiple scripts, I am 99.99% that the issue is due to the SPI.h library.
I have tried the simplest LED strip code, such as turning on led number 5. If I include SPI.h, the code does not work, the data LED of the arduino doesn't even light up, the arduino doesn't send anything to the strip data line. If I remove include SPI.h, the code works.
This is really odd, I have read about the SPI.h messing with the pins, so now I'm looking for a solution, to use the SD card module without the SPI library if it is possible.
Here is an example of a code that does not work due to the use of the SPI.h library.

Any help is greatly appreciated, this is extremely odd and problematic.

#include <Time.h>
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#include <SPI.h>
#include <SD.h>

Sd2Card card;
SdVolume volume;
SdFile root;

const int chipSelect = 4;

#define PIN            6
#define NUMPIXELS      400

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB +   NEO_KHZ800);

boolean stringComplete = false;  // whether the string is complete
boolean readarray=false;
String inString = "";
int c=0;
int cc=0;
int led=0;
int i=0;
int j=0;
int pixel_n=0;
unsigned long start;
unsigned long endd;

//char* ledd[]={"", "", ""};
int ledd[3]={0,0,0};

File myFile;

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

Serial.print("\nInitializing SD card...");

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

Serial.println("Ok we're done");
delay(2000);

pixels.setPixelColor(5, (200,200,200)); // THIS DOES NOT WORK
pixels.show(); // THIS EITHER

  Serial.begin(9600);
}

void loop(void) {

}

I had the same problem with using the SD reader with a SPI SRAM. It turns out that the very cheap SD reader cards do not like multiple SPI components on the same port. Since the Arduino has only one SPI, the only thing that worked was to use a SD data logger card.

To add a tristate solution by using two resistors on the MISO line also did not work in my case.

See my post for the post I created regarding this probably similar problem.


Share battery pack with Arduino and DC motors I used 6 rechargable AA batteries (total 7.2V) to power my Arduino (UNO R3) Car's two DC Motors (using L293D IC as motor driver). I used separate 9V battery to power arduino itself. But I want to share same 6 battery pack to power my arduino via barrel jack. Please suggest me how can I do this? What precautions Should I take? Like decoupling capacitors or any other?

You may have read that the UNO can accept 7-12 volts as input power. Your AA battery pack (7.2 volts) is very near the low limit of 7 volts. After just a little discharge of the battery (and also voltage drop from motors running), your batteries are likely to deliver less than 7 volts.

As your AA battery goes below 7 volts, then the 5 volts (regulated) will also begin to go lower.  A reasonable scenario would be if AA battery was 6.5 volts (1/2 volt low), then the 5 volts regulated would be about 4.5 volts. The UNO is likely to operate ok at this voltage, but as voltage goes lower operation could become a problem depending upon your program used.

Since you are experimenting with a toy car, I would say to go ahead and run both the motors and UNO from the same battery pack.  Not a lot to lose on trying.

The UNO already has decoupling capacitors in it's 5 volt regulator circuit.

Just for fun,  you could use an Analog input to measure your 5 volts and if the voltage drops to 4.5 volts, you could dis-allow motor operation and flash an LED (or other action). Just a low battery indicator.

If you decide to measure the 5 volts with an analog input,  read up on using resistor dividers and the Analog reference (A-ref). Because 5 volts dropping to 4.5 volts could effect your analog reading, depending upon what you use for Analog reference.


Alternative code for pinMode()? In my code I need to set five pins to output mode. I have the pinMode() statements in my setup.

I am trying to make my Arduino code run a bit faster, and I came across a tutorial which swaps digitalWrite() for PORTB &= _BV(PB6) (high), and makes it run ~25 times faster.

I'm wondering if there's a similar type of substitution I can do for pinMode(), that will make it run faster as well? Or is pinMode() already a fast command, so I shouldn't worry about it?

Thanks

It isn't worth it for something done once, if you only do it in setup. However if you need to toggle the mode frequently yes it can be done. You sadly haven't said which pins, but assuming they are D2 to D6 (digital pins 2 to 6) on a Mega you can do this to set output mode:

  DDRE |= bit(PE3) | bit(PE4) | bit(PE5); // D5, D2, D3
  DDRG |= bit(PG5); // D4
  DDRH |= bit(PH3); // D6

For input mode you have to "and" in the ones-complement of the bits like this:

  DDRE &= ~(bit(PE3) | bit(PE4) | bit(PE5)); // D5, D2, D3
  DDRG &= ~(bit(PG5)); // D4
  DDRH &= ~(bit(PH3)); // D6

The exact register names are in the datasheet, and the mappings to the pins on your board are in the schematic (available from the Arduino site). The relevant part is this:

The bit numbers are in grey on the left (eg. PE4) and the board pin numbers are in green on the right (eg. 2 is digital pin 2).

The bit macro works similarly to the _BV one you mentioned in your question. It shifts 1 left the required number of bit positions to be in the right place.

A somewhat simpler and more portable solution is to use the digitalWriteFast library which you can download from:

https://github.com/NicksonYap/digitalWriteFast

This uses various compiler tricks to detect if you are using a constant for pinMode and digitalWrite and converts them into the appropriate register manipulation. You just install the library and add Fast to the function names, eg.

pinModeFast (2, OUTPUT);
digitalWriteFast (2, HIGH);


glediator + PL9823 (WS2812B) + teensy = fail? here is what I got:

teensy++ 2.0 with code below
Glediator configured for Glediator_Protocol/Single_Pixels/HL_TL/RGB/B_1000000
led matrix with the PL9823 leds (80 of them)

I first off have to set the code to 160 on the teensy just to get it to                     at least make the leds change. even when i have it set to that OR the 80 leds, it does not show what is on screen (see video below). I have no clue what to try next.

Code

#include "FastLED.h"
#define NUM_LEDS 160
const int dataline = PIN_B4;
CRGB leds[NUM_LEDS];

void setup()
{
    digitalWrite(6,LOW);
    Serial.begin(1000000);
    LEDS.addLeds<WS2812B, dataline>(leds, NUM_LEDS);
    for (int p=0;p< NUM_LEDS;p++)
    {
        leds[p] = CRGB::Black;
        FastLED.show();
    }
}

int serialReadBlocking()
{
    while (!Serial.available())
    {
    }
    return Serial.read();
}

void loop()
{
    while (serialReadBlocking() != 1)
    {
    }
    for (long i=0; i < NUM_LEDS; i++)
    {
        leds[i].r = serialReadBlocking();
        leds[i].g = serialReadBlocking();
        leds[i].b = serialReadBlocking();
    }
    FastLED.show();
}

https://www.youtube.com/watch?v=H6OuMWKtbmo

G'day Guy, What you're building there looks nice. Do you have a circuit diagram you can share? Regarding the code, I've never played with FastLED.h but is the serialReadBlocking how it deals with the input data? Not that it's wrong, just not what I was expecting.

Two things to look at:

Your serial baud rate is a bit odd, 1 million neat. Is that intended? I wouldn't think so. Most common is 9600, I have run projects at 19,200 for giggles, but I doubt that you have it correct there.
I see your project you are using multi coloured LEDs with 3+1 pins which in actual fact means you have 240 LEDs (are the last 80 segments/colours all lighting?). If your PC sending the serial stream is expecting 80x single colour LEDs (80 individual LEDS) but you've got 80x tri-colour LEDs (80x3=240 LEDs) you probably aren't lighting them all up. (I only mention this point because I noticed your PC appeared to be sending only one colour, but that could have just been the moment I saw in the video).

edit: I meant to include this link for the teensy serial baud rate info: https://www.pjrc.com/teensy/td_uart.html


Where to connect BLK and GRN pins of Openlog board on my Uno? I have the following SD card reader on the left side from Sparkfun. In the tutorial they have it connected directly into an Arduino Mini, which has BLK and GRN pins> I would like to connect it to an Arduino UNO. Where do I connect these pins or can I ignore them? Thanks for your help.

If you read the page about the OpenLog board you can see (on the schematic link) what the pins mean:

I've added the labelling on the board in blue.  The GRN pin (DTR in the schematic) is actually an input, which resets the chip:

Thus:

GRN should be connected to RESET on your Uno, so that when you reset the Uno, you rest the OpenLog.
TXO (transmit out) on the OpenLog would be connected to serial input on the Uno (ie. digital pin D0 - labelled RX).
RXI (receive input) on the OpenLog would be connected to serial output on the Uno (ie. digital pin D1 - labelled TX).
You can see that GND and BLK are both ground pins, and thus should be connected to ground.
VCC (RAW on their schematic) is the voltage input to the 3.3V very-low-dropout voltage regulator MIC5205 on the OpenLog. This will accept input voltages in the range 3.3V to 12V. (The datasheet seems to suggest a maximum of 16V, but it might get rather hot if you did that). Connecting VCC to +5V on the Uno would be satisfactory.


Programming standalone 328P in circuit I am designing a PCB using a 328P. As I understand it, I can either flash the chip via the ICSP header (without bootloader) or via Serial (if it has a bootloader already). But how does programming actually work?

According to my program running on the chip, it acts as master for SPI peripherals. If using ICSP, how does the chip know that it is supposed to act as SPI slave and receive a program?
Is there anything I must take into account with regards to what is connected to the SPI pins? i.e. does it harm in any way if I have other SPI slaves on the board connected to these same pins?
Same for serial programming: how does the chip know that it's supposed to receive a program on the serial interface, when my application uses this port for a different purpose?

According to my program running on the chip, it acts as master for SPI peripherals. If using ICSP, how does the chip know that it is supposed to act as SPI slave and receive a program?

A special signal is sent using the RESET pin. From the datasheet (p361):

  Power-up sequence: Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems, the programmer can not guarantee that SCK is held low during power-up. In this case, RESET must be given a positive pulse of at least two CPU clock cycles duration after SCK has been set to “0”.
  Wait for at least 20ms and enable serial programming by sending the Programming Enable serial instruction to pin MOSI.
  The serial programming instructions will not work if the communication is out of synchronization. When in sync. the second byte (0x53), will echo back when issuing the third byte of the Programming Enable instruction. Whether the echo is correct or not, all four bytes of the instruction must be transmitted. If the 0x53 did not echo back, give RESET a positive pulse and issue a new Programming Enable command.

  Is there anything I must take into account with regards to what is connected to the SPI pins? i.e. does it harm in any way if I have other SPI slaves on the board connected to these same pins?

Yes. It is possible that a chip may respond to the ICSP signals. You should have pullup resistors on all your CS (or SS if you prefer to call it that) pins on all your slave chips so that while the ATMega328P is in programming mode (and all the GPIO pins are in INPUT mode by default) the CS pins of your slaves aren't floating.

  Same for serial programming: how does the chip know that it's supposed to receive a program on the serial interface, when my application uses this port for a different purpose?

Simple: it listens for 2 seconds after power-on or reset for a special sequence of bytes arriving on the serial port. If they arrive within that 2-second window (8 seconds for ATMega32U4 based boards, to allow time for USB enumeration) the bootloader keeps running and looking for programming instructions. If it doesn't see that start sequence within the timeout period it exits the bootloader and runs your sketch.

The STK500 protocol (which the Arduino bootloader is based around) is detailed here. The trigger sequence is the "CMD_SIGN_ON" command detailed on page 4.


Sensirion library for SHT7x humidity sensor I have following code (and it works great!) for SHT75 Sensirion sensor.

/*
 * Example code for SHT1x or SHT7x sensors demonstrating blocking calls
 * for temperature and humidity measurement in the setup routine and
 * non-blocking calls in the main loop.  The pin 13 LED is flashed as a
 * background task while temperature and humidity measurements are made.
 * In addition, the sensor may be placed in low resolution mode by
 * uncommenting the status register write call in setup().
 */

#include <Sensirion.h>

const uint8_t dataPin =  2;            // SHT serial data
const uint8_t sclkPin =  3;            // SHT serial clock
const uint8_t ledPin  = 13;            // Arduino built-in LED
const uint32_t TRHSTEP   = 3000UL;     // Sensor query period
const uint32_t BLINKSTEP =  250UL;     // LED blink period

Sensirion sht = Sensirion(dataPin, sclkPin);

uint16_t rawData;
float temperature;
float humidity;
float dewpoint;

byte shtState = 0;
byte ledState = 0;

unsigned long curMillis;               // Time interval tracking
unsigned long trhMillis = 0;
unsigned long blinkMillis = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  delay(15);                           // Wait at least 11 ms before first cmd
//  sht.writeSR(LOW_RES);                // Set sensor to low resolution
  sht.measTemp(&rawData);              // Maps to: sht.meas(TEMP, &rawData, BLOCK)
  temperature = sht.calcTemp(rawData);
  sht.measHumi(&rawData);              // Maps to: sht.meas(HUMI, &rawData, BLOCK)
  humidity = sht.calcHumi(rawData, temperature);
  dewpoint = sht.calcDewpoint(humidity, temperature);
  logData();
}

void loop()
{
  curMillis = millis();

  if (curMillis - blinkMillis >= BLINKSTEP) {    // Time to toggle the LED state?
    ledState ^= 1;
    digitalWrite(ledPin, ledState);
    blinkMillis = curMillis;
  }

  switch (shtState) {
  case 0:
    if (curMillis - trhMillis >= TRHSTEP) {      // Start new temp/humi measurement?
      sht.meas(TEMP, &rawData, NONBLOCK);
      shtState++;
      trhMillis = curMillis;
    }
    break;
  case 1:
    if (sht.measRdy()) {                         // Process temperature measurement?
      temperature = sht.calcTemp(rawData);
      sht.meas(HUMI, &rawData, NONBLOCK);
      shtState++;
    }
    break;
  case 2:
    if (sht.measRdy()) {                         // Process humidity measurement?
      humidity = sht.calcHumi(rawData, temperature);
      dewpoint = sht.calcDewpoint(humidity, temperature);
      shtState = 0;
      logData();
    }
    break;
  default:
    Serial.println("How did I get here?");
    break;
  }
}

void logData() {
  Serial.print("Temperature = ");   Serial.print(temperature);
  Serial.print(" C, Humidity = ");  Serial.print(humidity);
  Serial.print(" %, Dewpoint = ");  Serial.print(dewpoint);
  Serial.println(" C");
}

How can I extend it for two sensors (by using of another pins, of course)?

You simply create a second instance of the object with different pins and store the result in a different set of variables. Any extra logic of when to do what is purely down to you.


Servo FS5106B does not work properly I was testing out my new Servo FS5106B. Here is the code I used:

#include <Servo.h>

Servo servo;
void setup()
{
    servo.attach(10);
}

void loop()
{
    servo.write(0);
    delay(1000);
    servo.write(180);
    delay(1000);
}

After I upload the sketch, the console says:

  Sketch uses 2872 bytes (1%) of your device memory. Total available 253952 bytes. Global variables use 161 bytes (1%) of the dynamic memory, leaving 8031 bytes for local variables. Maximum 8192

The delay between the rotations wasn't 1 second (as I was expecting), but 13 seconds (when I connect only a LED and use the delay function, everything works perfectly). Why is that happening?

P.S The power source for the servo is my Arduino-Mega 2560, wich outputs 5V. The model I use for wiring is:

Edit 1:
I tried to execute the program that @ChrisStratton suggested, here an updated code

#include <Servo.h>
#define led 22

Servo servo;

void setup()
{
    Serial.begin(9600);
    while(!Serial)
        delay(10);

    Serial.println("Start!");
    pinMode(led, OUTPUT);
    servo.attach(10);
}

void loop()
{
    digitalWrite(led, HIGH);
    servo.write(0);
    delay(1000);
    digitalWrite(led, LOW);
    servo.write(180);
    delay(1000);
}

When this program loads, servo does 2 rotations in 0.4 seconds and the LED goes high and low really fast, then anything changes for another 10 seconds, then again the LED goes high and low and the Servo does 2 rotations

In the official Arduino examples, a servo motor is powered by the 5V pin of the Arduino board. In real life, that is a bad idea.
Your FS5106B has specified about 1A stall current. The average current is less than that, but the start peak current could indeed be 1A.
Could you try to use a seperate power supply of 5V (or 6V) for the servo motor ?

To check if the Arduino resets, you could do a Serial.begin(9600); in setup, directly followed by Serial.println("the sketch has started");

Some servo motors require different timing. That would not explain the 13 seconds delay, so I assume that your servo motor has normal timing.

Do you use a breadboard ? Sending a current peak through a breadboard (with bad contacts) can cause a lot of voltage spikes.

(To the other problem solvers: I'm ignoring the 13 seconds and assume that once in a while the servo motor is able to start, just a guess, I could be wrong).

[ADDED]
@ChrisStratton is trying to tell you this:

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

void loop()
{
  digitalWrite( LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite( LED_BUILTIN, LOW);
  delay(1000);
}

The next step would be:

#include <Servo.h>

Servo servo;

void setup()
{
  Serial.begin(9600);
  Serial.println("The sketch has started");
  pinMode( LED_BUILTIN, OUTPUT);
  servo.attach(10);
}

void loop()
{
  servo.write(0);
  digitalWrite( LED_BUILTIN, HIGH);
  delay(1000);

  servo.write(180);
  digitalWrite( LED_BUILTIN, LOW);
  delay(1000);
}

[ADDED2]
Or even more fun, with a counter (as @ChrisStratton wrote):

#include <Servo.h>

Servo servo;

unsigned int counter;

void setup()
{
  Serial.begin(9600);
  Serial.println("The sketch has started");
  pinMode( LED_BUILTIN, OUTPUT);
  servo.attach(10);
}

void loop()
{
  servo.write(0);
  digitalWrite( LED_BUILTIN, HIGH);
  delay(1000);

  servo.write(180);
  digitalWrite( LED_BUILTIN, LOW);
  delay(1000);

  Serial.print("Still alive after ");
  Serial.print(counter);
  Serial.println(" seconds");
  counter += 2;   // two seconds per loop iteration
}


ATMega32u4 (Leonardo) Serial Baud Rate Does anyone know what the actual baud rate that the CDC Based virtual serial port on the Leonardo runs at is? Serial::being() for the CDC version is just empty, so it's not setting a baud rate anywhere.

Basically, I'm debating between using the 32u4 or the 328p with an FTDI chip and trying to figure out if the 32u4 will be slower... since it uses a virtual COM port I'm assuming it is, but I'd be happy if I was wrong :)

I'm not sure if the concept of an "actual baud rate" is really meaningful in a pure USB connection.

In my experience, the 32u4 is faster than the 328p at serial-heavy tasks. There is no intermediate chip, and USB has much larger hardware buffers than the serial port does. I don't know how much processing you're planning to do on your data, but I would expect that a 32u4 can process serial data pretty much as fast as you can generate/process it.

On the host side, it seems to me that there is very little difference in whether the "virtual COM port" has an FTDI or a 32u4 on the other end, so I don't see why one should be faster than the other (though admittedly they go through different device drivers).


Problems bluetoothing float values I have two Arduino Unos, one of which is connected to a HC-05 bluetooth device and a temperature reader, the other has just a HC-05 bluetooth and is expected to output temperature readings in serial monitor.

This is first device:

#include <SoftwareSerial.h>
const int tempPin = 1;
SoftwareSerial BTSerial(10, 11);

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

}

void loop() {
int value = analogRead(tempPin);
float mv = value * (3300/1024);
float x = (mv - 500)/100;
Serial.print("Temperature is: ");
Serial.println(x);
BTSerial.print(x);
delay(5000);
}

This is the second device:

#include<SoftwareSerial.h>
void setup() {
BTSerial.begin(38400);
Serial.begin(9600);
}
void loop() {
if(BTSerial.available())
{
float x = BTSerial.read();
Serial.println(x);
}
}

The first program is able to give me accurate readings (around (15 degress Celsius) but the second program gives readings between 40 - 60 *C (as well as that it spits out 5 different readings between delay intervals). Why is that? How should I change this so both devices output the same readings

Two problems:

Your first program sends an ASCII representation of the temperature with no line ending.  So after a few readings you get something like:

20.2520.2520.5021.0021.25

etc.  You need some line endings in there to break them up.

Secondly your second program reads one byte at a time as a number (float) and prints it - so would get something like:

50.00
48.00
46.00
50.00
53.00
50.00
48.00
... etc ...

You need to, in association with sending line endings in your first program, read each character of a single line either into a string and then parse that as a float (with dtostrf()) or directly into a float using a state machine.

You can read more about working with serial here and working with a number reading state machine here.


Fail programing a Sonoff Dual with Arduino IDE 1) I have a Sonoff Dual, which I wish to upload a Sketch.

2) Other Sonoff basic devices programed the same way, with succes.
But when uploading  the sketch the ( even the generic Blink sketch ) - I do not get any response from the Sonoff device.

3) pins were soldered correctly according this tutorial

4) Uploading the sketch succeeds, using FTDI set to 3.3v.

What might be the reason for it ? What can I do more to check it ? my only guess is that something has happened to Sonoff device - but it uploads successfully.

Guy

Code (edit2)

    /*
  Blink

  Turns an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
  the correct LED pin independent of which board is used.
  If you want to know what pin the on-board LED is connected to on your Arduino
  model, check the Technical Specs of your board at:
  https://www.arduino.cc/en/Main/Products

  modified 8 May 2014
  by Scott Fitzgerald
  modified 2 Sep 2016
  by Arturo Guadalupi
  modified 8 Sep 2016
  by Colby Newman

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Blink
*/
#define LED_BUILTIN 12
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  delay(2000);
  Serial.println("HELLLLLLO");
}

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

Upload

Build options changed, rebuilding all
Sketch uses 251224 bytes (50%) of program storage space. Maximum is 499696 bytes.
Global variables use 28080 bytes (34%) of dynamic memory, leaving 53840 bytes for local variables. Maximum is 81920 bytes.
Erasing 0x80000 bytes starting at 0x00000000
Uploading 255376 bytes from /tmp/arduino_build_214375/Blink.ino.bin to flash at 0x00000000
................................................................................ [ 32% ]
................................................................................ [ 64% ]
................................................................................ [ 96% ]
..........                                                                       [ 100% ]

Addede1: Port Selection:

note: when taken port was not connected ( connects to USB0)

edit3: erasing using esptool.py:

guy@desktop:~$ esptool.py --port /dev/ttyUSB0 --chip esp8266 erase_flash
esptool.py v2.5.0
Serial port /dev/ttyUSB0
Connecting....
Chip is ESP8285
Features: WiFi, Embedded Flash
MAC: 60:01:94:ad:bf:34
Uploading stub...
Running stub...
Stub running...
Erasing flash (this may take a while)...
Chip erase completed successfully in 2.4s
Hard resetting via RTS pin...

Your code is not good to detect if it  works.

The esp8266 Serial needs some time until it prints. First print after the Serial.begin() isn't printed. I guess the reason is the USB chip.

According to schematic, the LED in Sonoff Dual is on pin 12


Arduino pow() making 9's I am having a temporary lapse of judgement, or not understanding how the power method works, but when I put 10 to the power of a number, it is that value -1.  So:

10*10 = 100

Then I would assume, 10^2 = 100

So if I had a variable i, that was equal to 2, and I asked arduino for 10 to the power of i, I would expect it to do 10^2, and then give me 100, but instead I get 99.  What am I missing?

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

void loop() {
for (int i =0; i<5; i++){
   int power = i;
   Serial.print(power);
   Serial.print(":");

   int multiplier = pow(10,power);
   Serial.println(multiplier);

  }

}

I put this code into the IDE, and for n>=2, I got 99, 999, 9999 etc. The catch is that Arduino uses floating point arithmetic to implement the pow() function, and some of your values are being truncated as ints. If you change:

   int multiplier = pow(10,power);

to

   float multiplier = pow(10,power);

The results should be as expected.

(The brief reason why floats are used is related to the fact that it is very easy to calculate the pow() function using logs, and this makes it easy to pow() non-integers too. This also means that it may not be as exact as you would hope).


How to improve wiring a breadboard? just saw this tweet and was interested what wires are used there:

https://twitter.com/EngineersGarage/status/448014811280842752/photo/1

The wiring Looks cleaner than the setup I currently have with "normal" wires.

Thanks!

I think the wire itself is perfectly normal. It looks like he's simply soldered right-angled header pins onto the ends. That way, the wires can lie flat on the breadboard instead of being bent over for connections, meaning the whole thing is lower-profile and a little easier to route neatly.

It also has the advantage that they will probably survive far more insertions/removals. With that said, it brings the disadvantage that it exposes the contacts more above the surface of the board, which could increase the risk of accidental connections (short circuits and such like).


Call a class method from inside the same class If i have file cSpeedOfSound.h:

#ifndef cSpeedOfSound_h
#define cSpeedOfSound_h
#include "Arduino.h"
#include "math.h"
class cSpeedOfSound{
    public:
        cSpeedOfSound(float *i,float *C);
    private:
        float *C;
        float *a;
        float *i;
    };
#endif

and file cSpeedOfSound.cpp:

#include "cSpeedOfSound.h"
cSpeedOfSound::cSpeedOfSound(float *i,float *C){
    //some code...
    *C =roundto(*C,2);}
float cSpeedOfSound::roundto(float x,float dp){
return (round(x*pow(10., dp)) / pow(10., dp));}

where i want to run function roundto inside class, but it doesnt seems to work. So what im making wrong and how to do it properly?

Ps: Im begginer to arduino (want it to learn robotics + C language) and know python (learnd for about 1+ year), so pls do not hate me if i made crucial mistakes.

You need to include roundto() in your class declaration, e.g. something like this:

class cSpeedOfSound {
public:
    cSpeedOfSound(float *i,float *C);

private:
    float roundto(float x, float dp);

    float *C;
    float *a;
    float *i;
};

In C++, class structures are fixed. You can define the body of a function almost anywhere, but all member functions/data must be specified in the original declaration.

As a side note, it's worth pointing out that you have a naming conflict in your code. You have member variables called i and C, and you have totally separate function parameters called i and C. The compiler won't complain about this (the function parameters will simply mask the member variables), but it may not do what you expect.


Data transmission Serial to TCP I am trying to send numeric data using ESP8266 to local network python server. Before that I am collecting data from sensors using Arduino UNO and then send it to ESP using hardware serial.

ESP8266 code:

#include <ESP8266WiFi.h>

const char* ssid     = "ssid";
const char* password = "pass";

const char* host = "192.168.1.103";

String serial_data;

WiFiClient client;

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

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

   delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections

  const int port = 8888;
  if (!client.connect(host, port))
  {
    Serial.println("connection failed");
    return;
  }

}

void loop() {

  delay(200);

  while(Serial.available() <= 0)
  {
    //wait for arduino serial data
  }

  if(Serial.available()>0)
  {
    // This will send data to client via TCP
    Serial.println("Sent..");
    serial_data = String(Serial.read());
    client.print(serial_data);
  }
}

Python Server code:

import socket
import sys
from thread import *
from peewee import *

db = SqliteDatabase("data.db")

class post(Model):
    timestamp = DateTimeField()
    current = TextField()

    class Meta:
        database = db

#connecting to database
def initialize_db():
    db.connect()
    db.create_tables([post], safe = True)

initialize_db()

HOST = '192.168.1.103'
PORT = 8888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#keep talking with the client
#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

    #infinite loop so that function do not terminate and thread do not end.
    while True:

        #Receiving from client
        data = conn.recv(1024)
        print data

        #send data to database
        post.create(
            current = data
        )

        reply = 'OK ->' + data
        if not data:
            break

        conn.sendall(reply)

    #came out of loop
    conn.close()

#keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    start_new_thread(clientthread ,(conn,))

s.close()

After powering up ESP it successfully connects to server and then simulating arduino esp serial communication I am using serial monitor to send some numbers. Before I send anything server outputs number 240:

Connected with 192.168.1.100:26137
240

Then I am sending number 1 but on server terminal I get numbers 49 and 13. Sending numbers some 2 - 3 times and no more data are outputted to server terminal. Should I parse data received from serial to some form I can transmit it via TCP or data should be processed on server side?

The numbers are ASCII Codes (here is a chart from the Arduino website). 49 is the number 1, and 13 is a carriage return ('\n'). There should be a setting in the bottom right corner of Serial Monitor to change line ending, this should be set to "no line ending." If it is, than client.print() must be adding the carriage return, so you will need to remove it in Python. If you are only sending integers, replace

serial_data = String(Serial.read());

with:

serial_data = String(Serial.parseInt());

In the Python code I suggest adding a print statement to check if the connection is closed after

#came out of loop
    conn.close()


How to precisely control servo motor by changing duty cycle? I developed a PWM using timer1,using arduino uno and digital output, and identified that when I send a wave with duration of 0.6ms in High level, the motor goes to 0º. If I send 2.1ms, it goes to 180º. I tried to make a relationship between these scales to send the angle and change the time period in order to achieve that angle and it did not work.

I would like to move with a precision of 1 degree, is that possible? Just adjusting the time period.

The model of the motor is mg996r.
Maybe I am missing something.

My code just generates an interrupt over 50 microsencods and I use this to set the frequency of 50Hz and the duty cycle in ms using digitalWrite associated with pin 9.

#include <TimerOne.h>

double t = 0.0;

double period = 0;

void setup()
{
  t = 0;
  Serial.begin(9600);

  pinMode(9, OUTPUT);
  Timer1.initialize(50);
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here
}

void loop()
{
  // Main code loop
  // TODO: Put your regular (non-ISR) logic here
  if (Serial.available() > 0) {
    float grau = Serial.parseFloat();

    // receive data as angle
    if (grau > 180) grau = 180;
    if (grau < 0) grau = 0;

    // set period for that angle
    // relationship developed between angle and period in ms
    //set it to period
    period = (0.00833*grau + 0.6)*1E-3;
  }

}

/// --------------------------
/// Custom ISR Timer Routine
/// --------------------------
void timerIsr()
{
    t += 50E-6;
    if (t <= period) {
      digitalWrite(9, HIGH);
    }
    else if (t < 20E-3) { // periodo max de 20ms -> 50Hz
      digitalWrite(9, LOW);
    }
    else {
      t = 0;
    }
}

UPDATE:

I just got it working by creating a timer1 interrupt on CTC mode with a frequency of 100kHz and counting the necessary time to get increments (~ 10us each) of around 1 degree on my servo motor.

More info here.

The best is to use 10us Period, instead of 50us.
That precision will be close to 1°


How does the Arduino handle serial buffer overflow? How does the Arduino handle serial buffer overflow?  Does it throw away the newest incoming data or the oldest?  How many bytes can the buffer hold?

For hardware serial ports you can see in HardwareSerial.cpp that the buffer size varies depending on the amount of RAM available on the particular AVR:

#if (RAMEND < 1000)
    #define SERIAL_BUFFER_SIZE 16
#else
    #define SERIAL_BUFFER_SIZE 64
#endif

For a software serial port in SoftwareSerial.h the receiver buffer size _SS_MAX_RX_BUFF is defined as 64 bytes. In both cases it stops attempting to insert received data into the queue when it is full, so you could get a mix to old and new data depending on how you're retrieving data from the queue.

Ideally it would be best to ensure the buffer always gets emptied in a prompt manner to avoid the buffer filling. Maybe take a look at timers and implementing a simple state machine if your problem is related to other code blocking the main loop.


How to power Nodemcu using 12 volt AC to DC adapter? I am trying to make a small project using Nodemcu. My project is WiFi controlled LED, 2 LED's will blink at the same time. I have successfully uploaded the code and it works fine using USB connection. But I want to power the Nodemcu using 12 volts 1.5 amps AC to DC adapter. I have checked it in web search but I have not found an understanding circuit. please help me out guys.

You connect the + side of the adapter to VIN pin and the - side to GND.
You have to check the maximum voltage when using the VIN pin. Probably it means you 'waste' some power (but it's from a wall wart, so it should be ok). See the remark of Flyingfenix below for heating consequences.
See this link: Power Related ESP-12E Development Board Pins, fragment 'Using a Wall Wart':

The current (1.5A) should be more than enough; the adapter's current should be higher than what is needed by the NodeMCU + circuit. So this is ok.


Sharing clock pin on Pro Micro I am trying to get both a SPI LED matrix display and an NRF24L01 to both work on the same Arduino Pro Micro. I know they both want to use the clock pin but how do I get them to share? Can I use the CS pin to turn off one device while trying to use the other? The display does can be set only when something needs to change so it's not always running.

It is indeed possible and supported to use different CS (chip select) or SS (“slave select”) lines to address individual SPI devices on a single bus run by an SPI “master”.

Image from Wikipedia
Many SPI TFT Touch displays need this to address the display controller and the touch controller as individual SPI devices and/or an integrated SD Card interface (wich also uses SPI).
The MOSI, MISO and SCLK lines can be reused and shared between perpiheral devices, as long as only one device is actively being addressed at any point in time. I.e. only one SS/CS may be active at any time and the software must support such sharing of SPI resources.


How to send keystroke with shift modifier? This is a bit of a newbie question, but here it goes anyway. So basically I want to send a keystroke using the DigiKeyboard library, but with shift held down. I looked through the code and saw this comment in scancode-ascii-table.h:

//Format: most signifficant bit indicates if scan code should be sent with shift modifier
remaining 7 bits are to be used as scan code number.

I dont really understand where to specify this, whether it's when you call the sendKeyStroke function, or somewhere in the code. Help appreciated.

I never used this library, but in the header file there are this constants for modifiers:

#define MOD_CONTROL_LEFT    (1<<0)
#define MOD_SHIFT_LEFT      (1<<1)
#define MOD_ALT_LEFT        (1<<2)
#define MOD_GUI_LEFT        (1<<3)
#define MOD_CONTROL_RIGHT   (1<<4)
#define MOD_SHIFT_RIGHT     (1<<5)
#define MOD_ALT_RIGHT       (1<<6)
#define MOD_GUI_RIGHT       (1<<7)

and a function

void sendKeyStroke(byte keyStroke, byte modifiers)

so I would use this to send a key with Shift like this

sendKeyStroke(KEY_F2, MOD_SHIFT_LEFT);


HTTP POST request to IFTTT I'm trying to send a POST request to IFTTT from a Node MCU. Instead of writing the code from the scratch, I've tweaked an already existing code (for GET request). It does not seem to work, what am I doing wrong? Needless to say, I replaced the WIFI ssid, the password and the IFTTT token. When testing the POST request with CURL, it works perfectly. Here's how the request should look like:

https://maker.ifttt.com/trigger/{event_name}/with/key/my_super_secret_token

...and the code:

#include <ESP8266WiFi.h>

const char* ssid     = "mywifi";
const char* password = "mywifipassword";

const char* host = "maker.ifttt.com";

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

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

int value = 0;

void loop() {
  delay(5000);
  ++value;

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "trigger/{trigga}/with/key/IFTTT_token";
  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

    // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");
}

Problem I see is that the request is incomplete - the server will be waiting for your payload.

client.print(String("POST ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");

You haven't specified a Content-Length header so the payload should start after the headers finish - but you don't send anything.

You need to (at least):

add a payload or
add a Content-Length: 0 header or
add a payload with a matching Content-Length: header.

You can use curl to see a full set of valid POST headers like this:

curl -v -d "" http://localhost

You can use Chrome and Firefox's Web Inspector's Network tab to look at the raw headers of requests too.


Need to turn on project twice in order for screen to work! This problem is really stumping me. I made a simple printed circuit board with an ATtiny85, a 128x64 I2C OLED display, and a Sharp IR analog distance sensor. You can view the circuit here: circuits.io.

If I turn the system on using the simple 3-pin slide switch that I put on the board, the screen does not turn on. I can see that the system is powered though, because I can see a little bit of red light escaping from the IR sensor where some of the IR light borders on the visible end of the spectrum. If I turn the board off then immediately turn it back on, the display powers up just fine. If I upload a new program to the board and use the programmer's 3.3v power I don't need to do it twice - the screen works first time.

I'm using a 3.7v LiPo battery, so I know power is not an issue (everything is 3-5v tolerant, and the LiPo battery can deliver plenty of current). Why do I need to turn it on twice in order for the screen to work? Thanks!

Adding a 100ms delay before calling oled.init(0x3c); oled.clear(); oled.startScreen(); made this problem go away.


Why I could not read the other sms's except the first SMS? I have to read the incoming SMS on my GSM module SIM900, and I want to print the sender number and message to the serial monitor.

I first configure the GSM module with AT commands and Response() function will give me the response to AT commands.

as any SMS will be in the following pattern

+CMT: "[Mobile number]", "[Date and Time]>"
   [message body]

So, I first extract +CMT and after that I will take mobile number and at last we have message body. The code I have used is

char RcvdMsg[200] = "";
int RcvdCheck = 0;
int RcvdConf = 0;
int index = 0;
int RcvdEnd = 0;
char MsgMob[15];
char MsgTxt[50];
int MsgLength = 0;

void Config() // This function is configuring our SIM900 module i.e. sending the initial AT commands
{
    delay(1000);
    Serial.print("ATE0\r");
    Response();
    Serial.print("AT\r");
    Response();
    Serial.print("AT+CMGF=1\r");
    Response();
    Serial.print("AT+CNMI=1,2,0,0,0\r");
    Response();
}

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

void loop()
{
  RecSMS();
}

void Response() // Get the Response of each AT Command
{
    int count = 0;
    Serial.println();
    while(1)
    {
        if(Serial.available())
        {
            char data =Serial.read();
            if(data == 'K')
            {
                Serial.println("OK");
                break;
            }
            if(data == 'R')
            {
                Serial.println("GSM Not Working");
                break;
            }
        }
        count++;
        delay(10);
        if(count == 1000)
        {
            Serial.println("GSM not Found");
            break;
        }
    }
}

void RecSMS() // Receiving the SMS and extracting the Sender Mobile number & Message Text
{
    if(Serial.available())
    {
        char data = Serial.read();
        if(data == '+'){RcvdCheck = 1;}
        if((data == 'C') && (RcvdCheck == 1)) {RcvdCheck = 2;}
        if((data == 'M') && (RcvdCheck == 2)) {RcvdCheck = 3;}
        if((data == 'T') && (RcvdCheck == 3)) {RcvdCheck = 4;}
        if(RcvdCheck == 4)
        {
            RcvdConf = 1;
            RcvdCheck = 0;
        }

        if(RcvdConf == 1)
        {
            if(data == '\n'){RcvdEnd++;}
            if(RcvdEnd == 3){RcvdEnd = 0;}
            RcvdMsg[index] = data;

            index++;
            if(RcvdEnd == 2){RcvdConf = 0;MsgLength = index-2;index = 0;}
            if(RcvdConf == 0)
            {
                Serial.print("Mobile Number is: ");
                for(int x = 4;x < 17;x++)
                {
                    MsgMob[x-4] = RcvdMsg[x];
                    Serial.print(MsgMob[x-4]);
                }
                Serial.println();
                Serial.print("Message Text: ");
                for(int x = 46; x < MsgLength; x++)
                {
                    MsgTxt[x-46] = RcvdMsg[x];
                    Serial.print(MsgTxt[x-46]);
                }

                Serial.println();
                Serial.flush();
            }
        }
    }
}

The problem of the code is

After receiving first SMS I am getting my mobile number and message body. After that I am only getting the sender number printed to my serial monitor but not the message body.

Where has it gone wrong. I could not understood.

Please help me.......Thanks in advance.

It looks like RcvdEnd never gets reset back to zero because RcvdConf is set to zero when RcvdEnd is 2, which means it will never get to 3 and reset it (at least not when you are expecting it to). I'm not sure how many new lines you are supposed to be checking for but the way it is set up now or is looking for two on the first message, and three for every message thereafter. You might want to rework the logic and maybe move where that value gets reset.


Record data to SD card with ATtiny85 An application of ATtiny with SD card is complicated due to missing of hardware SPI in attiny.
The "ATmega" code for creating of a "SD file" is:
#include <SPI.h>
#include <SD.h>

File file;
int const pinCS = 2;

void setup()

{
SD.begin(pinCS);
file = SD.open("Test.txt", FILE_WRITE);
file.println("anything");
file.close();}

void loop()
{}

This code creates on SD card a file "Test.txt" and to this file records text "anathing".
Is it possible to rewrite this code for "ATtiny85"?

The ATtiny85 has no dedicated SPI port. It has, however, an “USI” port
(Universal Serial Interface) that should be able to do the job. The lack
of SPI should not be a problem, but the lack of memory will be a
problem.
Files on an SD card are written one sector (512 bytes) at a time.
For this reason, the SD library uses a 512 bytes buffer in RAM.
That cannot work on an ATtiny85, as the buffer would consume the whole
RAM.
You may be able to do something using the Petit FAT library,
provided you can work around the severe limitations of its write
interface:

The write function has some restrictions listed below:

Cannot create file. Only existing file can be written.
Cannot expand file size.
Cannot update time stamp of the file.
Write operation can start/stop on the sector boundary only.
Read-only attribute of the file cannot block write operation.

The first two points imply that you would have to create the file and
allocate the sectors for it in your computer.
This blog post mentions a port of the library to the Arduino
environment, and its use on an ATtiny84, which has similar capabilities
to the ATtiny85 (only with more pins).


Why am I only receiving the first address byte? (I2C Protocol) Expecting the slave to ACKnowledge and return data, but it does not. This is my protocol. This is my Datasheet.

Also FYI I'm on an Arduino Fio but I am not inheriting the Arduino library.

#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include <uart.h>
#include <i2c_master.h>

#define LED PB5

#define I2C_READ 0x5A

char buffer[1];

//char data[9];
uint16_t val = 0;
uint8_t status = 0;

void getVal()
{
  if(i2c_start(I2C_READ))
    {
        uart_puts("Start ");

        val = ((uint8_t)i2c_read_ack())<<8;
        val |= i2c_read_ack();

    status = ((uint8_t)i2c_read_nack());

      i2c_stop();

    } else
  {
        uart_puts("Error");

        i2c_stop();
    }
}

int main(void)
{
  init_uart(57600);
  i2c_init();

  DDRB = _BV(5);

    for(;;)
    {

      getVal();

            itoa(status, buffer, 10); //convert decimal to string base 10
            uart_puts(buffer);

      PORTB = 0xFF;
      _delay_ms(500);
      PORTB = 0x00;
      _delay_ms(500);
    }
    return 0;   /* never reached */
}

(Acknowledging this is an old question.) The TI article "Troubleshooting I2C Bus Protocol", suggests several common reasons for no ACK:
1. Timing
2. Missing / Unexpected SCL pulses
3. Incomplete 8 bit block
4. Missing Bytes
5. False slave address
6. Unsuccessful address change


How to count the number of times a changing variable reaches a peak value I am recording a varying distance with an Ultrasonic sensor and Arduino but my problem is I want to display the number of times this variable reaches peak (at an instance the value will be increasing and the next instance decreasing in that order) on an LCD.

So far this is my code:

//Libraries
#include <Ultrasonic.h>
#include <LiquidCrystal.h>

//Setup connection with LCD and HC-SR04
LiquidCrystal lcd(12, 10, 5, 4, 3, 2);
Ultrasonic ultrasonic(A0,A1);

void setup() {
  //Lcd init
  lcd.begin(16, 2); //16 rows, 2 columns
}

void loop()
{
  lcd.clear();
  lcd.print("  Ardumotive ;)  "); // You can change this message.
  lcd.setCursor(0, 1);
  lcd.print("Distance: ");
  lcd.print(ultrasonic.Ranging(CM));
  lcd.print("cm");

  delay(300); // 1sec delay
}

The counting portion of what you want to achieve is simple - you just increment a variable.  The hard part is knowing when to count.

You need to remember what your value has been doing in the past in order to know if you have had a peak or not.  Also you have to define exactly what a peak is.

The simplest method (I'm not going to spoon feed you code, just help you understand the concepts) is to set a couple of thresholds, and maintain a flag.

You decide upon a value "above which the value enters the peak zone", and another "below which the value leaves the peak zone".  They could be the same value, but don't need to be.

You then have a flag which remembers if you are in the peak zone or not.

If you're not currently in the peak zone and the new value is above the peak zone entry threshold then you have entered the peak zone.  Set the flag to remember that fact.

If you are currently in the peak zone and the new value is below the peak zone leaving threshold then you have just left the peak zone.  Clear the flag to remember the fact that you're not in the peak zone and increment your peak counter now you have left the peak.

It can be very good to have the leaving threshold lower than the entering threshold so that the value has to drop significantly out of the peak zone before it will register another peak.  This is known as hysteresis and is great for getting rid of the noise you may get if the value is hovering around the peak zone entry threshold.


Why does it skip the first index - shift register issue So, I wrote this code myself and I'm a noob on the issue. I did get my code working, but cannot understand why it has to be the way it is.

int counter;
int ledValue[] = {
  1,0,1,1,1,1,1,1
};

void setup()
{
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
}

void loop(){
  digitalWrite(5, HIGH);
  for (counter = 8; counter >= 0; --counter) {
  // turn the pin on:
    digitalWrite(2, ledValue[counter - 1]);
    digitalWrite(3, 1);
    digitalWrite(4, 1);
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    delay(100);
  // turn the pin off:
  }
  delay(1000);
  digitalWrite(5, LOW);
}

Now, I am puzzled by both the counter = 8 and the [counter -1]. To me it looks like I am loop-ing this 9 times, though I only got 8 items in the array

A. If I make it counter = 7 and [counter -1] my output is 10111110. This loops 8 times (I think), but gives me 7 leds.

B. If I make it counter = 7 and [counter] my output is 01111110. This loops 8 times (I think), gives me 7 leds but also an extra led burning up front, hence braking the prescribed pattern.

C. If I make it counter = 7; counter >= -1 my output is 10111111.(as it should). But how can it be -1?

My guess is that I am doing something wrong at the beginnen, but I can't find what. Tried several tutorials and explanations, but it still puzzles me why the correct running code is that way.

Just to be sure, I am familiar with an array being 0-indexed.

Please helpt me understand my code  ;-)

Edit:
Small addition:

pin 2 is connected to ShiftRegister pin 14
pin 3 is connected to ShiftRegister pin 12
pin 4 is connected to ShiftRegister pin 11
pin 5 is connected to ShiftRegister pin 10

Thanks for the feedback. My lack of understanding does not concern the loop or array. What I can't get my head around is why the shift registers outputs the loop as it does. Would a picture of the setup help?

The correct way to loop through an array of length 8 is:

for (int counter = 0; counter < 8; ++counter) {
    digitalWrite(2, ledValue[counter]);
    // ...
}

If you want to loop through the array backwards, then:

for (int counter = 7; counter >= 0; --counter) {
    digitalWrite(2, ledValue[counter]);
    // ...
}

This loop will visit, in this order, the indices 7, 6, 5... 1 and 0.

For extra clarity, you could define a constant that holds the length of
the array, then replace the numbers 8 and 7 above by VALUES_COUNT
and VALUES_COUNT-1 respectively.

You wrote:

  If I make it [...] my output is [...]

Not sure what you mean by that. This code should not have much visible
output, as the LEDs are turned off only microseconds after being turned
on. How do you determine what the program's "output" is? Maybe there is
an issue with the way you are trying to diagnose the problem.


Is it safe to connect VCC to a data pin on Attiny chips? I'm trying to make a compact prototype with Attiny2313A, and want to connect VCC to pin 18 with a push button as in the picture. Is it safe? Or do I need a resistor there?

As mentioned by @chrisl, here you would need a pull-down resistor to make sure that pin was not high when the button was not pushed.
It is more typical to connect the button between the IO pin and ground since then you can use the built-in pull-up resistors to make sure the pin is high when the button is not pushed. (This chip only has built-in pull-ups, although some chips have pull-downs).


MKR1000 not showing up on OSX I can't appear to get my MKR1000 to list a port on my mac in the arduino ide, am i missing something obvious or does it need additional drivers?

Also
➜  ~  csrutil status
System Integrity Protection status: disabled.

running OSX 10.11.3

Board appears to be working, default led flashing

Double click the reset button on the board. Then it will show in the Port list :-)


ESP8266 Battery Monitor Is there a way to monitor the battery that feeds an esp8266 in a portable project?

I have been meaning to implement that feature into my project so that i can be warned when the battery runs low on juice but i don't know if the esp has some kind of onboard sensor to do that.

There are two things you need to measure the battery of the system that is doing the measuring of the battery:

An analog-to-digital converter
Some form of fixed voltage reference to compare the battery voltage against.

Some ESP8266 modules have a single analog input available, and some don't. You need to check which module you have and which pins are available on it.

Then you need to use the ADC to measure the fixed known voltage. That could be from a small LDO voltage regulator that is below the voltage of the minimum voltage you will care about from your battery, or something like the forward voltage drop of a silicon diode (~0.7V) - something where you know what the voltage is.

From that reading you can then back-track what the supply voltage must be in order to give you the reading it has given you.  As the battery voltage drops the voltage range the ADC will be measuring will be reduced, and so the fixed voltage will rise within that range giving you higher readings from the ADC.

Here is a snippet of code I use with the 1.1V internal voltage reference of the ATMega328P to calculate the supply voltage:

long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1125300L / result; // Back-calculate AVcc in mV
  return result;
}

Of course, you need to change that to use the analog input of the ESP8266 instead (probably just using analogRead()). And of course change the ADC-scaled voltage.  The formula is basically:

Vref * ADCmax / ADCreading

So if you have the 1.1V reference as above, and the ADC can read 0-1023, then it's:

1.1 * 1023 / reading

Or, pre-calculate the first half of the sum:

1125.3 / reading

To keep it as integer mathematics work in millivolts instead of volts by multiplying the reference voltage by 1000:

1125300 / reading

And that, as you can see, is what is in the function above.


How to use multiple SPI slaves in MKR1000 if it doesn't have Slave Select (SS/CS) pin? I'm using a Genuino MKR1000 and I want to use the SPI interface, which I've seen that there is no Slave Select (SS)/Chip Select(CS) pin usage.

How can I use the SPI interface with multiple slaves then?

The Arduino doesn't care what pin you use for SS since you just use digitalWrite() on it anyway. You use any pin you like for one slave, so you can use any other pin you like for another slave.

The ATMega-based boards need pin 10 to be set as an output for SPI to function, but you don't then have to use that for the actual slave select. The only time it becomes a real slave-select pin is when using the Arduino itself as a slave.


Forcing bootloader startup through program I am trying to find out if it is possible to trigger programmatically the double-tap on reset button function, implemented in modified version of Atmel's SAM-BA bootloader. The board of interest is Arduino Zero.
In case this is not possible using the stock board setup, if this can be achieved by hardware or bootloader modifications.

Theoretically it is quiet easy to fake that double-tap with software, but there might be some obstacles in practice.
The bootloader uses an unsigned long value in RAM memory to indicate if the double tap happend. The actual bootloader for the zero uses the following definitions.
// zero specific; but other boards use the same values AFAIK
// (in board_definitions_arduino_zero.h)
#define BOOT_DOUBLE_TAP_ADDRESS  (0x20007FFCul)
#define BOOT_DOUBLE_TAP_DATA  (*((volatile uint32_t *) BOOT_DOUBLE_TAP_ADDRESS))

// for all bootloader (in main.c)
#define DOUBLE_TAP_MAGIC 0x07738135

When the bootloader is started after a reset, it checks, if that was a power on reset (POR) or not. If it has been a POR, it sets the indicator value to 0 BOOT_DOUBLE_TAP_DATA = 0;.
If it does not detect a POR, the bootloader continues with checking the indicator value whether it is set to the tap magic.
If the magic can be found  the indicator value is set back to 0 and the bootloader is started. Otherwise the value is set to the "double tap magic": BOOT_DOUBLE_TAP_DATA = DOUBLE_TAP_MAGIC. The bootloader waits for 500 ms to let the user reset the zero a second time (double tap) and resets the indicator value after that time interval.

How to:
To simulate a double tap, you just need to set the indicator variable with the magic value from within you program. Use the definitions above. Then perform a software reset.

The caveats:

If the bootloader was changed, that could make you code useless.
I have not the time to test my ideas, so this is just an unverified method. It might fail for some reasons, I do not see actually.
You have to find a method to reset the zero with the program. Iknow some methods but I've not tried any of them so far.

Reset Methods: (as a starting point for your search)
I've read somewhere that the zero supports the CMSIS method NVIC_SystemReset.
This is a method often used for M0 ARM controllers (like SAMD11).
SCB_AIRCR = SCB_AIRCR_VECTKEY(0x5FA) | SCB_AIRCR_SYSRESETREQ_MASK;

Here is my code "idea" (untested):
#define BOOT_DOUBLE_TAP_ADDRESS  (0x20007FFCul)
#define BOOT_DOUBLE_TAP_DATA  (*((volatile uint32_t *) BOOT_DOUBLE_TAP_ADDRESS))
#define DOUBLE_TAP_MAGIC 0x07738135

// lots of code ....

void resetWithDoubleTap()
{
   BOOT_DOUBLE_TAP_DATA = DOUBLE_TAP_MAGIC;
   NVIC_SystemReset();
}

I would be lucky, if you succeed with this. Please let us know your outcomes, either write your own answer or tell me what you've done and I will correct my answer if necessary. Good luck.


Please help me combine the two codes for DHT11 and SW-420 Vibration sensor for arduino in one program The following is the code used for DHT11 Temperature and Humidity sensor:

#include <LiquidCrystal.h>
LiquidCrystal lcd(4, 5, 0, 1, 2, 3);
byte degree_symbol[8] =
              {
                0b00111,
                0b00101,
                0b00111,
                0b00000,
                0b00000,
                0b00000,
                0b00000,
                0b00000
              };
int gate=11;
volatile unsigned long duration=0;
unsigned char i[5];
unsigned int j[40];
unsigned char value=0;
unsigned answer=0;
int z=0;
int b=1;
void setup()
{

lcd.begin(16, 2);
 lcd.print("Temp = ");
 lcd.setCursor(0,1);
 lcd.print("Humidity = ");
 lcd.createChar(1, degree_symbol);
 lcd.setCursor(9,0);
 lcd.write(1);
 lcd.print("C");
 lcd.setCursor(13,1);
 lcd.print("%");
}

void loop()
{

 delay(1000);
 while(1)
 {
  delay(1000);
  pinMode(gate,OUTPUT);
  digitalWrite(gate,LOW);
  delay(20);
  digitalWrite(gate,HIGH);
  pinMode(gate,INPUT_PULLUP);//by default it will become high due to internal pull up
 // delayMicroseconds(40);

  duration=pulseIn(gate, LOW);
  if(duration <= 84 && duration >= 72)
  {
      while(1)
      {
        duration=pulseIn(gate, HIGH);

        if(duration <= 26 && duration >= 20){
        value=0;}

        else if(duration <= 74 && duration >= 65){
        value=1;}

        else if(z==40){
        break;}

        i[z/8]|=value<<(7- (z%8));
        j[z]=value;
        z++;
      }
    }
answer=i[0]+i[1]+i[2]+i[3];

if(answer==i[4] && answer!=0)
{
lcd.setCursor(7,0);
lcd.print(i[2]);
lcd.setCursor(11,1);
lcd.print(i[0]);
}

z=0;
i[0]=i[1]=i[2]=i[3]=i[4]=0;
 }
}

The following is the code for SW-420 Sensor:

int LED_Pin = 13;
int vibr_Pin =3;

void setup(){
  pinMode(LED_Pin, OUTPUT);
  pinMode(vibr_Pin, INPUT); //set vibr_Pin input for measurment
  Serial.begin(9600); //init serial 9600
 // Serial.println("----------------------Vibration demo------------------------");
}
void loop(){
  long measurement =TP_init();
  delay(50);
 // Serial.print("measurment = ");
  Serial.println(measurement);
  if (measurement > 1000){
    digitalWrite(LED_Pin, HIGH);
  }
  else{
    digitalWrite(LED_Pin, LOW);
  }
}

long TP_init(){
  delay(10);
  long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

Assuming the DHT11 Pin configuration remains unchanged and you can change the pin configurations for SW-420 vibration sensor, please give me a combined code for the two sensors to display results in one program. Thanks a lot.

There are multiple threads on how to combine two different sketches. One of the main things you have to do is refactor your code to get rid of calls to delay(). Do a Google search on Arduino blink without delay and read one of the tutorials you find. The idea is to make a call to the millis() function for each thing you want to do on a time intervl, save the current millis count, and then wait until the new value of millis() is greater than the saved value by your desired time interval. By doing that, your code does a very fast series of checks:

"is it time to do <thing 1> again?"

"Is it time to to <thing 2> again?"

"What about <thing 3>"

And repeats.

Then it doesn't freeze the rest of your sketch waiting for time to pass. (That is what delay() does. Everything stops until the delay time has passed, which is bad.)


Mega + SIM808 GPRS GSM GPS IPX-SMA module power on from code Is it possible to turn on the SIM808 module from code? There is a button in the SIM808 board to activate the module, but I need to turn it on from the code automatically. This is because my device will be stored hidden inside a vehicle so I do not have to keep turn on and off by hand.

This is the model.

Looking at the pictures it looks like it should be possible to take the two exposed connections of the switch and add flying leads to them and run them back to the microprocessor to allow it to turn them on and off.  The possible problem is the current that has to run through the switch.

You will need to investigate, but it looks like it could be done like that if you can't find a better solution.