ArrayList implementation fails for string object I'm using a customised C++ implementation of ArrayList based on the method found in Processing. The original code is by Obed Isai Rios, but I've added a version to Github with more explicit file structure.  The arraylist is appended to by the add_string_item method, which works ok in the format arraylist->add_string_item("text string") but fails when the same input is a String variable.  The following script illustrates:

#include "ArrayList.h"
void setup(){
  ArrayList *list = new ArrayList("text1");
  list->add_string_item("text2");
  String str = "text3";
  list->add_string_item(str);
}
void loop(){}

This fails on the last line with error message:

no matching function for call to 'ArrayList::add_string_item(String&)'

sketch_aug24b.ino: In function 'void setup()':
sketch_aug24b:7: error: no matching function for call to 'ArrayList::add_string_item(String&)'
/Users/robinedwards/Documents/Arduino/libraries/ArrayList/ArrayList.h:17: note: candidates are: void ArrayList::add_string_item(char*)

I'm not familiar with C++ so can't figure out why this method accepts a string but not when assigned to a String object str.  I'm pretty sure it's because I need to coerce to char* but not sure how to do this.  I've tried toCharArray without success, although this seems the right direction.  Very grateful for any assistance.

ArrayList.cpp code:

#include "Arduino.h"
#include "ArrayList.h"

ArrayList::ArrayList(char* init){
  stringlist = (char**)malloc(10*sizeof(char*));
  stringlist[0] = init;
  this->size = 1;
}

ArrayList::~ArrayList(void)
{
}

void ArrayList::add_string_item(char* item){
  char **neulist = (char**)malloc((size+1)*sizeof(char*));
  for(int i=0; i<size; i++){
    neulist[i] = stringlist[i];
   }
   //
   neulist[size] = item;
   stringlist = neulist;
   size = size + 1;
}

void ArrayList::set_string_item(char* item, int index){
  stringlist[index] = item;
}

void ArrayList::remove_selected_item(int index){
  char **neulist = (char**)malloc((size-1)*sizeof(char*));
  //From Begining
  for(int i=0; i<index; i++){
    neulist[i] = stringlist[i];
  }
  //From next Index
  for(int i=index; i<=size-1; i++){
    neulist[i] = stringlist[i+1];
  }
  //free(matrix);
  stringlist = neulist;
  size = size - 1;
}

void ArrayList::empty_list(){
   size = 1;
   char **neulist = (char**)malloc((size)*sizeof(char*));
   stringlist = neulist;
   stringlist[0] = "EMPTY";
}

void ArrayList::display_string_list(){
   Serial.begin(9600);
  for(int i=0; i<size; i++){
    Serial.println(stringlist[i]);
   }
}

char** ArrayList::get_stringlist(){
  return this->stringlist;
}

char* ArrayList::get_item(int index){
  return this->stringlist[index];
}

void ArrayList::set_stringlist(char** stringlist){
  this->stringlist = stringlist;
}

int ArrayList::get_size(){
  return this->size;
}

In theory, there's no reason why you shouldn't be able to call it by using toCharArray(). You would need to call it like this:

String str = "text3";
char * buf = new char[str.length()+1];
str.toCharArray(buf, str.length()+1);

list->add_string_item(buf);

That allocates a char buffer, copies the string data into it, then passes that buffer pointer to the list to be stored. Note that the buffer is one character larger than the string, as it needs to add a null terminator at the end.

However, there is a major problem with the rest of your code, which could eventually cause your Arduino to crash or do other strange things (depending on how much you use the list object).

Unlike Java, C++ is not a garbage-collected language, meaning it won't automatically clean-up memory for you. If you call new or malloc() to allocate heap memory, you have to call delete or free() (respectively) when you're finished with it to deallocate it.

Simply overwriting a pointer with another call to malloc() is not enough; it results in a memory leak. This means the block of memory it was previously using is lost, and cannot be reused again as long as the program is running. On a platform like Arduino, which has limited memory, you can very quickly run out.

Fixing the design of your class is probably beyond the scope of an answer on this site. I would strongly recommend working through some C++ tutorials (of which there are hundreds online).

As a side note, you should generally use new/delete instead of malloc()/free(). It doesn't make much difference when you're using arrays of char or char*, but it's important if you want to allocate class instances.


How to use bitset/read on 16bit numbers (Arduino) I'm working on an Arduino powered Tetris game. To keep track of the pieces that have fallen and become fixed I have an array of bytes

byte theGrid[] = {
B00000000,
B00000000,
B00000000,
B00000000,
B00000000,
...

This works great when the well is only 8 LEDs wide, but I need it to be 16 wide. Is there a way to perform bitwise operations on a 16 bit number, like a short? I tried just declaring theGrid as a short, but I'm getting this error no matter what I do.

tetris:62: error: 'B0000000000000000' was not declared in this scope

The reason I was using byte is so I could use bitread and bitset. So if an L piece comes down and lands, I can bitset the appropriate bits like this

bitSet(theGrid[pixelY], 15-pixelX);

and end up with

B1000000000000000, B1110000000000000

The main problem that you're having is that binary literals don't exist in C; the Arduino libraries get around this by having every single binary value from 1'b0 to 8'b1111_1111 defined as a macro in cores/arduino/binary.h. The obvious workaround is to use octal, decimal, or hexadecimal literals instead.

unsigned short theGrid[] = {
00,
0,
0x0,
 ...
};

Bitwise operations work as normal.

theGrid[pixelY] |= _BV(15 - pixelX);


ESP8266 reset problem I am trying some AT commands with ESP8266 but it resets continously when it stop resetting, i can't get any response from ESP8266.

Example :

AT

OK
AT+CWMODE=1

OK
AT+CIPMODE=0

OK
AT+CIPMUX=1

OK
AT+CWJAP="..",".."

 ets Jan  8 2013,rst cause:4, boot mode:(3,1)

wdt reset
load 0x40100000, len 612, room 16
tail 4
chksum 0x12
load 0x3ffe8000, len 788, room 4
tail 0
chksum 0x50
load 0x3ffe8314, len 264, room 8
tail 0
chksum 0x4a
csum 0x4a

2nd boot version : 1.1
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd
ready

 ets Jan  8 2013,rst cause:4, boot mode:(3,1)

wdt reset
load 0x40100000, len 612, room 16
tail 4
chksum 0x12
load 0x3ffe8000, len 788, room 4
tail 0
chksum 0x50
load 0x3ffe8314, len 264, room 8
tail 0
chksum 0x4a
csum 0x4a

2nd boot version : 1.1
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd
ready

I have upgraded my firmware and I tried GPIO0 and GPIO2 are active but it still does not response fine. It worked yesterday but today it is working like crazy..

Arduino can not provide enough current for ESP8266 operations. Use external 3.3V power supply, I would recommend 500ma. Also don't forget to put a small cap between vcc and ground. 100uf should do it.


Powering 3.3V Arduino and 12V peripherals from single 12V power supply? Given:

I have some home alarm peripherals (motion detectors, glass break sensors) which operate at 12V and draw a nominal current of 20mA when in alarm state.
I have a Particle Photon (3.3V logic level) which will accept up to 5.6V on its VIN pin.
I have a 12V @ 2A switching power supply.

Can someone describe to me an efficient circuit which would allow me to power all of the peripherals @ 12V and the Arduino (Particle Photon) at 3.3ishV?

I have on hand an LM7805 linear regulator, which I believe will work, but will be inefficient. I also have on hand a DC-DC step down converter (4.5V-28V IN, 0.8V-20V OUT @ 2A) but I am a novice and don't know how to use it for the scenario described here.

@Majenko remarked:

Put 12V on the IN, connect the OUT to a volt meter, twiddle the knob till it reads 5V. Disconnect the volt meter. Connect it to the VIN of your photon.

@loopforever added:

For the 3.3V Arduino (Photon) current draw will not exceed 500mA. For the 4x 12V peripherals, if all were in an "alarm" state simultaneously, current draw will not exceed 110mA.

@Dampmaskin added:

Dropping 8.7V at 500mA wastes 4.35W so OK you're right, that is inefficient. A buck converter is probably the best approach then

@SDsolar added:

If you use a screw-terminal barrier block you can have both 12V and your lower voltages available at the same time


Turning a DC motor a set number of Rotations using an encoder I'm using an arduino UNO, and i want to turn a motor a set number of revolutions, i'm trying to read the clicks of the encoder which has a resolution of 360 clicks/ revolution, my logic is that i count the number of clicks until i get to the desired number which represents the the number of revolutions * the resolution of the encoder:

1 revolution ==> 360 clicks
5 revolutions ==> 360*5 (desired number)

i'm a beginner with arduino so here is my code:

volatile int counter=0;
int motor=5;  // motor is connected to pin 5

void setup(){
  pinMode(motor,OUTPUT);
  attachInterrupt(0, count,RISING); // attaching encoder on interrupt 0
}

void loop(){
  while(counter< 360*5){
    analogWrite(motor,255);
  }
}

void count(){
  counter++;
}

This code is not working at all, how can i fix it?

You never tell the motor to stop.

void loop(){
   while(counter< 360*5){
     analogWrite(motor,255);
   }
   analogWrite(motor, 0); //add something like this or whatever could stop it
   //you may want to disable the counter now too
}

However, even with that change you are likely a long way from having a working, or at least reliable system - see other issues in my comment on the question.


Can I reassign my Arduino Uno COM Port? The Arduino SW, under Tools, identifies my Uno as COM Port 3. However, COM Port 3 on my computer is in use by a chip set. My computer assigned COM Port 4 to my Arduino Uno.

Can I reassign my Uno to COM Port 4?

Edit: This question also applies to people who don't have administrative privileges. They do not have privileges to change the port via Windows Device Manager.

If the Arduino IDE identified your Uno as COM Port 3, your computer most likely has already assigned COM Port 3 to your Uno. You can double check the port assignment in Device manager > Ports.


How are libraries added to the Arduino library manager? Who curates the list of libraries in the Tools / Manage Libraries menu, and what is the procedure for submitting code for consideration?

You have to submit a ticket to the Arduino GitHub page. If you want to do this in an automated fashion, you can use this python program. Make sure beforehand that your library fits the Arduino library specification.


Why is my SRAM so quickly filled? There are not more than 60 bytes I have just gone through all my code. At max I use 60 bytes. I have done everything in order to minimize its usage - I even store booleans as bits, not bytes! What could be happening here?

The only thing that comes to my mind are extremely large arrays, like this:

const uint8_t SBoxes[8][4][16] PROGMEM;

However, these are stored in the program memory as you can see. How can I check they are really there and my memory usage? My code is too large to post it here.

EDIT:

IDE tells me (even though I believe it's very inaccurate):

  Sketch uses 7,898 bytes (24%) of program storage space. Maximum is 32,256 bytes.
  Global variables use 1,023 bytes (49%) of dynamic memory, leaving 1,025 bytes for local variables. Maximum is 2,048 bytes.

All my literal strings use F() and there are not many of them.

EDIT2:

Code on pastebin. Just for a quick glance, it is really large.

EDIT3:

My Serial prints

ready
some numbers (that's ok I ask it to print out an array)
ENready
again numburs
Enready
...

I ask it to print ready at the very beginning of my program. I ask it to println End of encr near the end of my setup funciton, but as you see it never finishes the printing.

It always behaves like that when I run out of SRAM.

When you are asking yourself what is eating so much RAM, the first step
is to look at the symbol table in the ELF file. If you use a makefile, you
probably know where to find the ELF file. If you are using the Arduino
IDE, go to File / Preferences, check “Show verbose output during
compilation”, compile and look at the output: you will see the temporary
directory where the compiler puts your ELF file.

Now run the command avr-nm -Crtd --size-sort your_elf_file and look
for symbols of type 'D' (data), 'V' (vtable) and 'B' (BSS), in either
upper or lower case. On a Unix-style OS you would pipe through
grep -i ' [dbv] '. Running this on your program gives:

00000068 B tx_buffer
00000068 B rx_buffer
00000034 B Serial
00000021 B lcd
00000016 V vtable for HardwareSerial
00000008 V vtable for LiquidCrystal
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000002 D __malloc_margin
00000002 D __malloc_heap_start
00000002 D __malloc_heap_end
00000002 B __flp
00000002 B __brkval
00000001 b timer0_fract
00000001 D encr
00000001 B debug
00000001 B EEPROM

Obviously, this cannot account for the 1,023 bytes of static RAM your
program is using. What this command misses is the literal arrays and
strings. These can be seen with the command
avr-objdump -j .data -s your_elf_file. The literal strings are quite
obvious in the output, the literal arrays less so. Running this on your
program gives a long listing starting with

Contents of section .data:
800100 00000005 2000010e 040d0102 0f0b0803  .... ...........
800110 0a060c05 09000700 0f07040e 020d010a  ................

Now, on the source code we see:

const uint8_t SBoxes[8][4][16] PROGMEM = {
{{14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
 { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
 { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
 {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13} },
 ...

If you translate this to hexadecimal, you get 0e 04 0d 01 02 0f...,
which appears also by the end of the first line of previous listing. So
there is your culprit: all the big PROGMEM arrays. The compiler does not
honor the PROGMEM attribute on local variables.

My first thought was to make the arrays global, and this does solve the
problem. However, as pointed out by Mikael Patel in a comment, the
documentation on PROGMEM states that “variables must be either globally
defined, OR defined with the static keyword, in order to work with
PROGMEM.” Then, making the arrays static const PROGMEM is a cleaner
solution.


Vary the length of square waveform Here in figure,  we can see two waveforms.

Below one is waveform of raw RPM signal. I want to find square waveform which based on that LOW INTERVAL of RPM signal and length must vary according our requirement. So for that purpose, I just made inverter circuit using 74HC14 and Low pass filter(for removing noise).

As a result of that circuit, I got Upper one waveform means square wave signal. Now, you can see it has also one spike beside square wave(I don't want that). And I can't vary length because inverter circuit gives only perfect inverting signal.

Is it possible to make square wave like this and also vary the length of that square wave with help of Arduino?

Here, I want to use Arduino because I have to vary the length of square wave with help of programming.  For example, if I want 10ms square wave then just enter value 10 in programming then generate 10ms square waveform. Rising edge must be same. And right now, I have no clue or idea how to do this.

If possible then please give me some suggestion how to do this.

The most steightforward decision is to use this spike to trigger interrupt in Arduino. The interrupt procedure starts one of the counters and sets 1 at one of the pins. After N milliseconds by counter or by inner timer the Arduino outputs 0 to the same pin, so you will have needed length of the positive pulse. This will work while pulse length will be less then time between successive spikes. Do not forget to make standard spike amplitude enough to start interrupt, but not too big not to damage Arduino. Of course you can work without interrupts, just testing the input in main cycle, but it will be less presise. You will need a decision, how to conveniently control the pulse length by some tool. It can be infrared pult or some other tool and you must see the set time value, so you will need to use some indicator. May be LCD  1602 keypad shield will be enough for this.


How can I run two loops simultaneously on an Arduino Uno? I'm new to Arduino and I have two devices that I'm trying to control:

A RGB LED light strip that can change colors
A light sensor that can detect the ambient light level

What I'd like to do is have the LED strip continuously cycle through a rainbow of colors, and the light sensor will adjust the brightness of the LED strip based on the ambient light level. Here are the two pieces of code by themselves, which I've tested in isolation and confirmed that they work properly:

LED strip:

j = (j + 1) % 256; // current iteration of the light cycle

// set the strip color
for(int i=0; i< strip.numPixels(); i++) {
  strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
}

// display the new colors and wait 20ms before the next cycle
strip.show();
delay(20);

Light sensor:

sensors_event_t event;
tsl.getEvent(&event); // get a light measurement
strip.setBrightness(event.light); // set the brightness of the LED strip

The problem is that the light sensor takes anywhere from 100ms to 600ms to get a reading, and tsl.getEvent(&event) is a blocking call, so the end result is that the LED strip updates way too slowly. I would need to run the two side by side so that the light sensor read does not block the LED strip update. Any idea how I can accomplish this?

You can make the sensor return data faster by lowering it's accuracy.

tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS);      /* fast but low resolution */

You can also modify the library to not power-down the sensor after each reading. Just open TSL2561.cpp, find the getFullLuminosity function, and comment out the line reading disable(); and the 12 lines reading switch (_integration){ ... }

Another solution is, to have the pixels update every 20ms using a timer. You can have the timer, interrupt the main loop every 20ms and update the pixel values.

(I can't really help you with timers, as I myself set the registers for my timers, and ISRs directly, which isn't for beginners. But there are probably libraries for it, to make it more user friendly.)


IR Receiver interrupt and arduino sleep mode I need to put my arduino into the sleep mode in order to consume less power. My arduino receives IR data and do some work with it, but I need to make it sleep until there is no data. If the data has appeared it should wake up and do something with data and go back to sleep mode.
Is there any way to do this.
I would be grateful for any help.

This is what I have managed to achieve ...

Library

IRLib - GitHub

  Version 1.51 March 2015
  Copyright 2013-2015 by Chris Young http://tech.cyborg5.com/irlib/

  This library is a major rewrite of IRemote by Ken Shirriff which was covered by GNU LESSER GENERAL PUBLIC LICENSE ...

Code

Modified code (from the demo IRrecord example):

/* Example program for from IRLib – an Arduino library for infrared encoding and decoding
 * Version 1.5  June 2014
 * Copyright 2014 by Chris Young http://cyborg5.com
 * Based on original example sketch for IRremote library
 * Version 0.11 September, 2009
 * Copyright 2009 Ken Shirriff
 * http://www.righto.com/
 */

/*
 * IRrecord: records IR signals
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Record a value by pointing your remote at the device
 */

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

const byte LED_PIN = 8;
const byte RECV_PIN = 11;
const unsigned long BAUD_RATE = 115200;
const unsigned long NO_ACTIVITY_TIMEOUT = 2000;  // milliseconds

IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
IRsend My_Sender;
/*
 * Because this version of the library separated the receiver from the decoder,
 * technically you would not need to "store" the code outside the decoder object
 * for this overly simple example. All of the details would remain in the object.
 * However we are going to go ahead and store them just to show you how.
 */
// Storage for the recorded code
IRTYPES codeType;          // The type of code
unsigned long codeValue;   // The data bits if type is not raw
int codeBits;              // The length of the code in bits

// These values are only stored if it's an unknown type and we are going to use
// raw codes to resend the information.
unsigned int rawCodes[RAWBUF]; // The durations if raw
int rawCount;                   //The number of interval samples

bool GotOne, GotNew;

// added by Nick Gammon
EMPTY_INTERRUPT (PCINT0_vect);

void setup()
{
  GotOne=false; GotNew=false;
  codeType=UNKNOWN;
  codeValue=0;
  Serial.begin(BAUD_RATE);
  while(!Serial);//delay for Leonardo
  Serial.println(F("Send a code from your remote and we will record it."));
  Serial.println(F("Type any character and press enter. We will send the recorded code."));
  My_Receiver.enableIRIn(); // Start the receiver
}

// Stores the code for later playback
void storeCode(void) {

  // added by Nick Gammon
  pinMode (LED_PIN, OUTPUT);
  digitalWrite (LED_PIN, HIGH);

  GotNew=true;
  codeType = My_Decoder.decode_type;
  if (codeType == UNKNOWN) {
    Serial.println("Received unknown code, saving as raw");
    // To store raw codes:
    // Drop first value (gap)
    // As of v1.3 of IRLib global values are already in microseconds rather than ticks
    // They have also been adjusted for overreporting/underreporting of marks and spaces
    rawCount = My_Decoder.rawlen-1;
    for (int i = 1; i <=rawCount; i++) {
      rawCodes[i - 1] = My_Decoder.rawbuf[i];
    };
    My_Decoder.DumpResults();
    codeType=UNKNOWN;
  }
  else {
    Serial.print(F("Received "));
    Serial.print(Pnames(codeType));
    if (My_Decoder.value == REPEAT) {
      // Don't record a NEC repeat value as that's useless.
      Serial.println(F("repeat; ignoring."));
     }
     else {
       codeValue = My_Decoder.value;
       codeBits = My_Decoder.bits;
     }
     Serial.print(F(" Value:0x"));
     Serial.println(My_Decoder.value, HEX);
  }

  // added by Nick Gammon
  pinMode (LED_PIN, INPUT);
  digitalWrite (LED_PIN, LOW);

}

void loop() {

  // added by Nick Gammon
  static unsigned long lastActivity;  // when we last woke
  // sleep if no activity for a while
  if (millis () - lastActivity >= NO_ACTIVITY_TIMEOUT)
    {
    Serial.flush ();  // wait for Serial to finish outputting
    Serial.end ();    // shut down Serial
    noInterrupts ();  // timed sequence coming up

    // pin change interrupt for D11
    PCMSK0 |= bit (PCINT3);  // want pin 11
    PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
    PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13

    set_sleep_mode (SLEEP_MODE_STANDBY);
    sleep_enable();

    byte old_ADCSRA = ADCSRA;
    // disable ADC to save power
    ADCSRA = 0;
    power_all_disable ();  // turn off various modules
    interrupts ();
    sleep_cpu ();
    sleep_disable();
    power_all_enable ();   // enable modules again
    ADCSRA = old_ADCSRA;   // re-enable ADC conversion
    Serial.begin(BAUD_RATE);
    lastActivity = millis ();
    }  // end of no activity for a couple of seconds

 if (My_Receiver.GetResults(&My_Decoder)) {
    My_Decoder.decode();
    GotOne=true;
    storeCode();
    delay(500);
    My_Receiver.resume();
  }
}

Explanation

Main changes are in loop (near the bottom) where it sleeps if there is no activity for two seconds. This "no activity" test gives it time to catch an incoming pulse stream.

Before sleeping it turns off Serial (to save power), and sets up to detect the pin-change interrupt. It also turns off the ADC, and calls power_all_disable to disable various internal modules.

Note that it uses pin-change interrupts on Arduino pin D11 (pin 17 on the chip). For a different processor than the Atmega328P, or a different input pin, you would have to change which pin-change interrupt is used.

I found that I had to use SLEEP_MODE_STANDBY rather than SLEEP_MODE_PWR_DOWN, otherwise it seemed to take too long to wake up and handle the incoming pulse.

For testing, I flashed D8 pin to make sure it was working when hooked up in low-power configuration.

Power consumption

I tested with an AX-1838T IR-receiver that I had to hand (same pin-outs as in the Adafruit article).

Measured stand-alone (ie. not connected to the Arduino) it consumed 630 µA, so therefore we could not expect lower power consumption than that.

Connected up to a "bare-bones" board (ie. just the Atmega328P chip, decoupling capacitors, etc.) I measured 1.158 mA when idle.

My tests on my page about power indicate that SLEEP_MODE_STANDBY uses 480 µA more power than SLEEP_MODE_PWR_DOWN, so this sounds about right.

630 + 480 = 1110 µA

You might be able to save more power by operating at a lower voltage. This particular receiver can operate at a lower voltage. As an indication, I tried the setup at 3.3 V (which is out of spec for the processor, but whatever, I was just testing) and it consumed 978 µA when idle. This is a modest saving over the 5 V test.

References

Power saving
Interrupts
Adafruit IR library
IR library source


When is SPI.beginTransaction required? I have been gradually converting many devices from i2c to spi for various reasons.  I noticed in tutorials like this from arduino.cc that SPI.beginTransaction is explicitly called out.  Then they link to examples such as this and this where they don't use SPI.beginTransaction.  In working through my own devices I found that I could often (almost always) forgo the use of SPI.beginTransaction.  The only case where I found problems was when I had 2 devices that used different SPI settings.
I went to Google and other searches for a simple reason for SPI.beginTransactions and found discussions of interrupts and locks and settings.  There was much discussions about users applications wrapping all calls with SPI.beginTransaction and SPI.endTransaction.  There were bugs when libraries didn't wrap everywhere.
This leads me to the conclusion that making calls to SPI.beginTransaction are only needed when the SPI settings need to change, but in practice you should always do it.  Is there documentation or examples that definitely state the purpose and proper (best practice) usage of it?

It appears calling the method beginTransaction() prevents additional SPI transactions from interrupting the current transaction.  Calling endTransaction() allows access to the SPI hardware again. This added complexity may sound odd.  Especially in the simple Arduino sketch-writing paradigm.  But as programs grow in complexity, more SPI devices are added and interrupts are used to quickly access SPI devices - the likely hood of SPI contention increases.
In the SPIClass source code, there is this comment immediately before the beginTransaction() method:
  // Before using SPI.transfer() or asserting chip select pins,
  // this function is used to gain exclusive access to the SPI bus
  // and configure the correct settings.

So, it may be, that if the sketch-code is particularly well behaved and does not need protection from accidentally using the SPI hardware from multiple concurrent transactions, that these two methods need not be used.  But why take the chance.


Waterlevel sensor disrupts PH reading I have a water level sensor and a PH sensor connected to my nodemcu via an ADS1115 . When I insert only the PH sensor into the water then everything works fine. But when I insert the waterlevel sensor into the same container the PH sensor seems to shortcircuit and I get 5V no matter the actual PH level. Is there anything im missing or a way to prevent that from happening?

That water level sensor uses bare metal which is in contact with the water. The PH sensors are sensitive for that kind of voltage in the water, even if it would be 0V.

There are isolated PH sensor amplifier modules. On forums are often discussions whether to ground an aquarium or not for a PH sensor. With a isolated PH sensor, you avoid most of those problems.

There are also non-contact water level sensors. For example capacitive sensor or even sensors that can be attached on the outside. Some sensors use the water pressure, but I don't know if this one is isolated: https://www.sparkfun.com/products/10221


ATMEL SAMD11 SPI (Slave) With Arduino (Master) I am trying to get my Atmel SAMD11 XPLAINED PRO and arduino to talk to each other using SPI. I have set up the arduino as the master, with the SAMD11 as the slave. On the ATMEL, I have the following code:

http://asf.atmel.com/docs/latest/samd21/html/asfdoc_sam0_sercom_spi_slave_callback_use.html

Essentially, it waits until the master sends data, compares the data with what it expects, and updates an LED accordingly. On the arduino side, I have the following:

#include <SPI.h>

#define BUF_LENGTH 20
int slave_select = 10;

void setup (void)
{
  // Initialize serial for DEBUG.
  Serial.begin(9600);
  pinMode (slave_select, OUTPUT);
  digitalWrite(slave_select, HIGH);  // ensure SS stays high for now
  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.beginTransaction (SPISettings (4000000, MSBFIRST, SPI_MODE0));  // 4 MHz clock, MSB first, mode 0
  // Master initialized.
  Serial.println("Master Initialized");
}  // end of setup

void loop (void)
{
  static uint8_t buffer_expect[BUF_LENGTH] = {
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
     0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13
  };
  // enable Slave Select
  digitalWrite(slave_select, LOW);    // SS is pin 10

  //write the 20 bytes
  for (int I=0;I<20;I++)
  {
    SPI.transfer(buffer_expect[I]); //write data byte
    delay(20);
  }

  // disable Slave Select
  digitalWrite(slave_select, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

When I run the code, the LED on the SAMD11 isn't updated, which means that it is waiting for data to be sent, and hasn't received any, despite what the arduino code writes. On the hardware side, I have GND connected on both boards, VCC on the SAM to 5V on the arduino, and SPI_SS_A, MOSI, MISO and SCK connected to pins 10,11,12 and 13 on the arduino respectively.

You haven't set your SS pin as an output anywhere in your code.

The arduino page you linked to has a note near the bottom which reads:

  Note about Slave Select (SS) pin on AVR based boards

  All AVR based boards have an SS pin that is useful when they act as a
  slave controlled by an external master. Since this library supports
  only master mode, this pin should be set always as OUTPUT otherwise
  the SPI interface could be put automatically into slave mode by
  hardware, rendering the library inoperative. It is, however, possible
  to use any pin as the Slave Select (SS) for the devices. For example,
  the Arduino Ethernet shield uses pin 4 to control the SPI connection
  to the on-board SD card, and pin 10 to control the connection to the
  Ethernet controller.

The Example code given for the teensy board on the other page you linked has:

pinMode (slaveSelectPin, OUTPUT);

in its setup() function.

So that's what you're missing.
Setting the pin high or low is not going to achieve anything if its not an output.

Remember that SPI can access many diffrent devices using the same MOSI/MISO/SCK pins, but each slave device has its own Slave-Select pin which needs to be individually driven by the master.
Your master can therefore have many different SS pins, all set as outputs - and there is no single standard pin for this.


When does interrupt get fired When does the ISR mapped to SPI_STC_vect (SPI transmission complete) get fired? Does it fire after a byte has been received (eight clock cycles) of when the slave select changes back to high to deselect the slave?
Or: does "transmission" mean the transmission of a byte or the whole bunch of bytes that belong to the command sequence?

It fires after a single byte has been sent or received (the two are one and the same). This is because there is only room for one byte in the buffer, so you need to get it out of that buffer (or put a new one in) after each 8-bit transfer.


IR module sensor query for Line Follwer Robot Are the IR sensors used in Line following Robot and Obstacle avoidance Robot with Arduino UNO different ? If yes , where do we buy these parts online ? I used the following sensor in my Line Follower and am not getting result as it’s detecting obstacle instead of black line .

The sensor you have used is fine. There is a potentiometer on the sensor PCB that is used for the range. For the line following robot you would want the range small, between 1-4cm. However, for the obstacle avoidance robot you would want to set this for a much larger range, say 10-45cm.

To make an effective line following robot you need at least 2-3 sensors.

Here is one using 2 LEDs either side of the line:

And here is a 3 sensor robot:

Notice that one LED stays on the line.

And finally a 5 sensor robot:

The following websites have good step by step guides where they explain the various techniques:

https://www.learnrobotics.org/blog/how-to-build-a-mobile-robot-using-arduino-part-4/
https://circuitdigest.com/microcontroller-projects/line-follower-robot-using-arduino
http://www.robotc.net/wikiarchive/Tutorials/Arduino_Projects/Mobile_Robotics/VEX/Using_the_line_tracker_to_follow_a_line

When I made my line following robot I used 2 of the following sensor:

These sensors were great as they pointed in towards each other, making a focal point. You can do this to your sensor by bending the LEDs slightly towards each other.


SparkFun Monster Moto Shield current sensing issue I am using a SparkFun Monster Moto Shield (PDF) for driving two DC motors. The shield is working fine and I am able to drive the motor in both directions. However, the current sensing is continuously showing "zero" in the serial monitor.

I am confused why the shield is not measuring any current. I want to measure normal current of 750 mA and stall current of 6 A but I'm getting zero value continuously. If anyone can help me I shall be very thankful.

Can you show us how your code is looking like? Please remember that you can not measure current directly, the method that is used to do that is to measure voltage drop on measuring resistor.
Check this image


Write to EEPROM before shutdown I'm currently designing a battery operated device that has to write data to an EEPROM before shutting down, or in regular intervals to save data. Would it damage the EEPROM if it had to shut down while it is being written to?

The first possible case is when it is transmitting the data over I2C. That shouldn't affect it much. But if it gets powered down while it is actually writing the byte to its memory, I don't know whether it would save it correctly or corrupt it.

According to the datasheet, an EEPROM write takes 3.3mS. If power drops below the level needed to complete the write, the data will be corrupted.


Multiple non-blocking countdown timers? I'm building a control system for three sump pumps using a single Arduino and a set of relays.  I have float sensors for each one, and need the Arduino to trigger the relays when the float sensors are triggered.  Sensor 1 triggers pump 1, sensor 2 triggers pump 2, etc.

Simple enough, but I also need each pump to remain on for 30 seconds after its float sensor returns to normal.  This throws me for a loop since I need the other pumps and sensors to function during this delay time.  I quickly found that the blocking delay() function is no longer feasible.

How can I trigger the relays, keep them on for 30 seconds after the sensors return to normal, but all the while still monitor and control the other sensors/relays?  Would a non-blocking timer solution work?  Would I have to delve into interrupts?

Would a non-blocking timer solution work?

Yes.  Your "timer" doesn't have to be anything more than a start time from millis() and a flag.  Then your loop just compares the start time to the current millis() value, and if it's more than the interval you wanted, do the "thing".  In code:

uint32_t startTime;
bool waiting = false;
const uint32_t PUMP_DURATION = 30000UL;

void setup()
{
  // start the "timer"
  startTime = millis();
  waiting = true;
}

void loop()
{
  if (waiting && (millis() - startTime >= PUMP_DURATION)) {
    waiting = false;
    // do something now!
    foo();
  }

The flag keeps it from checking when the pump isn't running.

If you have multiple timed things, just make another set of variables (i.e., startTime2 and waiting2).  Give 'em better names, eh?

There are also Arduino libraries that encapsulate this common design pattern.  TimeMark is one.

Here's some sample code on the Arduino forum.


Fade In/Fade Out with multiple LED strips I want to make a strip led application(Fade In/Fade Out).Each strip has 48 pixels.One of the strips should be red and the other should be blue.Using the for loop, I managed to fade in-fade out a small number of strips (eg 10).But when I fade in / fade out all of the 48 leds, the code behaves as if there is a "delay".I guess that's because there's a lot of data in the for loop.Is there a way to do fade in / fade out without using a for loop?

#include "FastLED.h"
#define NUM_LEDS_PER_STRIP 48
CRGB redLeds[NUM_LEDS_PER_STRIP];
CRGB blueLeds[NUM_LEDS_PER_STRIP];
void setup() {
FastLED.addLeds<NEOPIXEL, 6>(redLeds, NUM_LEDS_PER_STRIP);
FastLED.addLeds<NEOPIXEL, 7>(blueLeds, NUM_LEDS_PER_STRIP);
FastLED.setBrightness(0);
}

void loop() {
//fade in
for(int i=0;i<256;i=i+5) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i);
redLeds[j] = CRGB(255,0,0);
blueLeds[j] = CRGB(0,0,255);
FastLED.show();
}}
//fade out
for(int i=255;i>=0;i=i-5) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i);
redLeds[j] = CRGB(255,0,0);
blueLeds[j] = CRGB(0,0,255);
FastLED.show();
}}
}

Each change of brightness requires sending out 48 LEDs x 3 bytes/strip, = 144 bytes = 1152 bits of data. Each bit needs 2.5uS of data, so 2.88mS minimum at 400 KHz data rate. I don't know what rate FastLED.h uses, might be as fast as 800 KHz. How many strips? 2? So double that.

Each string needs all of its data sent out if any one LED changes, so you might change 1 LED, and leave 143 alone, all the data still gets sent out. That's just the way the addressable strips work.


Using MCP23017 with 5 rotary encoders, WITHOUT missing a single step from any of them? I have recently followed the instructions in the answer to this question:
Reading several rotary encoders
posted by maximilian-gerhardt
I've wired everything up, and am using the interrupts example that can be found here:
https://github.com/maxgerhardt/rotary-encoder-over-mcp23017/tree/master/examples/Interrupt
Everything seems to work as expected, except that my assumption was that since this was an interrupt-based solution, that I wouldn't be missing any steps of any of the encoders. There are a total of 5 that will move at the same time, and it is clear that while it almost works, there are many steps that are missed.
I'm guessing that is because while one interrupt is being handled, all other interrupts are disabled?
Is there any way where I can ensure that every single motion (step CW or CCW) is registered on all 5 encoders?
Thanks!
Brian

Interrupts don't mean that you can do lots of things at the same time. All they mean is that something can be responded to rapidly, as long as nothing else is being responded to of an equal or higher priority.
And coupling that with an IO expander which will inevitably slow things down means that you really can't do what you are trying to do.
If you want to respond instantly to every single pulse of every single encoder then each encoder has to be attached to something that can itself respond to those pulses.
I would be inclined to have a small microcontroller attached to each individual encoder (or maybe two encoders if you have enough interrupt pins) and deal with each separately - that way one encoder cannot interfere with any other. The small MCU can then keep track of position or count (depending on what it is you are trying to do) and you communicate that to a "master" controller (the Arduino for example) over some other bus, asynchronously to the encoder's pulses.
If you want more rapid response to the encoder movements then it could be possible to implement your own interrupt signal from the small MCU to the Arduino to say "My encoder has been moved", at which point the Arduino can collect the data. It won't matter how long that takes to happen as the small MCU will be keeping track of any other changes. The ATTiny85 using Pin Change Interrupts could be a good low-cost choice for this.


Why can't this C++ program read my arduino's Serial.write()? I made a super simple arduino uno sketch to send a serial byte once every second:

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

void loop(){
   Serial.write(12); // send a byte with the value 12
   delay(1000);
}

My arduino is hooked up to com 3.

On the other end of the line, I have a C++ program with the following read function:

int Serial::ReadData(char *buffer, unsigned int nbChar)
{
    //Number of bytes we'll have read
    DWORD bytesRead;
    //Number of bytes we'll really ask to read
    unsigned int toRead;

    //Use the ClearCommError function to get status info on the Serial port
    ClearCommError(this->hSerial, &this->errors, &this->status);

    //Check if there is something to read
    if(this->status.cbInQue>0)
    {
        //If there is we check if there is enough data to read the required number
        //of characters, if not we'll read only the available characters to prevent
        //locking of the application.
        if(this->status.cbInQue>nbChar)
        {
            toRead = nbChar;
        }
        else
        {
            toRead = this->status.cbInQue;
        }

        //Try to read the require number of chars, and return the number of read bytes on success
        if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
        {
            return bytesRead;
        }

    }

    //If nothing has been read, or that an error was detected return -1
    return -1;

}

This seems to check only one time if data is available, so obviously I have to loop through it until data comes in.  I did that in my main program:

#include "Serial.h"
#include <iostream>

using namespace std;

int main(void)
{
    Serial serial("COM3");

    char* c = "";
    int len = strlen(c);
    while(c == "")
    {
        serial.ReadData(c, len);
    }

    cout << "\n\n";
    system("PAUSE");
}

When I do this, my C++ program gets stuck in an infinite loop waiting for data from the arduino, and I cannot figure out why this is happening.  My program never sees the data the arduino is sending.

This Serial class works and is configured properly because I can SEND all the data I want to the arduino without any problems.  My issues are only with reading back from the arduino.

Can someone please help me figure out why this is not working?

The problem is in your C++ program at the other end of the line (not the Arduino side):

char* c = "";
int len = strlen(c);
while(c == "")
{
    serial.ReadData(c, len);
}

Here, len is zero because that is the length of "" , the empty string! Thus, in your loop, you ask ReadData to read 0 bytes. Hence, the condition of your while loop is always true as, c never changes.

Also, the while condition seems incorrect as it is not recommended in C++ to compare 2 strings (defines as char * or char [...]) with ==. In your situation, what is important is the number of characters read by ReadData:

char c[LEN + 1];
int numBytes = 0;
while(true)
{
    numBytes = serial.ReadData(c, LEN);
    if (numBytes != -1)
    {
        // Terminate the string if we want to use c variable as a string
        c[numBytes] = 0;
        break;
    }
}

in the code above, LEN is the number of characters you want to read at one time, in you example it should be set to 1, either as a #define or as a const variable:

// either:
#define LEN 1
// or:
const int LEN = 1;

The code above also ensures that c can be used as a normal string, by adding a 0 at the end. This is mandatory only if you want to use string functions on c such as strlen, strcpy, strchr... otherwise numBytes is enough to manage the number of characters read into c.


Error when compiling code NODE MCU ESP8266-12E module in Arduino ide Here is my sketch:

#include<ESP8266WiFi.h>

char* ssid = "xxxxxxxx";
char* pass = "xxxxxxx";

void setup() {
 WiFi.begin(ssid,pass);
 Serial.begin(9600);
 while(WiFi.status()!=WL_CONNECTED)
 {
  Serial.print(".");
  delay(500);
  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.print(WiFi.localIP());
}

Here is the error:

Traceback (most recent call last):   File "C:\Users\ASUS\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2/tools/upload.py", line 25, in <module>
    esptool.main(fakeargs)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 2653, in main
    esp.connect(args.before)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 460, in connect
    last_error = self._connect_attempt(mode=mode, esp32r0_delay=False)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 440, in _connect_attempt
    self.sync()   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 379, in sync
    timeout=SYNC_TIMEOUT)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 322, in command
    self.write(pkt)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 285, in write
    self._port.write(buf)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/pyserial\serial\serialwin32.py", line 323, in write
    raise writeTimeoutError serial.serialutil.SerialTimeoutException: Write timeout the selected serial port
serial.serialutil.SerialTimeoutException: Write timeout  does not
exist or your board is not connected

The section

void loop() {
}

Is missing in the code, add it and recompile and.....


How to combine time into a variable I have an Arduino Uno project which is recording student attendance using fingerprint sensor. So when sensor found a match, the serial monitor will be printing out Student ID and current time like this:

    DateTime now;
    void setup()
      {
          ...
      }

    void loop()
      {
          .....
          //found a match
          Serial.print("Found ID #");
          Serial.println(finger.fingerID);
          Serial.print("Time->");
          Serial.print(now.hour(), DEC);
          Serial.print(':');
          Serial.print(now.minute(), DEC);
          Serial.print(':');
          Serial.print(now.second(), DEC);
      }

Sample result will be:

Found ID#1
Time-> 18:11:54

I would like to store the time into a variable and print it out instead of printing hour, minute, second separately. How can I do that???

I have tried to do like this as below but im getting error, I would like to store it as a string. How can I do that?

string time = now.hour() + ':' + now.minute() + ':' + now.second();

You want to use snprintf for this:

char timeString[9];

snprintf(timeString, 9, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
Serial.println(timeString);

By using a format string like this you are taking into account time portions < 10 (like 7 minutes and 23 seconds past 3 am, which would otherwise be 3:7:23) by padding the time with leading zeroes where needed.


How do I use ATTiny pin 5 (RESET) as a digital output? I am using an Arduino Uno as ISP (Using the standard ArduinoISP sketch) to program an ATTiny13A through the Arduino IDE. (I also have a USBtinyISP 2.0 and a USBASP 2.0, but can't reliably get either to program this chip with any sketch.)

I want to use all six I/O pins on the ATTiny to each control 1 LED. Pins 0 through 4 work fine, but since pin 5 is the RESET pin, it doesn't want to work as an output normally.

I have read from many sources that I can disable the reset pin by changing the fuse bits, and that once I do so I will not be able to program the chip any more. Every source I've seen has given this warning, but has then proceeded to NOT say how to accomplish the 1-time-write.

Assume I've got my sketch exactly 100% as I want it, don't have a high-voltage programmer, and am fine with only being able to program the ATTiny once. How can I program the chip and set the appropriate fuse bits with what I have access to?

RSTDISBL is bit 0 of the high fuse byte. Use avrdude to read the current value of the high fuse byte (-U hfuse:r:-:h), clear bit 0, and then write the value back out (-U hfuse:w:0xXX:m).


WiFiClient::connected() not working I use an ESP32 to open an access point and listen for TCP connections over a WiFiServer object.

When I get a client on the server I want to know when it has disconnected.

Currently I have a simple piece of code on both the client and the server side. I connect using a TcpClient in C#.

When I call client.close() on the client side, the client.connected() loop on the server just continues forever.

Here is the ESP code:

void setup()
{
   WiFi.mode(WIFI_AP);

   WiFi.softAP("test");

   WiFi.softAPConfig(IPAddress(192, 168, 4, 1), IPAddress(192, 168, 4, 1), IPAddress(255, 255, 255, 0));

   Serial.println(WiFi.localIP());

   server.begin();
}

void loop()
{
    while (!client)
    {
        client = server.available();

        delay(10);
    }

    while (client.connected())
    {
        Serial.println("ok");

        delay(1000);

        client.read();
    }
}

C# code:

static void Main(string[] args)
{
     TcpClient client = new TcpClient("192.168.4.1", 222);

     client.Close();
}

This is a bug in a previous version of the library as mentioned on
https://github.com/bportaluri/WiFiEsp/issues/14

You can alternatively use WiFi.softAPgetStationNum() to get the count of stations connected to the AP interface.


How can I connect an arduino to a raspberry pi via an HC 05 bluetooth module and transmit data? I am currently undertaking a project where I am attempting to build a bluetooth thermometer using an arduino.
I have the temperature sensor working and returning temperature readings via a usb connection to the serial monitor in the Arduino IDE using the following code.

#include <OneWire.h>
#include <DallasTemperature.h>
#include "Timer.h"

Timer t;

// Data wire is plugged into pin 10 on the Arduino
#define ONE_WIRE_BUS 10

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

DeviceAddress insideThermometer = { 0x28, 0x94, 0xE2, 0xDF, 0x02, 0x00, 0x00, 0xFE };

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  // Start up the library
  sensors.begin();
  // set the resolution to 10 bit (good enough?)
  sensors.setResolution(insideThermometer, 10);
  int tickEvent = t.every(3000,doTempReading);

}

void loop()
{
    t.update();
}

void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC == -127.00) {
    Serial.print("Error getting temperature");
  } else {
    Serial.print("C: ");
    Serial.print(tempC);
  }
}

void doTempReading()
{
  delay(2000);
  Serial.print("Getting temperatures...\n\r");
  sensors.requestTemperatures();

  Serial.print("Inside temperature is: ");
  printTemperature(insideThermometer);
  Serial.print("\n\r");
}

I now want to try and transmit the readings via a bluetooth connection using the HC 05 module to a raspberry pi which will record the data.

I have done a lot of research and tried several different techniques and can't understand how to go about it.

What mode does the HC 05 need to be in? (Command AT/slave/data/etc.)
How should it be wired (I have found several different methods using various resistors and capacitors and unsure which to follow).
How should I pair it with the Raspberry pi?

Thanks in advance for any help.

I know this is old but to help out newcomers:
Here's a place you can begin https://create.arduino.cc/projecthub/millerman4487/view-serial-monitor-over-bluetooth-fbb0e5
The wiring depends on which arduino board you are using and the model of your HC-05 BT module. mine uses 4 pins VCC (5v) GND (ground) TX --> TX and RX --> RX
You should be able to google the wiring for your module, and connect to the raspberry pi after you install bluetooth on raspberry pi
sudo apt-get install bluetooth bluez blueman

sudo reboot

Navigate to new bluetooth interface in menu bar through

preferences
bluetooth

Add new device, turn arduino on with BT module plugged in and make sure your HC-05 module is blinking red, and you should see a pair connection named HC-05 on raspberry pi. Password is 1234


How to read bytearray from arduino pin in arduino sketch I'm using the DYP-ME007TX sensor with arduino uno.
The output from this sensor comes in packets of 4-bytes:

Data[0]= 0xFF: Packet Header
Data[1]= 0x0-0xFF: Data Most Significant Byte (MSB)
Data[2]= 0x0-0xFF: Data Least Significant Byte (LSB)
Data[3]= 0x0-0xFF: Data Checksum: = (0XFF + MSB + LSB) &amp; 0xFF

Data is in MILLIMETERS

16 bit value in mm = Data[1] << 8 | Data[2]

How can exctract this packet in arduino sketch and extract millimeter number?

I found the answer from forum.arduino.cc
There is a sketch

#include <SoftwareSerial.h>

// TX_PIN is not used by the sensor, since that the it only transmits!
#define PING_RX_PIN 6
#define PING_TX_PIN 7

SoftwareSerial mySerial(PING_RX_PIN, PING_TX_PIN);

long inches = 0, mili = 0;
byte mybuffer[4] = {0};
byte bitpos = 0;

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

  mySerial.begin(9600);
}

void loop() {
  bitpos = 0;
  while (mySerial.available()) {
    // the first byte is ALWAYS 0xFF and I'm not using the checksum (last byte)
    // if your print the mySerial.read() data as HEX until it is not available, you will get several measures for the distance (FF-XX-XX-XX-FF-YY-YY-YY-FF-...). I think that is some kind of internal buffer, so I'm only considering the first 4 bytes in the sequence (which I hope that are the most recent! :D )
    if (bitpos < 4) {
      mybuffer[bitpos++] = mySerial.read();
    } else break;
  }
  mySerial.flush(); // discard older values in the next read

  mili = mybuffer[1]<<8 | mybuffer[2]; // 0x-- : 0xb3b2 : 0xb1b0 : 0x--
  Serial.print("PING: ");
  Serial.print(mili/10);
  Serial.println("sm");
  delay(500);
}


How to change i2c address of Lidar Lite v3 using LidarLite library (Solved) I have 2 Lidars which are Lidar Lite v3 and Lidar Lite v4, both of these sensor having the same i2c address.
I'm trying to change my Lidar Lite v3's i2c address on arduino mega2560 using a function from LidarLite library from 0x62 to 0x63. However it doesn't seem to work, after I uploaded a code the serial monitor display
> nack

and when I'm using i2c scanner it still show a default address (0x62).
here is my arduino code
#include <Wire.h>
#include <LIDARLite.h>

LIDARLite myLidarLite;

void setup(){
  Serial.begin(115200); // Initialize serial connection to display distance readings
  char newAddress = 0x63;
  myLidarLite.setI2Caddr(newAddress , true);
  Wire.begin();
}

void loop(){

  **** i2c scanner code ****

}

setI2Caddr function from library
void LIDARLite::setI2Caddr(char newAddress, char disableDefault, char lidarliteAddress)
{
  byte dataBytes[2];

  // Read UNIT_ID serial number bytes and write them into I2C_ID byte locations
  read ((0x16 | 0x80), 2, dataBytes, false, lidarliteAddress);
  write(0x18, dataBytes[0], lidarliteAddress);
  write(0x19, dataBytes[1], lidarliteAddress);

  // Write the new I2C device address to registers
  dataBytes[0] = newAddress;
  write(0x1a, dataBytes[0], lidarliteAddress);

  // Enable the new I2C device address using the default I2C device address
  dataBytes[0] = 0;
  write(0x1e, dataBytes[0], lidarliteAddress);

  // If desired, disable default I2C device address (using the new I2C device address)
  if (disableDefault)
  {
    dataBytes[0] = (1 << 3); // set bit to disable default address
    write(0x1e, dataBytes[0], newAddress);
  }
}

I've checked a read function and found this condition
    // A nack means the device is not responding, report the error over serial
    int nackCatcher = Wire.endTransmission();
    if(nackCatcher != 0)
    {
      Serial.println("> nack");
    }

the datasheet of Lidar Lite v3 is here and changing i2c address topic can be found in 5th page
I've tried to compare the function to a datasheet but still have no idea why it didn't work.
So, how can I change an I2C address of Lidar Lite v3 to make them able to work together?

Update
Finally I have found the mistake. The simple way to fix is just call function Wire.begin() or myLidarLite.begin() (which containing Wire.begin inside the function) before using setI2Caddr().
So, the code will be like this
#include <Wire.h>
#include <LIDARLite.h>

LIDARLite myLidarLite;

void setup(){
  Serial.begin(115200); // Initialize serial connection to display distance readings
  Wire.begin(); // or myLidarLite.begin();
  char newAddress = 0x63;
  myLidarLite.setI2Caddr(newAddress , true);
}

void loop(){
  **** i2c scanner code ****
}

After upload to the board, the address is finally changed.
Ps. Btw, when I set 0x64 to setI2Caddr it changed to 0x63 instead of 0x64 and still keep the old address eventhough I set disabledefault as true.

You probably need to use LIDARLite_v3HP.h. The setI2Caddr() function is not same between LIDARLite_v3HP.h and LIDARLite.h.
The datasheet you provided, has the instruction on how to update the I2C address. LIDARLite_v3HP.h's setI2Caddr() followed those instructions.
To check, if you go to this line of the source code of LIDARLite.h, you will see the function doesn't write 0x08 to 0x1e, instead writes 0x00. Either that's how it was in the earlier versions or maybe it's a bug.
Also, it is mentioned in the datasheet that, if you power cycle the Lidar the address will be restored to default.

Update
After I gone through the library more carefully I noticed that writing `0x08` into `0x01` is actually handled but differently in the `LIDERLite.h'.
Here is the setI2Caddr() code from the library (check the last two lines):
void LIDARLite::setI2Caddr(char newAddress, char disableDefault, char lidarliteAddress)
{
  byte dataBytes[2];

  // Read UNIT_ID serial number bytes and write them into I2C_ID byte locations
  read ((0x16 | 0x80), 2, dataBytes, false, lidarliteAddress);
  write(0x18, dataBytes[0], lidarliteAddress);
  write(0x19, dataBytes[1], lidarliteAddress);

  // Write the new I2C device address to registers
  dataBytes[0] = newAddress;
  write(0x1a, dataBytes[0], lidarliteAddress);

  // Enable the new I2C device address using the default I2C device address
  dataBytes[0] = 0;
  write(0x1e, dataBytes[0], lidarliteAddress);

  // If desired, disable default I2C device address (using the new I2C device address)
  if (disableDefault)
  {
    dataBytes[0] = (1 << 3); // set bit to disable default address
    write(0x1e, dataBytes[0], newAddress);
  }
}

All you have to do is set disableDefault to any positive int when you call setI2Caddr().


How can I detect which baudrate a virtual COM port is set to? I would like my software running on Leonardo to behave differently depending on the baudrate of the USB Serial set by the PC. For example, I want to make a smart USB to UART converter which performs some processing of the data it transmits. It would be much more elegant to set the UART baudrate to whatever value the PC is requesting on USB side, rather than hardcoding a value.

AFAIK 32u4 chip is used as a USB to UART converter on Mega, where it supports different baudrates, so this should be doable.

I also have a Teensy 3.2 board, so if anyone knows how to detect the baudrate on this board I'm also interested.

From looking at the source it appears that on 32u4 based boards Serial  includes extra methods to access the settings from the USB host:

see: https://github.com/arduino/ArduinoCore-avr/blob/b7c607663fecc232e598f2c0acf419ceb0b7078c/cores/arduino/USBAPI.h#L129

From USBAPI.h:

// These return the settings specified by the USB host for the
// serial port. These aren't really used, but are offered here
// in case a sketch wants to act on these settings.
uint32_t baud();
uint8_t stopbits();
uint8_t paritytype();
uint8_t numbits();
bool dtr();
bool rts();


Sending value from Arduino to MySQL using ESP8266 I am trying to send a value from Arduino to a remote MySQL. I am following this tutorial.

I have tried but no data is received on the server. What is the issue? I am new to Arduino. My code is:

int led1=8;
int count=1;
void setup() {
  pinMode(led1, OUTPUT);
  delay(3000);
  // initialize serial communication at 9600 bits per second:
  Serial.begin(115200);
  Serial.println("AT+CWMODE=1");
  delay(1000);
  Serial.println("AT+CWJAP=\"mhboys\",\"mhboys123\"");
  delay(1000);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led1,HIGH);
  // turn the LED on (HIGH is the voltage level)
  delay(1000);  // wait for a second
  if(digitalRead(led1)==LOW) {}
  if(digitalRead(led1)==HIGH) {
    count++;
    //code for sending updated count to mysql
  }
  digitalWrite(led1, LOW);
  // turn the LED off by making the voltage LOW
  delay(1000); // wait for a second
  int adjustedValue = count;
  // print out the value you read:
  Serial.println("AT+CIPSTART=\"TCP\",\"www.onemediagroup.in\",80");
  delay(1000);
  Serial.println("AT+CIPSEND=66");
  delay(1000);
  Serial.print("GET /energy/getUsage.php?currentValue=");
  Serial.print(adjustedValue);
  delay(1000);
  Serial.println("AT+CIPCLOSE");
  digitalWrite(13, HIGH);
  delay(100000); // delay in between reads for stability
}

You're sending commands blindly without checking if they actually succeeded. If you're not ready to correctly handle the responses, you're better off using a library like this. The 'HTTP GET' example should help.


How to read data from an NI DAQ? I'm using an Arduino to control an experimental setup and read analogue signals from some sensors. But there are other sensors for which I need a DAQ for. I have a National Instrument USB-6259. On my PC I use LabView or NI SignalExpress to read data from DAQ connected via USB. Considering that I want the read data from different sensors to be synced, I was wondering if I could somehow read the DAQ directly on the Arduino?

Some other points:

I also have Arduino Ethernet Shield, if required.
The final goal is to have logged data synced so out of the box solutions are also acceptable for me.
If I'm not mistaken there are some versions of Arduino which you can install Linux on, just like a Rasppbery pi. There are even OSes for normal Arduino boards. There is a Low Cost USB DAQ Driver for use with Raspberry Pi for NI USB-6008/6009 devices. Is it possible to install this driver on Arduino?
I prefer not use a Raspberry pi because analogue/PWM read and write there is not as straight forward. So if there are other boards which are as easy as an Arduino with an OS compatible with current driver please suggest.

Unlikely.

First you would need a USB shield to be able to plug it in.

Second you would have to reverse engineer and then reimplement the proprietary protocols that device uses in order to get the Arduino to control the device.


analogRead function not working in MATLAB I am new to Arduino and I am trying to control it through MATLAB.  I have downloaded the arduino IO package and installed it.I am using MATLAB 2014a.I have a LED and I change its brightness by changing the PWM voltage as follows :

a=arduino('COM3');
brightness_step = (5-0)/20;
   for i = 1:20
      writePWMVoltage(a, 11, i*brightness_step);
      val=a.analogRead(0);
      display(val)
      pause(0.1);
   end

   for i = 1:20
      writePWMVoltage(a, 11, 5-i*brightness_step);
      val=a.analogRead(0);
      display(val)
      pause(0.1);
   end
clear a

Everything works great except for the analogRead part which throws the following error :
No appropriate method, property, or field analogRead for class arduino.

What am I doing wrong?

That function is part of legacy code.

  NOTE: This solution (formerly known as "Arduino IO Package") is no
  longer supported. It is recommended that you use Arduino support
  packages that are developed and supported by MathWorks:

  MATLAB Support Package for Arduino Hardware: Read, write, and analyze data from Arduino sensors
  http://www.mathworks.com/hardware-support/arduino-matlab.html
  Simulink Support Package for Arduino Hardware: Develop algorithms that run standalone on your Arduino
  http://www.mathworks.com/hardware-support/arduino-simulink.html

  Use this legacy support only if one of the following is true:

  - You are using MATLAB R2013b or earlier (but not earlier than R2011a).

You are using 2014a, so its probably the reason analogRead isn't working. Get the more recent package and use this function instead:


Possible to use the hardware serial port for peripheral on ATmega32u4 when using USB for programming? I have a Arduino Pro Micro and use the USB port for programming. Is it possible to use the hardware serial port for connecting with a peripheral while I'm using the USB port (and hence the hardware serial port) for programming? Or must I disconnect the USB cable or otherwise reconfigure the hardware?

I have a Teensy 2.0 with a ATmega32u4 and I can use both, with the USB as Serial.* and the hardware UART as Serial1.*

For the Arduino Pro Micro it is the same.  See Arduino Pro Micro, get data out of Tx pin?

For Teensy, see https://www.pjrc.com/teensy/td_uart.html


NodeMCU Modbus interfacing with Pressure Multi-Switch I've been trying to interface between a NodeMCU and a Dotech DPX200 Pressure Multi-Switch over Modbus RS485 using a MAX485 Module for the past few weeks, going through nearly every Modbus post on this site  with no luck.
As my access to the multi-switch can be limited at times, I've also tried using several simulators like ModScan64, Simply Modbus Master/Slave, Modbus Poll etc. but could get none to work.

I'd like to know if the Modbus device's Slave ID has to be set on the device itself or the NodeMCU? Also to get the "Display of low pressure value" the address given in the manual is 40023. How would I write the NodeMCU code to read that value using either the ModbusRtu, ModbusMaster or any other appropriate library?

I've added the DPX200's Manual link with my NodeMCU script and wiring diagram, and would appreciate any help from you.

#include <ModbusMaster.h>
#define MAX485_TX_ENABLE  12

int myInts[6];
ModbusMaster node;

void preTransmission(){
  digitalWrite(MAX485_TX_ENABLE, 1);
}

void postTransmission(){
  digitalWrite(MAX485_TX_ENABLE, 0);
}

void setup(){
  Serial.begin(9600);
  Serial1.begin(9600, SERIAL_8N1);
  pinMode(MAX485_TX_ENABLE, OUTPUT);
  digitalWrite(MAX485_TX_ENABLE, 0);
}

void loop(){
  uint16_t k = 0,Status;
  node.begin(1, Serial1); //Slave ID = 1?
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
  Serial.println(i);
  Status = node.readHoldingRegisters(0x0023, 5); //Since address is 40023 to 40027
  if ( (Status == node.ku8MBSuccess) ){
     Serial.print("\nIDK: ");
     //Serial.println(node.getResponseBuffer(0));
     for (k = 0; k <= 5; k++ ){
        Status = node.readHoldingRegisters(k, 1);
        Serial.println(node.getResponseBuffer(0));
        delay(0);
     }
  }
}

Now you have node.begin(1, Serial1), but you can't use Serial1 for RS485 because Serial1 doesn't have RX pin

According to the picture you wired the adapter to RX/TX pin of Serial, but this pins are wired on board to USB for communication with the computer (upload and Serial Monitor). You can't use Serial for RS485 adapter while you are using it for debug prints.

You can use SoftwareSerial fo example on D1/D2 for RS485.

Or if you have an USB-to-TTL-Serial adapter then you can use Serial1 for debug prints and Serial for RS485


How to build a robot that can stop at a certain point using an altimeter I am thinking about creating a robot that climbs vertically and stops at a certain point. I thought about using an altimiter in order to measure the distance, however, I dont know how to create a code for it. Where would you start with it, can it be done with MATLAB?

Thanks for everything :)

have fun playing with the Arduino and some sensors! It is a great platform to learn. For your task, look into the Bosch sensor modules BME280 (pressure with temperature and humidity) or BMP280 (just pressure). You can expect maybe +-1 meter of accuracy. Or check the precision version BME388 that could give you +-50cm. Go to the adafruit shop and try a few of the breakout boards. They provide great library and documentation support.

In order to get absolute altitudes, you need to factor in ambient air pressure. A good source for that are METAR reports issued for aircraft. There are many online sources where you can get the so called altimeter setting for an airport close to you. Airplane altimeters actually just show the altitude above a standard pressure plane, so you need to compensate for whatever pressure the current weather gives you.

For higher precision, you pretty soon have to integrate barometric pressure, GPS altitude, and maybe other sensors, with some serious math. This is where MATLAB fits in.


Get JSON data from Arduino with AJAX I have an Arduino with Ethernet Shield. I'm trying to get data from Arduino, using AJAX call.
At the moment I have the following code on Arduino:

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

EthernetServer server(80);

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

  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  float temperatureIndoor;
  float temperatureOutdoor;
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: Arduino");
          client.println("Connnection: close");
          client.println();

          temperatureIndoor = 22.77;
          temperatureOutdoor = 15.55;
          client.print("{\"0\":{\"TemperaturaInterior\":\"");
          client.print(temperatureIndoor);
          client.print("\",\"TemperaturaExterior\":\"");
          client.print(temperatureOutdoor);

          client.print("\"}}");
          client.println();
          break;
        }

      }
    }
    delay(1);
    client.stop();
    Serial.println("client disconnected");
  }
}

I'm trying to get values with the following ajax call:

    $.ajax({
        url: 'http://192.168.1.177/',
        type: 'post',
            data: { tag: 'getData'},
            dataType: 'json',
                  async: false,
                  success: function (data) {

$('#TemperaturaInterior').val(data.TemperaturaInterior).show();
$('#TemperaturaExterior').val(data.TemperaturaExterior).show();

                            }
                        });

If I access directly from the browser to Arduino (192.168.1.177) I get the correct JSON reply from arduino:
{"0":{"TemperaturaInterior":"22.77","TemperaturaExterior":"15.55"}}

I'm not getting the values.
Any idea?
Thanks

NOTE:

This what I get when ask to arduino to give me the values:

This is more of a Stack Overflow question, but I'll help you a bit. The problem has nothing to do with your Arduino per-say. It has more to do with your PHP/Ajax.

Your code is suited for a completely local setup, but pulls from a remote site, which violates some security protocols build into your browser and jQuery. You need to change your code to this:

$.ajax({
    url: 'http://192.168.1.177/',
    type: 'post',
    data: { tag: 'getData'},
    dataType: 'jsonp',
    async: false,
    success: function (data) {
        $('#TemperaturaInterior').val(data.TemperaturaInterior).show();
        $('#TemperaturaExterior').val(data.TemperaturaExterior).show();
        }
    });
(may need slight modifications since you didn't include all PHP/html code)

For more information, see the jQuery documentation, particularly look at data types and what it says about cross-domain json vs jsonp.

Here is a relevant SO question.


What will happen if I give my Arduino Uno more or less than 5 volts? Will it still run on less than 5 volts? Will it break?

Will it break at < 5V? Not likely.

Check the datasheet for the IC's on the board and find the minimum power supply voltage the device works at.
At typical ATmega328 Safe Operating Area (under "Speed grades" in the datasheet) specifies approximately 4.1V for 16MHz.
If you require to use the USB interface, you'll have to check the datasheet for that chip too.

Will it run at < 5V? Maybe.

If the supply voltage gets below the minimum operational voltage, the controller may behave erratically. That means it can do anything (un)expected. This value is in the datasheet and probably somewhere around 2.7V.
If the Brown Out circuit is configured (in fuses), then the controller will switch itself off when supply voltage gets too low to prevent undefined situations. Once the supply voltage returns, it restarts.

Will it break at > 5V? Depends on where you apply it.

V(IN) should work fine for 7-20VDC as it is fed through an on board regulator. Notice though that the regulator has to dissipate the excess voltage and can get pretty hot when you draw a fair bit of current. The regulator will fail if the voltage goes over 20V or gets too hot too often;
+5V should work fine up to 5V, and I personally wouldn't worry if an external supply delivers up to 5.5V unloaded. Above that 5.5V you will probably release the magic blue smoke.


Serial Port configuration with asio C++ library I've made a small interface using the asio C++ library to open serial ports and do I/O from/to them.
It works with my Arduino Uno and other hardware as well (industrial weighing machines), but I only specify the port and baud rate.

The following code is run in the client application, which runs both on my Windows 10 Student Edition x86_64 machine, and on old 32 bit  Win XP machines that communicate with the weighing machines:

/*this is inside a constructor*/
/*iosvc gets passed by reference, port_ is a member variable of type asio::serial_port,
 npuerto is the name of the port (e.g. "COM3") */

port_(iosvc_, npuerto),

/*...*/

port_.set_option(asio::serial_port_base::baud_rate(baudios));

The Arduino is programmed to do a serial echo of whatever is sent to it, for testing purposes. This is the echo code:

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

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

It works fine with my Arduino until I unplug it and plug it back in. After replugging it all the values returned are garbage, specifically some sort of '?' character inside a black box, don't know the bit value though, but it's constant. The problem gets fixed when I open an arduino IDE Serial Port monitor.
If I close it, and once again use my own software to open up the serial port, all the values are fine.

From this I concluded that the Arduino IDE Serial Port monitor is doing something when it opens up the port that I'm not doing.

Any clues? Flow control? Handshake?
Thanks

Can you include all the other calls you make related to setting up the serial port along with asio::serial_port_base::baud_rate(baudios)? Ideally, split that out into a separate function (that takes parameters such as baud rate) that you know is the only thing doing this setup.

As I mentioned in the comment, getting back the right number of chararacters but incorrect characters looks as if the baud rate is correct but something else is wrong. The first thing that comes to mind is the bits/parity/stop bits settings. Typically you want to be using 8 bits, no parity, often referred to as "8N1".


Sim900 error on AT command AT+HTTPINIT I want to send data to my php server using sim900 module but I am unable to initialize http service on sim900.

code:

#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(8, 9);

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

  Serial.println("Con");
  delay(2000);
  Serial.println("Done!...");
  gprsSerial.flush();
  Serial.flush();

  // See if the SIM900 is ready
  gprsSerial.println("AT");
  delay(1000);
  toSerial();

  // SIM card inserted and unlocked?
  gprsSerial.println("AT+CPIN?");
  delay(1000);
  toSerial();

  // Is the SIM card registered?
  gprsSerial.println("AT+CREG?");
  delay(1000);
  toSerial();

  // Is GPRS attached?
  gprsSerial.println("AT+CGATT?");
  delay(1000);
  toSerial();

  // Check signal strength
  gprsSerial.println("AT+CSQ ");
  delay(1000);
  toSerial();

  // Set connection type to GPRS
  gprsSerial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(2000);
  toSerial();

  // Set the APN
  gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"web\"");
  delay(2000);
  toSerial();

  // Enable GPRS
  gprsSerial.println("AT+SAPBR=1,1");
  delay(10000);
  toSerial();

  // Check to see if connection is correct and get your IP address
  gprsSerial.println("AT+SAPBR=2,1");
  delay(2000);
  toSerial();

}

void loop()
{
   // initialize http service
   gprsSerial.println("AT+HTTPINIT");
   delay(2000);
   toSerial();

   // set http param value
   // ToDO : send dynamic value
   gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://www.fohoraayo.000webhostapp.com/?lat=1111&lon=1111\"");
   delay(4000);
   toSerial();

   // set http action type 0 = GET, 1 = POST, 2 = HEAD
   gprsSerial.println("AT+HTTPACTION=0");
   delay(6000);
   toSerial();

   // read server response
   gprsSerial.println("AT+HTTPREAD");
   delay(1000);
   toSerial();

   //gprsSerial.println("");
   gprsSerial.println("AT+HTTPTERM");
   toSerial();
   delay(300);

   gprsSerial.println("");
   delay(10000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}

output:

Config SIM900...
Done!...
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CREG?

+CREG: 0,1

OK
AT+CGATT?

+CGATT: 1

OK
AT+CSQ

+CSQ: 31,0

OK
AT+SAPBR=3,1,"Contype","GPRS"

OK
AT+SAPBR=3,1,"APN","web"

OK
AT+SAPBR=1,1

ERROR
AT+SAPBR=2,1

+SAPBR: 1,1,"xx.xxx.x.x"

OK
AT+HTTPINIT

ERROR
AT+HTTPPARA="URL","http://www.fohoraayo.000webhostapp.com/?lat=AT+HTTPACTION=0

ERROR
AT+HTTPREAD

ERROR
AT+HTTPTERM

ERROR

For me, your code is working like charm. but change the

gprsSerial.begin(9600)

to

gprsSerial.begin(4800)


ESP8266 wakeup from deep sleep: Both by timer and button? In a project powered by batteries, the ESP8266 should go to deep sleep for long time, having RF disabled. After some number of sleep cycles, it shall restart with RF enabled, synchronize time via NTP, and again go to sleep. Think this could work with a counter saved in RTC Memory or SPIFFS.
Additionally, s.o. should be able to wake up via push button (at any time), which should result in different behaviour (running as WiFi AP, allowing for configuration of new WiFi credentials).
The question is: Is it possible to find out what did wake the ESP (timer or pushbutton)?
Edit: Using external circuitry this might be possible. To avoid this, we switch to ESP32, which is an overkill for the project, but easy to find out the source of the wakeup (and with the possibility to use touch sensors). Additionally, ESP32 allows for easy use of "Preferences" in NVR and variables in RTC memory (when using the Arduino IDE), which will survive deep sleep (RTC) and even reset/power loss (NVR).

Place a capacitor on the ESP side of the button to one power rail or the other (my preference is to ground, but either should work), and have the setup() routine reads the state of the pushbutton switch as it's first instruction.  You probably don't even need the capacitor, but if you don't have it, you'll have to read the switch state multiple times to account for possible contact bounce.
If the ESP wakes up due to a timer, there will be no activity on the PB line; if it wakes up due to the PB being pressed, there will be activity on the PB line for several 10's of millisec no matter how quickly it is pressed and released.


Why I'm getting this error: invalid conversion from 'const char*' to 'char' [-fpermissive]? Why I'm getting this error?

invalid conversion from 'const char*' to 'char' [-fpermissive]

Here is my simple sketch:

const char data = "should";

//I have also tried:
//const char* data = "should";

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

void loop() {
  Serial.print("this " + data + " work");
}

const char data = "should";

In this case data is a single character, not a string. So it can store 's' but not "should".

Serial.print("this " + data + " work");

No, that will never work, even if you get your data types correct.  You do not concatenate strings like that. All you are doing is attempting to add the addresses of two string literals to the address of a string constant. If that were possible (the  compiler doesn't let  you) you'll get gibberish (or a crash) as it tries to print out whatever is at that address.

Instead break it down:

Serial.print("this ");
Serial.print(should);
Serial.print(" work");


Will I destroy my Arduino Uno if I connect a 600-mA DC motor to the +5V pin? I know that if I connect an electronic component that consumes more than 20 mA, my Arduino Uno will be destroyed. I don't know if that refers only to digital pins or refers to +5V pins too.

If you connect a motor to the +5V pin, it will always be on. Is that what you want?

The +5V pin on the Arduino Uno gets power from the on-board 5V linear voltage regulator OR from the USB jack, and thus the host computer. This allows the board to have a fixed 5V source even when applying 9 or 12 V to the barrel jack or the RAW pin, and to be powered by a USB host.

When you draw 600mA for your motor (ignoring what the other devices on the Arduino draw), you are drawing 600mA from the regulator's output. You are also drawing 600mA from the regulator's input, which supplies a higher voltage. Excess power is dissipated as heat. 5V * 600mA is 3W. If you power the board from 9V, you are discarding [(9V-5V)=4V] * 600mA = 2.4W of power. 2.4 Watts is probably too much for the little regulator to handle. It will get too hot and burn up.

If you do this, you will probably be able to still operate it powered by the USB port, as only the 5V regulator is damaged.

However, if you try to draw 600mA and power the board from a USB device like a computer, you may burn up the computer's USB chip and make it useless forever.

For high-power devices like motors, always power them from a sufficient external supply of the appropriate voltage. Be sure to connect the ground of the external power supply to the GND pin of the Arduino. Don't send high current through the Arduino board. The Arduino should handle signals, not power.

Use the signals to activate switching devices like MOSFETs, which are designed to control higher currents by low-power signals.


Flash Arduino Micro code on Atmega32U micro controller First of all, I am not an expert on electronics, so forgive me for asking something which is trivial for probably the most of you.

I am trying to get my Arduino (Micro) code running on a custom PCB with the Atmega32U chip on it. The person who made the PCB copied parts of the schematics of the Arduino Micro onto a custom PCB. What he did, is place the Atmega chip on it, and also copied the wiring for the micro USB connector.

That way, I can hook up the PCB to my USB port but now Windows does not recognize the chip as a "Arduino hosted via a COM port", but just as a atmega chip.

I learned that installing Atmel Studio 7 will also provide the correct drivers so that Windows recognizes the chip correctly via USB:

The next step for me was to get my code running on the atmega chip. So with some help from the internet I came to the following steps:

open my sketch in Arduino IDE
compile with verbose output
find the location where the ".HEX" file is stored

But how can I flash this .HEX to the Atmega chip?

To get your chip to respond to the Arduino environment over USB you need a booloader (some extra code) to be running on the Atmega32.

To install the bootloader you can use another Arduino as a programmer to the ICSP pins (or any other AVR ICSP programmer).
This procedure and description from Sparkfun for the Arduino Pro will help you.

This may help you understand the ICSP aspect, again from Sparkfun.


Voltage meter ADC + serial: Bytes lost during communication I want to make a simple digital voltage monitor. So I have a sketch:

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

void loop() {
  int val = analogRead(A4);     // read the input pin
  val = 1;
  byte buf[4];
  buf[0] = 0;
  buf[1] = 0;
  buf[2] = val & 255;
  buf[3] = (val >> 8) & 255;
  Serial.write(buf, 4);             // report voltage value
}

When I tried to read serial buffer on PC host, I noticed that sometimes 1 byte can be lost, which lead to shifts and headache. How should the streaming be done?

PS.

host os: win7 x64;
language: c/c++
com port library: CSerial

Loop is as follows:

typedef int32_t sample_t;
while (true) {
    int nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(sample_t));
    size_t numRead = nBytesRead / sizeof(sample_t);
    if (numRead > 0)
        std::cout << "read: " << numRead << " samples\n"; // Calculate average here!
}

With help in a comments I've managed to deal with the task myself.

First of all, as @Majenko pointed out, I was dealing with some multi-byte data. So I need some control character, that separates packets. I choose hex output with '\n' delimeter as control character - that served good. I was able to read 3.5 to 5k packets per second (with voltage reading) from serial on the host.

Second improvement, credited to @Jot, is to stack some sequential values right in arduino, before sending.

Alongside with increasing sampler frequency that could be very good.

#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

void setup() {
  sbi(ADCSRA, ADPS2);
  cbi(ADCSRA, ADPS1);
  cbi(ADCSRA, ADPS0);
  Serial.begin(115200);
}

void loop() {
  int val = 0;
  for( int i = 0; i < 32; ++i )
    val += analogRead(A0);
  Serial.print(val, HEX);
  Serial.print("\n");
}

at the host recieve side, some simple conversion could be done:

#include "Serial.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

// sample to voltage
double s2v(int sample) {
    return 5.0 * (static_cast<double>(sample) / 1024);
}

int main() {
    std::ofstream ofs("test.csv", std::ios::out | std::ios::ate);

    size_t comPort = 3;
    size_t baudRate = 115200; // 57600;

    CSerial serial;
    if (serial.Open(comPort, baudRate))
    {
        std::cout << "COM" << comPort << " opened @" << baudRate << "bit/s\n";

        // serial recv buffer
        size_t bufSize = 1048576;
        auto lpBuffer = new char[bufSize];

        // accumulator
        size_t nVals = 0;
        int nAcc = 0;

        // timer
        __time64_t destTime;
        __time64_t destTime2;
        _time64(&destTime);

        while (true) {
            SleepEx(10, false); // care of 100% cpu core usage, poll serial port lazily
            size_t nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(lpBuffer[0]));

            //parse buffer:
            size_t cvtPtr = 0;
            for (size_t i = 0; i < nBytesRead; ++i) {
                if (lpBuffer[i] == '\n') {
                    try {
                        lpBuffer[i] = '\0';
                        auto val = std::stoi(lpBuffer + cvtPtr, nullptr, 16);
                        nAcc += val;
                        nVals++;
                    }
                    catch (...) {
                        // ignore, or warn that serial recieved junk/empty packet
                    }
                    cvtPtr = i + 1;
                }
            }

            //check if doom had come!
            _time64(&destTime2);
            if ((destTime2 - destTime) > 0) {
                auto fVoltage = ( s2v(nAcc) / 32 ) / nVals;
                std::cout << fVoltage << "\t(" << nVals << " ksps)\n";
                ofs << destTime << "," << fVoltage << "," << nVals << "\n";
                if((destTime % 30 ) == 0) // care of disk, write only once in 30 seconds
                    ofs.flush();
                destTime = destTime2;
                nVals = 0;
                nAcc = 0;
            }
        } // while
    } // if opened
    return 0;
}

That gives voltmeter with high precision, about ±0.5mV, that is updated every second.

Also! It was stated about 10bit adc, 5.0V/1024 = 4.88mV, but i got some subthreshold oscillations in vivo, adding samples up. So you are wrong, noise can be attenuated and resolution can be artificially pumbed up, in a trade for increased sampling time. Here is 14bit ADC built on top of 10bit ADC: . Its photovoltaic cell in a dark street, oscillations are caused by cars' front lights. Timescale is 1000 seconds per grid div


How to add a yield before else if? So I am running my project on a NodeMCU, but I don't know how to let it add a yield in front of an else if. It will give me an error like this:

  Arduino:1.8.12 (Windows 10), 開發板:"NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Sketch + WiFi Settings, 115200"

  G:\資優班\科展\程式碼\Front_End\Main_Code_V5\Main_Server\Main_Server.ino: In function 'void loop()':

  Main_Server:84:5: error: 'else' without a previous 'if'

  exit status 1
  'else' without a previous 'if'

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

Here's the code:

#include <SPI.h>
#include <ESP8266WiFi.h>

#define MAX_SRV_CLIENTS 2
#define led LED_BUILTIN

WiFiServer server(80);
WiFiClient serverClients[MAX_SRV_CLIENTS];
IPAddress ip(10, 241, 241, 27);
IPAddress mask(255, 255, 255, 0);
IPAddress gateway(10, 241, 241, 254);
char ssid[] = "AP";
char pass[] = "Science_Fair";

void setup() {
  Serial.begin(9600);
  WiFi.config(ip, gateway, mask);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    yield();
  }
  server.begin();
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
}

void loop() {
  uint8_t i;
  Serial.setTimeout(10);
  for (i = 0; i < MAX_SRV_CLIENTS; i++) {
    Serial.println("Pre 1");
    if (server.hasClient()) {
      Serial.println("Pre 2");
      if (!serverClients[i] || !serverClients[i].connected()) {
        Serial.println("Pre 3");
        if (serverClients[i]) {
          Serial.println("Pre 4");
          serverClients[i].stop();
          Serial.println("Pre 5");
        }
        Serial.println("Pre 6");
        serverClients[i] = server.available();
        Serial.println("Pre 7");
        serverClients[i].setTimeout(10);
        Serial.println("Pre 8");
        Serial.print("New client: ");
        Serial.println("Pre 9");
        Serial.println(i);
        Serial.println("Pre 10");
        break;
      }
    }
    yield();
  }
  for (i = 0; i < MAX_SRV_CLIENTS; i++) {
    String fromClient = serverClients[i].readStringUntil('e');
    Serial.println("P1");
    yield();
    if (fromClient == "LR") {
      Serial.println("LR");
      String reply = Serial.readStringUntil('e');
      Serial.println("P2");
      yield();
      if (reply == "Warn_B") {
        yield();
        Serial.println("Confirm");
        Serial.println("P3");
        for (i = 0; i < MAX_SRV_CLIENTS; i++) {
          serverClients[i].print("Warn_B");
          Serial.println("P4");
          yield();
        }
      }
    }
    yield(); // this is the yield I need to add
    else if (fromClient == "RR") {
      Serial.println("RR");
      Serial.println("P5");
      String reply = Serial.readStringUntil('e');
      Serial.println("P6");
      yield();
      if (reply == "Warn_A") {
        Serial.println("P7");
        Serial.println("Confirm");
      }
      for (i = 0; i < MAX_SRV_CLIENTS; i++) {
        serverClients[i].print("Warn_A");
        Serial.println("P8");
        yield();
      }
    }
    yield();
  }
}

I need the yield() there but I don't know how to let it still do the else if. Please help me guys, thanks!

First of all do yourself a favour and listen to your IDE

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

and in an if else there is no in between so either let it run as a state machine especially inyour case A != B != C != other:

void subfunction(){
  if(A){
  // code to run
  return;
  }
 yield();
 if(B){
  // code to run
  return;
  }
 yield();
 if(C){
  // code to run
  return;
  }
 else{}  // to catch if not A or B or C
 yield();
}

or implement switch case (Pseudo code)

 switch(fromClient){
    case "LR":
      //code to run
      yield();
      break;
    case "RR":
      //code to run
      yield();
      break;
    default:
      //code to run
      yield();
      break;
  }

Id else chains are prone to errors as in your case its A != B != C != other


calling a random function number I have a recurring problem that when I'm controlling leds, I make several different functions for different fx and just want to trigger them randomly but having a hard time to formulate it in an intelligent way and end up hardcoding every function call.

ex: I have let's say 10 functions called anim1();, anim2();, anim3(); etc
and would like to called them randomly in that fashion :

randNumber = random(1,11);
anim[randNumber]();

I know that it's not that type of brackets I need to use but I can't find the proper syntax and I'm wondering if it's possible to do that..
I'm sure there must be a way ;)

thanks for your help

What you want is an array of function pointers.

void anim1() {
    // blah blah
}

void anim2() {
    // blah blah
}
// ... etc ...

typedef void (*animptr)();

animptr anims[10] = {
    anim1,
    anim2,
    anim3,
    // ... etc ...
    anim10
};

Then you can use:

anims[animNumber]();


Teensy MIDI Show Control I'd like to use my Teensy 3.1 to send MIDI Show Control messages using USB MIDI in order to control an ETC Nomad system. These are different from standard NoteOn, NoteOff, ProgramChange, etc. commands, but as far as I can tell they are not supported by the standard library.

Is there any way I can send these messages directly (using lower level commands), as seen here, or does anyone know of a library that supports this? Google has, unusually, not been much help.

According to the documentation, SysEx messages are sent like any other messages:

array[0] = 0xf0;
array[1] = 0x7f;
array[2] = 0x7f;
array[3] = 0x02;
array[4] = 0x7f;
array[5] = 0x01;
array[6] = 0xf7;
usbMIDI.sendSysEx(7, array);


Is it possible to combine a HC-05 Bluetooth module and a shrinked arduino ATtiny45/85 to control a motor, LEDs, or other components? I'm thinking of making a tiny RC toy project that is controlled through Bluetooth with most components at its tiniest size. I'm a complete beginner in this area so i'm not completely familiar with lots of components so please don't mind me if i sound dumb and uneducated. Anyway...

If it's possible: how many components can i use with the ATtiny45/85? or should i go with the atmega8.

I have a m20 mini motor, a micro servo and a few leds. This doesn't include other components that i havent purchase such as dc driver module and HC-05 Bluetooth module.

If not possible: what other options I can do to create my project.

The ATTiny has 5 usable pins (6 if you decide to reuse the Reset pin). Since it doesn't have UART hardware, you need to use a SoftwareSerial library to communicate with the HC-05. This takes 2 pins. To drive a motor, you need at least 1 pin. If you need to control it's speed (instead of just on and off), you would need to generate a PWM signal. Either through hardware timer or by code. (The ATTiny has 2 timers. When you want to use PWM with hardware timer, you need to make sure, that the SoftwareSerial library doesn't want to use the same timer). For the servo it's similar. The servos position is encoded by pulse lengths. (Make sure, that the used library doesn't want to use an already used timer)

Unless you use techniques as multiplexing or matrixes (which are not that useful for a small number of LEDs), you need 1 pin per LED.

Depending on what exactly you want to achieve, you will pretty fast run out of pins. Since you are a beginner you should start with a chip with more pins. If you don't know, how exactly your project will be in the end, better by a chip with maybe double the pins, that you think you need. Develop, until you really know, what functionality your project should have, what not and what you need to achieve that. Based on this you can choose the correct chip, that is as small as possible. Also consider using SMD parts in the finished version. There are mostly much smaller, but also more difficult to solder.


How do I use a 3 legged phototransistor? I have searched the Internet and found the following circuit to use with my phototransistor but it is not working, I can say so because all analog input i get is 1023 even if i have covered it totally, I have include the phototransistor and the diagram can anyone tell why is it not working!
I used this webpage to check my sensor and it works-I used this page

I have used 10kohm resistor.

This is my phototransistor

A reasonably generic data sheet is HERE
That is for an AT156 but yours may be an AT138/HT138 based on an ad some years ago from the same seller when they said they had 10,000 for sale.

Basic information here and more in the data sheet.