Convert from 3 V to 5 V I'm new to Arduino, electronics, and this forum.

I have made up a little project that connects an HC-SR04 ultrasonic range detector, and displays the distance on a 4 digit, 7 segment LED display.

When I have it plugged into my laptop for power, it runs beautifully on an Uno board.

But I want to mount all this in a Nerf gun (Nerf N-Strike Elite Firestrike) using a Nano board.

The Nerf gun has a built in "laser" (red light) that is powered by 2 x AAA batteries, which makes 3 V, I think. I want to rig this up so that pulling the laser/light trigger also triggers the range detector and display.

I want to run the range sensor and the display off the Nerf guns batteries, but they both use 5 V. Is there a way to do this? Or do I need a separate 5 V power supply?

You may want to use a boost converter which is a device that can step up voltage.

You can get them from eBay for around $US 2.

As Chris Stratton pointed out in a comment, the boost converter may run your batteries down quite quickly. Let's say you need 200 mA for your Uno, sensor and LEDs. At 5V power that is 1W of power (0.200 * 5).

However to get 1W from 3V you would consume 333 mA (0.333 * 3). Then take into account that the converters are not completely efficient. Let's say the converter has 90% efficiency. Then you need to multiply the current by the inverse of the efficiency, that is: 0.333 mA / 0.9 = 0.37 mA.

Another factor is the battery type. If you use NiCad batteries their nominal voltage is closer to 1.2V than 1.5V, especially after you have been using them for a bit. Ditto for NiMh batteries.

Reworking the above for 2 * 1.2V (2.4V) we see that the current will be:

1W / 2.4V = 0.4167A
0.4167A / 0.9 = 0.463A (allowing for 90% efficiency)

Now it potentially draws close to half an amp when active. Your batteries might not be able to handle that for long.


What is the capability of AVRISP and USBASP on ATMega48, 328, 2560? For use with ATMega 48 (old Arduino?), 328 (UNO, Pro Mini) and 2560 (Mega2560) chips, what is the capability for the AVRISP and USBASP programmers on:

Can it read, write fuse?
Can it read, write Program Flash?
Can it work 3.3 and 5 volts?
What workable clock frequency range on the MCU?
Can it be used under Arduino ISP to write to board so as to erase the bootloader and use the FULL flash space for big user program (eliminate boot loader saves 0.5 to 8KB space on above Arduino boards)?
Can it be used with ATMel factory software development tools (Atmel studio and associated tools) to use MCU on chip hardware based breakpoint (Debug wire, JTag, or other names, as on different MCU)?

Many thanks in advance

Yes.
Yes.
Depends on the specific hardware. See the documentation for the exact variant you have.
See 3.
No. They have their own protocol that you must use instead. They are selectable from the Programmer menu in the IDE though. However, you must unprogram the fuse bits outside of the IDE.
No. They are low-cost tools meant to be used for programming only. You will need an Atmel-supplied debugger in order to use Atmel Studio's debugging features.


Fastest wireless communication Hy guys,

I am currently working on a quadcopter stabilization algorithm for an indoor quadcopter. I now need to setup a wireless communication between my onboard Arduino and my controlling Arduino (and/or RasperryPi (not shure yet)).

My question is: What would be the fastest wireless communication possibility?

I am not worrying about distance; they won't get far apart from eachother. I want to keep a lot of resources on the stabilization algorithm and to keep down resources used for the communication and thus get the fastest communication on very few resources.

What are your opinions and experiences, what is going to be fastest?

There is a difference between Wifi and Wireless. Wifi requires an already established network and uses the standard internet protocols. If this is what you mean, then the communication speed would only be influenced by the bandwidth of your network and the speed of the arduinos. I have not been able to find what the speeds of the modules are, but if they are 150 mB/s and your network is only 100, then you'll only get a speed of 100mB/s (which is a pretty decent speed).

If you want wireless (they create their own network using the unlicensed 2.4ghz spectrum, then buy these: nRF24L01+ 2.4GHz. They seem pretty reliable at short distances, and have a low power and high power variant. These have a speed of (at tops) 2 mB/s, but you won't have to worry about having a Wifi connection.

I personally do not know much about Bluetooth modules, so I cannot comment there.

Hope this helped.


8266 analogRead(A0) always 1024 dear member.
I have 4 ESP-12 averything OK but one chip behave weird.
always return 1024 on analogRead(A0);
once use ADC_MODE(ADC_VCC) and reflash using ADC_MODE(ADC_TOUT); and never back to normal, is my Chip Error..?
FM 4MB
ArduinoIDE 1.8.13
BR 115200
PS 80MHz
int iVal = 0;
void setup() {
  Serial.begin(115200);
  delay(999);
  pinMode(A0,INPUT) ;
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  iVal=analogRead(A0);
  Serial.println(iVal);

  if (iVal > 900) digitalWrite(LED_BUILTIN,HIGH);
  else   digitalWrite(LED_BUILTIN,LOW);
  delay(720);
}

First be sure your voltage on the analog input is less then 1V and greater then zero, that is the range for the input. If nothing connected no guarantee what you will get. Just guessing, no circuit or definition.


Wifi with ESP8266 and Arduino sketches I have a NodeMcu Lua ESP8266 ESP-12E which i want to use to control to a relais via Wifi network.

The first step was to write an Arduino Sketch which scans networks and connects to the network. However, even the standard example from the examples menu didn't work (c.f.,https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino) .

To rule out hardware problems I tried the LUA version from the list API doc (see below), which worked.

 -- print ap list
function listap(t)
      for k,v in pairs(t) do
        print(k.." : "..v)
      end
end

wifi.sta.getap(listap)

Using a firmware build from http://nodemcu.com/index_en.html

I gave the INO version another try and it seemed to work as well. However, it turned out it only works if the previous firmware has been the firmware from http://nodemcu.com/index_en.html

To I need to include a library or something ?

Thanks in advance,
Cafebabe

(By googling) I figured out the problem and a work-around. But not an executable solution. The problem seems to be that the RF module is not properly initialised when the device is powered on or awakes from reset.

Sadly there seems to be no manual mode to switch on the RF module.

However, I found a workaround. First I made the connection to enable deep sleep, for that, we need to tie the RST pin to D0/GPIO 16 on the ESP8266.

Then I added the following code to setup

extern "C" {
  #include "user_interface.h"
}

void setup(){
  if (resetInfo->reason != REASON_DEEP_SLEEP_AWAKE) {

      ESP.deepSleep(10, WAKE_RF_DEFAULT)
  }

Basically whenever the system comes into setup from something else than deep sleep, the system goes to deep sleep and when powering back on the RF module is enabled.


D1 Mini latch button using rst pin I'm trying to use a Wemos D1 mini as a smart button that will boot up, perform a task, and then shut back down. I'd like to do this as a true power off as opposed to any sort of sleep mode.

I'm hoping I can do something similar to this post https://www.esp8266.com/viewtopic.php?f=11&t=4458

Tie RST pin to a Low GPIO pin so that it doesn't boot
Push a button that will run 3.3v to RST pin to make it go high and cause a boot up
Flip the GPIO pin that is tied to RST to high so that it stays running when button is no longer pressed
Run some code and flip GPIO back to LOW shutting down

Things I've tried:

Tie to GPIO15 (D8) - This stops the boot and starts booting when button is pressed but never finishes booting up. I'm assuming I am causing D8 to go high by pressing my button and interfering with the boot, but honestly not sure
Tie to GPIO4 or 5 (D2, D1). This doesn't prevent boot.
I've also tried #2 with a pull down resistor on the GPIO pin, but that doesn't seem to work either

Any help would be much appreciated.

To do this you would usually use MOSFETs to control the power.

Take the following circuit, for example:

simulate this circuit – Schematic created using CircuitLab

M1 is normally off, having its gate pulled up by R1.

Pressing SW1 pulls the gate of M1 low, allowing current to flow through it to power the D1.

The D1 boots up, and immediately drives the GPIO high.

This then turns on M2 (which is normally off, having the gate pulled down by R2), which in turn pulls the gate of M1 low.

SW1 can now be released since M2 is doing the same job.

To turn off, simply drive the GPIO low, or allow it to float as an input, in which case R2 will turn off M2, which then turns off M1, which stops the current flowing.


9V Vin powered Mega - 3V instead of 5V I'm experiencing an issue with an Arduino Mega 2560 :
I powered the board through the Vin using a +24 --> 9V voltage regulator. When I power the board and measure the 5V output from the board, the voltage quickly drops from 5 to ~3V within seconds.

However, while powering with USB, the 5V output from the board gives us a clear 4.8V.

I have checked the 9V Voltage regulator (connected to the Vin), and it has a +24V input which remains stable (as should the 9V).

Any thoughts ?

So, according to the comments the main problem should be a thermal protection in LM7809C regulator.

The voltage drop between regulator's input and output is about 15 Volts and even with current consumption about 150mA it means 2.25W of power dissipation on it.

For such a big difference between input and output voltage switching regulator is recommended. (Or 9V power supply instead of 24V)

And it is not possible to have 2mA current consumption. I've just measured power consumption of bare Arduino Mega 2560 and it is 81mA through barrel jack input (9V) without anything on it. Not even blinking Led. So if you've measured for example 0.2A it's not 2mA but 200mA


Arduino randomly does incorrect addition I've been trying to make an accelerometer calibration tool for my Arduino Nano and MPU6050, but the arduino seems to randomly do incorrect addition. If you look at the output of the console, it works fine for the first 4 iterations, then on the fifth, decides that -31904+-7964 is equal to 25668. It is supposed to be -39868. It does this every time I run it, usually between the 3rd to 6th iteration, but with different numbers.

bool calix = true; //X calibrated or not
      while(calix)
      {
        accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
        Serial.print("PrevAvgX: "); Serial.println(axo/i);
        Serial.print("Axo: "); Serial.println(axo);
        Serial.print("RawX: "); Serial.println(ax);
        axo = (float)ax + (float)axo;
        i += 1;
        Serial.print("Axo2: "); Serial.println(axo);
        Serial.print("RawX: "); Serial.println(ax);
        float cax = axo/i; //Current Average (x)
        Serial.print("AverageX: "); Serial.println(cax);
        delay(100);
        accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
        Serial.print("NewX: "); Serial.println(ax);
        float offsettocurrent = ax-(axo/i);
        Serial.print("AverageX-RawX: "); Serial.println(offsettocurrent);
        if(offsettocurrent>5 or offsettocurrent<-5)
        {
          Serial.println("Offset not accurate enough. Continuing.");
        }
        else
        {
          Serial.println("Offset accurate enough. Finishing calibration");
          break;
        }
        delay(100);
      }

Serial console output:

Initializing I2C devices...
Testing device connections...
Connected to MPU6050
Attempting full calibration
PrevAvgX: -1
Axo: 0
RawX: -8048
Axo2: -8048
RawX: -8048
AverageX: -8048.00
NewX: -8028
AverageX-RawX: 20.00
Offset not accurate enough. Continuing.
PrevAvgX: -8048
Axo: -8048
RawX: -7940
Axo2: -15988
RawX: -7940
AverageX: -7994.00
NewX: -7964
AverageX-RawX: 30.00
Offset not accurate enough. Continuing.
PrevAvgX: -7994
Axo: -15988
RawX: -7972
Axo2: -23960
RawX: -7972
AverageX: -7986.00
NewX: -8016
AverageX-RawX: -30.00
Offset not accurate enough. Continuing.
PrevAvgX: -7986
Axo: -23960
RawX: -7944
Axo2: -31904
RawX: -7944
AverageX: -7976.00
NewX: -8016
AverageX-RawX: -40.00
Offset not accurate enough. Continuing.
PrevAvgX: -7976
Axo: -31904
RawX: -7964
Axo2: 25668
RawX: -7964
AverageX: 5133.00
NewX: -7944
AverageX-RawX: -13077.00
Offset not accurate enough. Continuing.

int only goes from -32768 to 32768, and rolls-over, as you've seen.
Use a long data type instead and you can go MUCH further from zero. Use double instead of float likewise, when you need more room. Be aware however that larger types use more RAM, and in the case of double, execute a bit slower as well.


What's the difference between different Ethernet Shields? I am working on a project with Arduino and I need an Ethernet shield. but after searching in some electronics shops I found there isn't only one but a lot. I don't know which one is better and what are the differences.

Arduino Ethernet with PoE module

Ethernet Pro

Ethernet Shield for Arduino - W5200

Arduino Ethernet Rev3 Without PoE Module

Ethernet Shield W5100 For Arduino

in DFRobot Online Shop.

Clearly the 'best' one is the one that meets your requirements (or is the most expensive - that's always the best, right?).

You say you need an ethernet shield - can you explain why? Without that information, it's almost impossible to tell you which is the most suitable.

If you are looking at IoT applications, it may be that an Ethernet shield isn't the 'best' thing for you. If you just want access to the local IP network, you could use any of those. If you want the 'best' library of functions to support your application, that may affect which module you use.

For me, I think the best module is the cheapest one that gives me connectivity: http://www.aliexpress.com/item/Hot-Sale-ENC28J60-Ethernet-LAN-Network-Module-For-Arduino-51-AVR-STM32-LPC/32254842414.html

The W5100 is also a good choice, but only if it is under $7


HC-05 and p-channel mosfet I'm trying to use a MOSFET (BS250P datasheet) to switch a circuit on and off while the MCU is asleep. It's a P-channel MOSFET that closes the circuit when the gate is pulled low. The most power hungry module in my circuit is a HC-05 bluetooth module. The specs on the website I bought it at rates it at 3.3V - 6V and a max current draw of 50mA when pairing and around 9mA when connected. Hooking it up to an Arduino 3.3V source confirms that it works at that voltage and pairs it up with another identical module just fine.

Now when I put that same 3.3V source through the MOSFET with a 10k pull up resistor and connects the HC-05 to the drain, the module does not power up. I measured the voltage on the drain and when nothing is connected it's the same as the source. After connecting the HC-05 it's about 2.4V (maybe this is a clue). Even if I run the power through a step up converter to 4.10V it does not power up through the MOSFET. If I increase the voltage to 5V it all works fine. I would ideally run the circuit at 3.6V in order to preserve current for the rest of the modules, and not having to use a voltage regulator for the RX of the HC-05.

I assume the issue is with the MOSFET properties, but as far as I can read from the datasheet it can sustain 230mA current. It has a VGS(th) of 3.6V, but since I'm always pulling the MOSFET low in this scenario that shouldn't be an issue? Measuring the resistance when the gate is pulled low indeed gives just a few ohms as the datasheet suggests.

So basically, what am I missing here? :-) Thank you for any help with this!

That's not a good choice of MOSFET I'm afraid.

The on resistance is quoted as 14Ω when the gate is at -10V - however, you are only able to get -5V, so it will be considerably worse.

That massive on resistance will be causing a massive voltage drop, which is what you are experiencing.

You should find a MOSFET with an on resistance that is in the milli-ohm range when the gate is between 0V and -5V.


Interfacing Arduino through USB or I2C? I am planning to connect multiple Arduinos to my Raspberry Pi. There are basically two ways I can achieve that:

Use an USB hub. Each Arduino will then be available through ordinary serial commands both for reading and writing. The USB hub I have is powered and can handle both communications and powering the Arduinos.
Use I2C, so that the Arduinos are I2C slaves of the Raspberry Pi.

Since USB is used for updating the Arduino, I don't have the best feeling about using this same connection for "management" tasks.

Are there any known disadvantages to using the pre built USB socket on
the Arduino in "production", any best practises or similar saying that I should not do
this? Is this USB socket meant to be used for debugging and code deployment only?

The plan is to let the computer send commands to the Arduinos using a serial protocol. The computer will automatically detect whenever an Arduino is connected and immediately send a "hello" command over serial. The Arduino is then supposed to send back its "name" and a list of capability keywords. A capability may be "motion-sensor". The computer will then know that it can ask the Arduino if it has detected motion. Other capabilities may be "temperature-sensor", "barometric-sensor", "lights".

It's for a generic open source home automation system/robotics system I am working on creating a framework for.

One complication you should be aware of is that in its default configuration, an Arduino Uno (and I assume that is what you’re talking about) will automatically reset whenever a serial connection is opened to it. This is easily bypassed with a capacitor between RESET and GND, but not taking it into account might make for hours of debugging fun.

The other complication is that just after a power up or RESET, an Arduino will delay for a second or two to listen for a programmer connection on the serial port, but that’s something you’ll have to take into account anyway.


Xbee not activate on arduino micro I have 2 nodes: one is a PC+arduino mega+xbee the other one is arduino micro+xbee.
The 2 xbees are communicating fine, I have tested this with 2 separate arduinos.
My problem is that when the second xbee hooked up to the micro it seems it does not try to send or receive data from the serial lines.
It is connected to the first RX/TX pins in proper order (RX->Tx, Tx->Rx) on the micro.

This is obvious for me because if I start my program's setup section on the ardu with:

void setup()

{
  Serial.begin(9600);
  while (!Serial);

The whole main program won't be running because the serial just never gets ready only if I plug my PC in.

When I try to send data from the PC->micro through xbee I see the Xbee receives it (led goes on the board) but nothing happens on the micro.

The micro right now is set to periodically send some debug data through the serial, I don't get that back either otherwise I would see the serial TX led on the micro blinking that it is sending the data. It only works when the PC is connected through USB.

Do I need some additional code for the xbee or is it require a hardware modification? I use a 5V-3V ttl converter as an extra hardware.

It is probably because you are using the only Serial to communicate to both the devices - your PC and XBee. At any instant, you can communicate to only one device. So you might need an extra serial to get you go.

And, may be due to this conflict you can see TX led blinking. May be it's communicating with anyone of them, and the other one is receiving garbage.


How do i send ads1115 data over spi to master arduino I am trying to send ADS 1115 data which is connected with Arduino mega_1 over I2C and arduino Mega_1 is connected with arduino Mega_0 over SPI.
Arduino Mega_1 is act as a slave and send ADS 1115 data to master device..
I think my whole setup is working but i want to received actual data of ADS 1115 on master Arduino
Here is screenshots of results of my code

master

#include <SPI.h>

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

  digitalWrite(SS, 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.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait

void loop (void)
{
byte a;

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('a');  // add command
a=transferAndWait (0);

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

  Serial.println ("results:");
  Serial.println (a);

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

slave

#include <Wire.h>
#include <Adafruit_ADS1015.h>
int out_buf;
int adc0;

// Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */
Adafruit_ADS1015 ads;
// what to do with incoming data
volatile byte command = 0;
void ss_falling ()
{
  command = 0;
}
void setup (void)
{
 ads.begin();
 Serial.begin(9600);
 //ads.startComparator_SingleEnded(0, 1000);
// have to send on master in, *slave out*
 pinMode(MISO, OUTPUT);

// turn on SPI in slave mode
 SPCR |= _BV(SPE);

 // turn on interrupts
 SPCR |= _BV(SPIE);
 attachInterrupt (0, ss_falling, FALLING);

}

// SPI interrupt routine
ISR (SPI_STC_vect)
{
 byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = out_buf; // add 15
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
adc0 = ads.readADC_SingleEnded(0);
Serial.print("AIN0: "); Serial.println(adc0);

out_buf=adc0;
//int buff = atoi(out_buf);
Serial.print("AIN1: "); Serial.println(out_buf);
delay(1000);
 }

i am sending 1570 but on Master side i received 35 i think ADS data is of 16 bits i.e 2 bytes and SPI received only 1 byte at a time i am stuck here please help me.
Thank you in Advance

example

Implementing SPI slave mode is a little more tricky than you may think.  The most important thing to remember is that it's not a "Give me X" -> "Ok, here is X" kind of protocol.  It's actually a "Here's X" <=> "Here's Y" protocol.

That is, at the same time that the master sends X to the slave, the slave sends "Y" to the master.

The way you have it is that the master sends "a" as a command and discards what it receives.  The slave remembers that "a" as the "command". Then the master sends 0, and remembers what it receives. The slave receives that 0 and thinks "Ah, I got the command last time, so it must want the value" and queues up the value to be sent the next time a transaction occurs.  That then gets thrown away, since that occurs when the next "command" is sent.

You need to be a little more cunning, and implement a finite state machine to work out where in the stream you are.

When SS falls set a "byte counter" to 0.
When a byte is received examine the "byte counter":

Byte 0: If it's an "a" then place the first byte of the value in SPDR.
Byte 1: Place the second byte of the value in SPDR
Byte 3: Do nothing (or place 0 in SPDR)

Increment the byte counter

So the transaction goes something like this (1570 is 0x622 in hex, and I choose "little endian" since the AVR is naturally little endian):

Master Sends        Slave Queues          Master Receives
'a'                 0x22                  Rubbish
0                   0x06                  0x22
0                   0x00                  0x06

'a'                 0x22                  0x00
0                   0x06                  0x22
0                   0x00                  0x06

The important thing to remember is that the master receives what the slave queued on the next transfer.


sensor sampling frequency I have a problem collecting data from my accelerometer/gyroscope sensor with a constant sampling rate. Is there a way to program the arduino to collect data from the sensor and store these values in a SD card with a constant frequency of 1kHz without using delay? The sensor that I am using is a MPU6050 gy-521 sensor that uses I2C with arduino. I will be reading 6 different datas from my sensor: acceleration in x,y,z directions and gyration in x,y,z directions. Thank you all in advance for the advice/help.

so my project will be making a device that collects the values from the sensors and saves them to study the data later. First, a LCD display will print out a message without having any data collection to occur. The data collection will start when a button is pushed. After the button is pushed, the display will print out another message saying that the arduino is collecting data and the Arduino will save the 6 values (x,y,z acceleration and gyration) from the accelerometer/gyroscope sensor to the SD card. The data collection will stop after the button is clicked again and the display will print out another message saying that it has stopped collecting data. Then, this process can start again if the button is clicked once again. Thanks in advance

You have discovered delay() does not guarantee the period of your code.  This is because the period of your code is the delay() plus the time for your code to execute.

What you need is a hardware clock to give your code an indication that a fixed period has expired.  This is one of several Arduino timer libraries. The timer library web page describes your problem in more detail with example code using delays and using the timer library features.


LCD prints weird characters when I place the print statement in setup after pinMode statements #include "LiquidCrystal.h"

const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7)

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(22, INPUT_PULLUP); // Reed switch - Row1
  pinMode(24, INPUT_PULLUP); // Reed switch - Row2
  pinMode(26, INPUT_PULLUP); // Reed switch - Row3
  pinMode(28, INPUT_PULLUP); // Reed switch - Row4
  pinMode(32, OUTPUT);
  digitalWrite(32, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("hello");
}

When I run the above code I get weird characters in my LCD. I removed all the connections to the pins` defined in pinMode and left only the lcd connections but kept the pinMode and digitalWrite statements in the code, but am still getting weird characters. But when I remove the pinMode and digitalWrite statements from my code the lcd works fine. Can anyone help me out.

Edit:
Another weird thing happened, I removed all the pinMode and digitalWrite statements do my setup() had only Serial.begin() and lcd.begin() and I only had the lcd connections. Now I put this code to print into an function called lcdprintMove() and there were other functions too which were performing other tasks when I ran it as such I got weird characters in the LCD but when I removed all of the other functions,the lcd printed fine. From this I was able to conclude that this problem can't be because of the supply but has to be something else. But I still can't figure it out.

Problem Solved

Today I commented all the digitalWrite statements and uploaded the program and it worked! So,  I am going to connect the lcd onto a separate arduino and communicate serially. Someone suggested the solution of putting a cap to ground and buff the power of 5 v pin can you explain this in more detail.

Circuit diagram   Note: Rs is connected to pin 7 and E to 6

The capacitor between 5V and GND effectively acts as a small battery. When a sudden demand in a current relatively large occurs, the system can get that extra small amount from the cap and not experience a voltage drop.


Controlling Arduino through Internet and Bluetooth I have an Arduino sketch that controls an LED through the Internet, and another through Bluetooth. The thing is I want to combine both sketches so that I can control my Arduino LED by Bluetooth as well as through the Internet. Is it possible to do that?

If I were you, I would separate the "hardware" from the "software". This is quite an interesting "pattern". It's used by almost every Operating System, to assure compatibility with devices all around the world.

But how?

Layers

The "OSI-model" typically describes a few layers. But to me, the most interesting part is the difference between "Host layer" and "Media layer".

Media Layer

The media layer(s) typically handle the transportation of your bits, addressing and data collision. In "the internet" you can 'simply' change from copper to glasfiber without it being noticeable in your end application (apart from being faster).

Host layer

The same for the host layers, whatever PC or network adapter you have, your program will run fine (if this abstraction/integration is done well).

Applying this

So how do we apply this? In a basic, small application.

We want our Host to not care too much about which Media(layer) it is using.
The Arduino has to be able to be configured or detect which media layer it is using.

Something like this is neccesary (this is not actual code, more pseudo code):

String messageBuffer = "";

void Setup(){
   setupWifi(pin1,pin2);
   setupBluetooth(pin3,pin4);
}

void Loop(){
   messageBuffer = getWifiMessage();
   handleMessage(messageBuffer);
   messageBuffer = getBluetoothMessage();
   handleMessage(messageBuffer);
}

If you set up this correctly, you'll only have to write the buffer handling code once. Which is very useful!
Handling buffers along with all the logic/effects it will cause, should be solid. You (probably) don't want different behaviour when you use bluetooth as when you use WiFi. Imagine your web-browser only working when you use copper, but not when you use glasfiber :)

Protocol

Your message should be exactly the same for WiFi and bluetooth. This way you won't have to deal with two different protocols and it will be easier to implement this at the other (control) side.

A good protocol/message can be this:

"@12#13,255,255,0;"

I use the @ as an start indication. This is very usefull for receiving, since you know where to start (obviously?).
You'll have to make rules for what will follow (maybe a set amount of characters, in my example, between @ and # it will indicate an "address". When you send it to multiple devices, you only want (in my example) device 12 to react. This often is handled by the bluetooth or wifi already, but it can be good to have some sort of unique header. So that random messages (which might look alike) won't be seen as one of your messages.
An message ID is useful, you kinda want to have different types of messages, for either "LED brightness" or "debug request" or "set output".
Each message could have an x amount of parameters, it's often better to separate these. It's important that you specify the maximal amount of parameters and what behavior they will cause.
Some protocols use a set length, but an end delimiter ";" is often the best way to let the other device know your message is completely received.

Some notes

Try to aim for existing protocols, it will be cool if your device is compatible and creating yet another protocol isn't particularly useful.
Mind that possible transmitted text does not include your start/end delimiters. You could use the message length or exclusions/inclusions in this case.
Be wary that the protocol adds overhead. But usually being able to "read" a message will make it much more easier to program a handler or generally work with it.
Check if the message is fully received and does not have errors. If you have an error, be sure your system can handle it and will respond with a message telling so. In no way your system should lock down on error or not provide a reaction (which makes debugging a pain).

The server

From whatever device you're sending your stuff, it should have bluetooth and/or WiFi. Bluetooth is fairly easy and should get you started quite fast.

If you're using WiFi, you should check if your device can make a TCP/IP connection. TCP/IP is basically a "shell" around your message, to shoot it over the internet ;D it comes with some neat addressing and error checking built in (but you can't be 100% sure there will be no error between your receiver and arduino).

But why?

Not only is it useful to learn how to do this, having to write the handler and protocol specification for both the Wifi and bluetooth (and possible usb, rf, ethernet etc).
Apart from that, in embedded systems, you want to be sure that something works, using different handlers for different physical layers will create vague specific errors and might rip up your program logic. Also, if your protocol/application is used/reviewed by more people, you'll be more certain that it works well.


Reading data from the MCP3002 I am using a MCP3002 to convert an analog signal to digital data. It works fine actually, sends good data. However; After a while, when the power is turned off and on again a few times, it only returns zeros. If I Power it on the next day, it works for a while again.

I am just beginning with SPI, so I do not know 'all' the basics. Is there something I should reset when powering on or something? (Clock, Timing, etc.)

This is the code I am using (pretty straightforward):

#include <SPI.h>
SPISettings spiSettings(7280000, MSBFIRST, SPI_MODE0);
const int SPI_CS = 2;

void setup() {
    pinMode (SPI_CS, OUTPUT);
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);
    SPI.setFrequency(7280000);
}

void loop() {
    SPI.beginTransaction(spiSettings);
    digitalWrite (SPI_CS, LOW);

    uint8_t cmd = 0b11000000;
    byte msb, lsb;
    word assembled;

    msb = SPI.transfer(cmd);
    lsb = SPI.transfer(0);

    assembled = word(msb, lsb);
    Serial.println(assembled);

    digitalWrite (SPI_CS, HIGH);
    SPI.endTransaction();
}

Is there something wrong, or should something be added to this?

I thin the following is happening:

The MCP transmits 1 measurement per SPI transaction, which consists of activating chip select, reading data and deactivating chip select. To distinguish between different transactions, the time between deactivation and reactivation of chip select need to have a bit delay between them. Currently your code runs really fast, a few microseconds between the transactions at max.

This may also be connected to the MCP needing time to measure the analog signal.

I think there is some kind of race condition, so that the MCP does not have a new value to transmit, either because the MCP hasn't finished measurement yet, or because the delay between the transactions were just a bit too short, maybe a combination of both.

When the MCP is once in this situation, it will only send zeros at that point  (read chapter 5.1 in the datasheet. Last sentence in the left column).

You need to give the MCP more time between the transactions. I suggest using a small delay at the end of the loop() function. You can experiment with the actual value, I would guess, that you can go down to the microseconds range.


Powering Arduino with car batteries Presumably, one powers an Arduino board with car batteries for long-term operation away from the power grid.

How can this be done, and what are the most (1) economic, and (2) reliable ways to do this? Specifically, do any additional risks to short the board with an extraneous discharge exist?

Use a switching regulator such as the LM2596. You can get a ready board from eBay for about US$1.

Just set the output voltage to 5 V and feed the Vcc input of Arduino; this bypasses the onboard regulator.

The benefit is that unlike the linear onboard regulator, a switching regulator is very efficient which means less consumption and less generated heat on the regulator. An additional benefit is that it can withstand a higher input voltage (about 35 V for the specified regulator), just in case the circuit is used in a vehicle that has 24 V batteries.

The regulator has already several protections like for short circuiting, overheating, etc.


Does Linux have software protection on USB? Or has the magic smoke escaped? I'm making a GUI in Python that will control an Arduino via serial monitor. I have 6 input pins grounded and I'm taking 5V from the board (powered from USB) whilst serial monitoring and everything's going beautifully.
I'm so impressed by all these flickering 0's and 1's that I drop my flying lead straight onto the tiny cap behind the USB connector on the UNO. Everything is definitely not going beautifully now.  My serial data is frozen mid-string.
I try to connect again with my serial monitor software:

Error: Could not open device /dev/ttyUSB0

Power off and on my PC and the Arduino, same result. So, I connect another board a nano this time.
The Arduino Web Editor recognizes that I have connected a Nano, but when I try to upload my code the Arduino Web Editor says this:

avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied

So, I put this in to terminal:
sudo chmod a+rw /dev/ttyACM0
chmod: cannot access '/dev/ttyACM0': No such file or directory
sudo chmod a+rw /dev/ttyusb0
chmod: cannot access '/dev/ttyusb0': No such file or directory

Thought I might have fried my USB but it's still accepting flash drives being plugged in, and I have connected to both front and back USBs with the same results. And I have power-cycled my PC.
So, not sure if I fried my Arduino, (but having 2 Arduinos with the same fault seems unlikely, especially as one was not attached when I dropped the flying lead).
Magic smoke escaped from my PC USB ports, but again it seems unlikely that front and back would be dead whilst allowing USB sticks to communicate.
Is there some kind of software fusing preventing communication that needs to be/can be reset? Or could something have become corrupted maybe?
I'm on Ubuntu 20. If anyone knows of a command I can give that will bring ttyusb0 back to life, that would be great.

The fact that you're referencing ttyUSB0 tells me you have cheap Chinese clones and not genuine Ardunios.  These are usually based around the CH340 USB interface chip which is notoriously unreliable.
Your UNO is dead.
My supposition is that plugging it in cripples the CH340 driver.  Any other boards that you subsequently plug in can not be recognised because the driver is in a bad state.
To prove this:

Unplug the UNO
Reboot (power cycle) the computer
Plug in the Nano

It should recognise the Nano fine.

Unplug the Nano
Plug in the UNO

It should fail now.

Unplug the UNO
Plug in the Nano

The Nano should now also fail.
If that sequence is correct then the Uno is definitely dead. Throw it away, or at least never plug it in through USB ever again (you could program over serial through the TX/RX pins or using ICSP as if it were a breadboard Arduino though).


Only print when the button is pressed and not being pressed anymore I have an Arduino and a microswitch that I want to use to know when the switch is initially being pressed (get "OnsetTime" on Serial) and when the switch is not being pressed anymore (get "OffsetTime" on Serial).

Imagine a bird sitting on the switch. I want to get an output "OnsetTime" when the bird first sits on the switch and an output "OffsetTime" when the bird flies away from the switch.

Right now, I have an output that constantly prints out "OnsetTime" when the switch is pressed.
I would appreciate it if anybody can help me figure out how can I implement the below code to get the outputs only when the switch is initially pressed and not being pressed anymore.

void setup() {
  pinMode(7, INPUT);
  Serial.begin(9600);
}

void loop() {
  if (digitalRead(7) == HIGH) {
    Serial.println("OnsetTime");
    }
}
    //Serial.println("GetOffsetTime");

If you want to be simple, you can use this library. The code will be

#include <ezButton.h>

ezButton button(7);  // create Button object that attach to pin 7;

void setup() {
  Serial.begin(9600);
  button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop() {
  button.loop(); // MUST call the loop() function first

  if(button.isPressed())
    Serial.println("OnsetTime");

  if(button.isReleased())
    Serial.println("GetOffsetTime");
}

If you want to understand in depth, You can see the code and instruction in this tutorial


RGB LED strip green LEDs cannot be dimmed to less than 50% I have an RGB LED strip which I want to control with my arduino uno, everything works fine, except for the green LEDs.
They cannot be dimmed to less than 50%, because they will simply turn off.

I have this test code in my setup:

Serial.write("dimming green test started");
for(int x = 255; x > 0; x--) {
    analogWrite(greenPin,x);
    Serial.write(" - g:");
    Serial.print(x);
    delay(6);
  }
  Serial.println();
  Serial.write("dimming green test done");
  Serial.println();

And the green LEDs are fully turned on in the beginning, and at about 127, the just turn off. All the other colors are perfectly dimmable.
I checked the energy usage, and green does only use a little more than the other colors, so that's not the problem.

Are green LEDs not dimmable? Or is this just an optical effect?

(I use a setup very similar to this one with one difference: but only use 5V, because my LED strip only needs 5V)

analogWrite only works on pins that support PWM. Those are the pins with the ~ next to it.

On no-PWM pins, analogWrite will set the pin to LOW, for all values lower than 128, and HIGH for all the higher values. Which is what you are experiencing.


Adjust resistance of a circuit I need to emulate a component that measures an input mechanically and varies resistance from 0 to infinity (a more detailed set of specs list it at 20-1,000ohms, though I'll have to actually check its true values myself once I have physical access to it).

My aim is to replace this troublesome mechanical component with a current (read as available and serviceable) component, and convert the signal from the new component into an emulated signal (varying resistance) from the old component.

I am not certain as to the resolution required (how big the steps can be), though it may be able to handle 50ohm 'leaps', just judging by the range of mechanical movement and my past experience with replacing similar mechanical systems with ready-made kits for conversions.  I'd like to smooth the curve a whole lot more than 50ohm leaps though.

I have barely an idea where to begin on this.  I thought maybe a resistor ladder and a set of transistors triggered by the arduino to connect into the different points in the line, though I suspect there has to be a better way to achieve a much better result (and I don't think I have enough outputs for that anyway).

Is there a digital component that can vary its resistance using a PWM signal or maybe an analog signal from an arduino?

FYI, I greatly appreciate your input.

EDIT

The controller provides a constant voltage to the component, and the controller then looks at the ground (the voltage over a static resistor) I presume. It is an actual load.

I may be able to provide a variable voltage to the controller on its ground pin, though I have never seen that done on them before. I think that may be the trick, though the controller may(??) dislike it? I can try that.. The next best thing (only 2nd because it requires more components) would be the digital pot.

Anyone ever forged a return signal on a circuit thats supposed to supply its own constant voltage to a resistor type sensor?

What about a digital potentiometer
Digital Pot

Many types available, generally controlled via a serial interface e.g SPI


Send files via network I want to send a file from an Arduino to the server or another Arduino.

I wrote a code that's open the file then write the content of the text on an array and then send it.

That would work if the data is small, but when i try to send, .wav it will takes lots of time if i do it that why (storing each byte in array).
I want to send the whole file at on time.
Is there a way or a library helps ?

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

const int push1 = 2;

File myFile;
char a[400];
int c= 0;

// network parameters
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x05, 0x02 };  // ethernet interface MAC address
IPAddress localIp(10,131,41,72);    // local ip address
IPAddress destIp(10,131,41,74);      // destination ip address
unsigned int port = 9631;               // destination port

// EthernetUDP to send and receive messages.
EthernetUDP Udp;

// timing

// setup the arduino and shields
void setup() {

    pinMode(push1, INPUT);

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

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // start ethernet and udp
  Ethernet.begin(mac, localIp);   // static ip version
  //if(Ethernet.begin(mac) == 0) {     // dhcp version
  // report failure to obtain network parameters
  // Serial.println("DHCP error");

  // no point in carrying on, loop indefinitely:
  // while(true)
  // ;
  //}

  // open UDP port
  Udp.begin(port);

  // show the local ip address (useful for dhcp)
  Serial.print("Local IP: ");
  Serial.println(Ethernet.localIP());

  // initialize previous millis variables

}

// do tasks
void loop() {

if(digitalRead(push1) == LOW){

   myFile = SD.open("R.wav" , FILE_READ);

  if (myFile) {
    // read from the file until there's nothing else in it:
    Serial.println("i will send now");
    while (myFile.available()) {
        a[i] = myFile.read();
        i++;
        }
      Udp.beginPacket(destIp, port);
     Udp.write(a);
      Udp.endPacket();
      Serial.println("Sending UDP message");
      Serial.println();
    }
    // close the file:
    myFile.close();
  } else {
   // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }  } }

You may try:

Serial.println("Sending UDP message");
Udp.beginPacket(destIp, port);
while (myFile.available()) {
  Udp.write(a);
}
Udp.endPacket();
Serial.println("Message sent!");

Or send the message part by part (for example 100bytes or 500bytes at a time)

Though, what makes you think that Arduino would be a platform that can rapidly send large files over network?
Potentially you are better off with an Raspberry Pi.


Failed to read DHT22 sensor using Intel Galileo Gen2 board Why do I end up with the display

  Failed to read from DHT sensor!

in the serial monitor in most cases when I run the code given below? When I reduce the delay to 1000ms the reading shows 0.00 for both temperature and humidity which, as well, is pretty much false. Any help would be highly appreciated.

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for Arduino Due:
//DHT dht(DHTPIN, DHTTYPE, 30);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hi);
  Serial.println(" *F");
}

The article link by Nick is the same that I found, so it must be a well search problem.
What is described on the Intel forum is that the Galileo is not capable of direct communication with the sensor as it is a computer and not a microcontroller, so therefore lacks the ability for accurate timing required by the sensor and also the DHT* is considered a peripheral and would thus require a way to interface with the "PC".
What is described in the post is to use two pins to create the proper digital signal for the DHT.
The circuit makes use of a diode to protect the output pin.
The OP on the forum describes the connections like this:

Pin 2 of Galileo is connected to the data pin of the DHT11.
Cathode of the diode is connected to pin 3 of the Galileo.
Anode of the diode is connected to the DHT11 data pin.

The diode would be a standard diode, possibly a fast switching signal diode as the 1N4143. The resistor would be the standard pull up resistor of 10K Ohms.
Here is the OPs schematic:

(source: intel.com)
You will also need to make use of the code linked to by the OP in the linked post as it was modified to work with the workaround.


How is this code working?? val3 is defined as constant const int val3 = 7;
void setup(){
  Serial.begin(9600);
  int val3 = 8;
  int val4 = 4;
  Serial.print(calc(val3,val4));
}

void loop()
{}

int calc(int val1, int val2)
{
  return val1 + val2;
}

this code gives output as 12.

In your code, the const int val3 = 7; definition, is outside of any functions so it defines a global constant/variable (available in every part of your code).

The int val3 = 8; definition is inside your setup () function, so it acts as a local variable only within that function. This overrides the val3 constant defined outside of the setup () function. I.e. the global val3 constant and the local val3 variable inside of setup () are not the same variable, which will inevitably lead to confusion (as in your case).

It’s valid syntax but I don’t consider it good coding practice. It’s good to know why it works that way though.


Can this work as a waterproofing method? Im making my garden automated with temperature, humidity and soil temperature sensors. I want to be able to connect my Arduino Uno to a solar panel and keep it outside at all times. I dont want to have to remove it to water the plants. Could I cover it in clear nail polish to water proof it?

Nail polish would work in general as a fair conformal coating. However, conformal coatings are not generally intended as waterproofing, but moisture or humidity resistance.

If you product is going to be regularly submerged or deluged with water, you are better off using a waterproof enclosure with a good watertight gland around the cable entrance.


Can I use atmega328P without capacitors? I need to use atmega328P without arduino board, so far I know that I will need 16MHZ Quartz Resonator and two 22nf capacitors. However, I have seen that other people are using atmega328P without capacitors.

What is the role of those capacitors? Can I use atmega328P without capacitors?

Those specific capacitors form part of the resonant clock oscillator circuit. If you are using a quartz crystal then they are required. You can't do without them.

If you use a 16MHz ceramic resonator, however, they don't need the capacitors (they're built into the resonator).

Also, if you have your ATMega328P on a breadboard the capacitance of the board itself is sometimes enough to "get it working", though as soon as you transfer your circuit to a permanent PCB it will suddenly stop working for no apparent reason.


Ultrasonic Sensor receiving Side I'm doing my project regarding 40khz ultrasonic sensor which will be used to get accurate distance measurements. I have a separate transmitter and receiver. I want to get the time between the moment my transmitter transmitted the waves and the time my receiver received it. However, I couldn't actually make it work. Does any of you give me a code that would help me transmit and receive the 40khz waves and get the time in between so I could use it to compute for the distance?Thank you in advance. I would greatly appreciate it!

This is the most basic ultrasound pulse and receive code. I wrote it to work with the HC-SR04 modules; so hopefully it will work fro you too as those also sound at 40khz.

The main functionality comes from the pulseIn() funciton.

#define TRIGPIN 9
#define ECHOPIN 10

void setup() {
  Serial.begin(9600);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(ECHOPIN, INPUT);
}

void loop() {
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);

  uint16_t duration = pulseIn(ECHOPIN, HIGH, 4000);
  int distance = (duration*.0343)/2;
  Serial.println(distance);
}

Note that you will need to adjust the 4000 (μs) to whatever timeout in you want (or emit entirely if you don't want it).


Soft wdt reset error on NodeMCU (ESP8266) I am getting error on Serial monitor Soft WDT reset. I decoded the error code also and found the following stacktrace.
I am using SIM808 module and DFRobot_sim808 as the library.

0x4010030d: millis at AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_wiring.c line 180
0x401003b9: __digitalWrite at AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_wiring_digital.c line 82
0x40202863: sim808_wait_for_resp(char const*, DataType, unsigned int, unsigned int) at Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 172
0x402027a4: sim808_send_byte(unsigned char) at Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 118
0x402028ce: sim808_check_with_cmd(char const*, char const*, DataType, unsigned int, unsigned int) at Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 191
0x402025dc: DFRobot_SIM808::init() at Documents\Arduino\libraries\DFRobot_SIM808-master/DFRobot_sim808.cpp line 63
0x402024c1: setup at G:\Development\ESP8266\SIM Module\sim_module/sim_module.ino line 41 (discriminator 1)
0x40203248: loop_wrapper() at AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_main.cpp line 122
0x40100e8d: cont_wrapper at AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/cont.S line 81

I tried to find solution for the same everywhere but none found it. But the same code I am trying on arduino it works but not for ESP8266. I dont have long waiting loop(). But still it gives me error.
Below is the code for the same
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PHONE_NUMBER "********"

#define MESSAGE  "hello,world"

#define PIN_TX D1
#define PIN_RX D0

SoftwareSerial mySerial(PIN_RX, PIN_TX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

void setup() {
  delay(1000);
  mySerial.begin(9600);
  Serial.begin(9600);

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB
  }
  while(!sim808.init()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }
  Serial.println("Sim808 init success");
  Serial.println("Start to send message ...");

  sim808.sendSMS(PHONE_NUMBER,MESSAGE);
}

void loop() {

}

The culpret is the SIM808 library. It's not written to work well with the ESP8266.

The problem lies in this function:

boolean sim808_wait_for_resp(const char* resp, DataType type, unsigned int timeout, unsigned int chartimeout)
{
    int len = strlen(resp);
    int sum = 0;
    unsigned long timerStart, prevChar;    //prevChar is the time when the previous Char has been read.
    timerStart = millis();
    prevChar = 0;
    while(1) {
        if(sim808_check_readable()) {
            char c = serialSIM808->read();
            prevChar = millis();
            sum = (c==resp[sum]) ? sum+1 : 0;
            if(sum == len)break;
        }
        if ((unsigned long) (millis() - timerStart) > timeout * 1000UL) {
            return false;
        }
        //If interchar Timeout => return FALSE. So we can return sooner from this function.
        if (((unsigned long) (millis() - prevChar) > chartimeout) && (prevChar != 0)) {
            return false;
        }

    }
    //If is a CMD, we will finish to read buffer.
    if(type == CMD) sim808_flush_serial();
    return true;
}

It has a loop that can take some time to run, and it doesn't yield() at any point to allow the ESP8266's housekeeping routines to run and "kick the dog".

Adding a call to yield() inside the while(1) loop should cure the problem.


Proper use of * and & when passing objects in methods Coming from C#, pointers are somewhat foreign although I am grasping the concept.
Is it proper to construct methods in the following manner and passing the object (as a parameter) constructed by reference? If not, then please answer how to do this properly.

Initialize the object

Adafruit_VS1053_FilePlayer musicPlayer =
    Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

Method: (use the * for pointer?)

boolean initializeMusicPlayer(Adafruit_VS1053_FilePlayer *mp, uint16_t baudRate) {

    musicPlayerSerialPort.begin(baudRate);
    // initialise the music player
    if (!mp->begin()) { // initialise the music player
        Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
        return false;
        //while (1);
    }
    Serial.println(F("VS1053 found"));

    mp->sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

    if (!SD.begin(CARDCS)) {
        Serial.println(F("SD failed, or not present"));
        return false;
        //while (1);  // don't do anything more
    }
    Serial.println("SD OK!");
    // Set volume for left, right channels. lower numbers == louder volume!
    mp->setVolume(20, 20);

    if (!mp->useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
        Serial.println(F("DREQ pin is not an interrupt pin"));
        return false;
    }
    return true;
}

Call the method (Use the ampersand to pass the currently created one by reference?)

if(initializeMusicPlayer(&musicPlayer, 9600) == true) {
    tempString = tempString + "MusicPlayer initialized!";
    Serial.println(tempString);
    //when adding lcd, print the above to lcd and remove the serial print
}

The method you have implemented, passing by pointer, is one of the two normal methods, yes. The other is passing by reference and is specific to C++, not C.

Under the hood the end result is the same between the two methods, by the syntactic "sugar" is very different and the latter can be preferable for that reason alone.

Your method:

void function(whatever *ob) {
    ob->method();
}

function(&myObject);

The pass by reference method:

void function(whatever &ob) {
    ob.method();
}

function(myObject);

As you can see the need to convert the object into a pointer with & is now gone. That makes it much easier for people lacking in programming skills to use it since it hides the whole pointer mechanism from them.

Also, internally your function now treats ob as just another object using ., rather than a pointer to an object and needing to use ->.  Note that you can only use the reference operator in a function prototype, not a variable or anything like that - it's purely for passing objects and variables to functions.  If you want to then go and store the pointer in a variable you still then have to get the address:

void function(whatever &ob) {
    myObjectPointer = &ob;
}

As you see it gets confusing with the two different uses of &. Basically though: if it's in a function prototype it's the pass by reference operator. If it's anywhere else it's the get the address of operator (or a logical AND of course).

Storing the pointer can be useful if you want to then do other things later on with the same object, especially if you are yourself working with a class.  For instance, I often write code similar to the following:

class foo {
    private:
        bar *ob; // Pointer to other object of type "bar"
    public:
        foo(bar *inob) : ob(inob) {}
        foo(bar &inob) : ob(&inob) {}

        void something() {
            ob->doSomething();
        }

        void somethingElse() {
            ob->doSomethingElse();
            ob->evenMoreThings();
        }
};

You then have a choice of constructors:

bar myBar;
foo myFoo(myBar);

// ... later ...
foo.something();

or

bar myBar;
foo myFoo(&myBar);

// ... later ...
foo.something();

and the user doesn't have to remember which they need to use - whichever they try will work.


Not understanding C++ arrays I'm attempting to re-write a library for the CD74HC4067 multiplexer.  There is a library available for this device on the Arduino Playground, however, it's limited in its functionality.

I have this as a private data member in the class header file:

uint8_t channelSelects[16][4];

And this in the class constructor:

CD74HC4067::channelSelects[16][4] = {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
};

And I'm getting this error:

cannot convert '<brace-enclosed initializer list>' to 'uint8_t {aka unsigned char}'

Could someone please explain what I'm not understanding here ?

Many thanks in advance.

If you have in your constructor this:

CD74HC4067::channelSelects[16][4] = ...

then you are trying to assign something into the element at position [16][4]. Thats why it's telling you

  cannot convert '' to 'uint8_t {aka
  unsigned char}'

Anyway - you don't even need that second dimension. You can use binary representation like  0b00001000 ...

And if you'll think about previous line, you don't even need any array, you can do it with simple counter value and getting its bits.

However if you want to rely on this array, the constructor should look like:

CD74HC4067::CD74HC4067() :
  channelSelects {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
  }
{
   // constructor code
}

(maybe one more {} enclosure, I'm not sure right now exactly)

EDIT: I'd go this way (if you need only one or two instances):

// ADC READ channel + Address selection pins
template <uint8_t ADC_Chan, uint8_t Addr0, uint8_t Addr1, uint8_t Addr2, uint8_t Addr3>
class Mux16b {
public:
  void initPins () {
    pinMode(Addr0, OUTPUT);
    pinMode(Addr1, OUTPUT);
    pinMode(Addr2, OUTPUT);
    pinMode(Addr3, OUTPUT);
    pinMode(ADC_Chan, INPUT);
  }

  int readMux(uint8_t channel) {
    digitalWrite(Addr0, channel&1 != 0);
    digitalWrite(Addr1, channel&2 != 0);
    digitalWrite(Addr2, channel&4 != 0);
    digitalWrite(Addr3, channel&8 != 0);
    // maybe some delay to stabilize voltage at the ADC_Chan input ??
    return analogRead(ADC_Chan);
  }

  // not necessary but it's easier to use   mux(10) than mux.readMux(10)
  int operator()(uint8_t channel) { return readMux(channel); }
};

// analogRead from A0, Address pins: 4 9 5 2
Mux16b<A0,4,9,5,2>  mux;

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

void loop() {
  Serial.println(mux.readMux(15));

  Serial.println(mux(12)); // using overloaded operator ()

  delay(5000);
}


How to build a valid HTTP Response. Recv failure: Connection reset by peer I'm developing an Arduino server that should respond with a message when it receives a POST Request.

If I test my project with a HTTP Client (like insomnia or postman), I get an error:

Error: Failure when receiving data from the peer

I still get a response that I can read but with a final error.

That's my client request:

> POST /SOMETHING/ HTTP/1.1
> Host: [ARDUINO IP]
> User-Agent: insomnia/6.2.0
> Accept: */*
> Content-Length: 0

And this is my Arduino response considered as not valid:

< HTTP/1.1 200 OK
< Connection: close
< [MY MESSAGE]

* Recv failure: Connection reset by peer
* stopped the pause stream!
* Closing connection 2

As you can notice, I just added 2 strings

HTTP/1.1 200 OK
Connection: close

before the real message.

Am I missing something to create a valid response?

Thanks

HTTP requires an empty line after HTTP headers.

First line is status line. Then the header lines. The headers are terminated by an empty line. Then the response body follows. Line terminator for HTTP is \r\n. Arduino println() function uses \r\n.

The response with body should contain Content-type and Content-length header. Alternative to Content-lenght is "chunked" Transfer-Encoding.

ESP8266WebServer library handles HTTP for you.


IoT gabage monitoring system with my own Android application I'm developing a device system in our campus - my aim is to provide three IoT smart garbage containers that will get the fill level (to determine the space of garbage inside and to inform the garbage collector if the garbage is empty, not yet full and full), temperature and humidity from the garbage bin and will send the information to my application that I'm going to develop.

I don't know how I can connect these three IoT devices which are a fair distance from each other. I know it should be wireless though I can't figure out the exact Arduino device to provide connection to my mobile application.

Does your campus have WiFi? If so, go with EPS8266 if its pins are OK for your sensors.
ESP Pinout

You'd want to keep an eye on power consumption; you'd sample your sensors per desired interval and deep-sleep at all other times. Check out available sleep here. It also has en example of how to sample and send a sensor, and sleep afterwards.

On the application end, you could either use a ready service such as Blynk, or go for a custom solution and send the data on your server. Of course, you would then need to write an API and some sort of application to present your data.

Let me also point out that for measuring garbage level, you should calculate the total volume of your bin and subtract the volume of garbage your sensor detects. Having non-uniform trash would give you some trouble, but it's a good technique for an estimation of garbage volume. Also, if using ultrasonic distance sensors, given the fact that you have temperature readings available, you should compensate your measurements; check this out.


How to restart USB subsystem? I'm developing on the Arduino platform (ESP8266 with USB -> serial) and sometimes the USB port that is being used stops working and gets frozen. Then I need to plug the device into another USB port. It happens again and once all the USB ports stop working I have to restart the machine, which is really annoying.

As far as I remember there is a command that can restart the USB subsystem individually, but I can't remember. How to restart USBs without restarting the entire system? Thanks.

I'm using Mac OS X Sierra.

You are using a USB to UART adaptor. The Arduino has no concept of what that is - it just sends and receives UART data. The adaptor is completely separate and the Arduino can do absolutely noting at all with it.

If you are powering the whole circuit through that adaptor it may well be that it only requests 50mA from the computer. If you draw more than that (which you most likely are) the computer is free to shut the port down. It sounds like that may be what is happening.

What can you do? Well, two things:

Use an adaptor that requests enough current for your needs (may be hard to find)
Power your circuit separately using another power source.

Of the two I would suggest external power.


How can I loop my code? For example after 30 minutes? So I have this code which records the temperature and humidity using a DHT22 sensor. After it get's the values it then sends it to a webpage using PHP $_GET method, where that gets imported into a DB and emails (using PHP). But this only happens when I upload the code to my ESP8266; how can I know build in a loop function that it sends it every 30 mins or given time?

#include <ESP8266WiFi.h>
#include "DHT.h"

const char* ssid     = "bbox2";      // SSID of local network
const char* password = "azerty";   // Password on network

WiFiClient client;
char servername[]="lucasdebelder.be";  // remote server we will connect to
String result;

float temperature;
float humidity;

#define DHTPIN 14

#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

void loop() {

}

void sendDataToServer(String temperature, String humidity)
{
  if (client.connect(servername, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /send_temperature.php?temperature="+temperature+"&humidity="+humidity+" HTTP/1.1"); //Send data
    client.println("Host: lucasdebelder.be");
    client.println("Connection: close");  //close 1.1 persistent connection
    client.println(); //end of get request
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

 while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
      result = result+c;
    }

  client.stop(); //stop client
  Serial.println(result);

}

void readSensor()
{

  humidity = dht.readHumidity();
  temperature = dht.readTemperature();
  Serial.println("Temperature:");
  Serial.println(temperature);
  Serial.println("Humidity:");
  Serial.println(humidity);

}

You execute the corresponding function only in the setup() function, which is called once on startup of the ESP. After that the loop() function is called repeatedly. The setup() function is meant to "setup" your code for it's functionality, which is then executed in the loop() function. For example you are begin the Wifi connection and connect to a network in there, because you need the network for your main functionality.

So you have to put the code from readSensor() until (and including) sendDataToServer() into the loop() function. This will execute this code repeatedly.

Then you have to introduce some concept of time, else your code will be executed very fast, effectively flooding your webserver. The easiest way would be to add a call to delay(30000), which would delay the code for 30s. But using delay is not considered good coding style, since it is basically busy waiting and you cannot do anything else during that time.

So to be able to add other functionalities in the future you can implement the time concept with non-blocking code. Take the BlinkWithoutDelay example from the Arduino IDE as reference. It uses the millis() function, which counts the milliseconds since the startup. You save a timestamp of the last execution of your code and wait until the difference between the current time (given by millis()) and your timestamp is greater than 30s. In this time the ESP can do other things, since it still goes through the loop() function undisrupted. Then after the timespan you execute the code and reset the timestamp to the current time.


Array is affecting digitalread values i want to turn on an led with two buttons. If either of the buttons is pressed i want the led to turn on while the button is pressed and stay off if nothing is pressed. i have two sets of code, they both do the same thing, but the second set of code causes the led to stay in the on position even when nothing is being pushed and i dont understand why.. i am using pulldown resistors on both the buttons.

This is the first set of code that works properly:

class Button {

  public:

    int pin;
    int state;
    int location;
    int Speed;
    int Direction;
    int active;
    int prevstate;

    Button(int pin1, int state1, int location1, int active1, int previousState)
    {
      pin = pin1;
      state = state1;
      location = location1;
      active = active1;
      prevstate = previousState;
    }
};

Button button(7,0,0,0,0);
Button button2(8,0,0,0,0);
Button buttons[2] = {button, button2};

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

void loop() {
   if (digitalRead(button2.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
       if (digitalRead(button.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
}

this is the code i want to use but it is not working.. the led stays in the on position:

void loop(){
  for (int i = 0; i<sizeof(buttons); i++){
    if(digitalRead(buttons[i].pin) == HIGH){
          digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
    }
}

also if i change

if(digitalRead(buttons[i].pin) == HIGH)

to

if(digitalRead(buttons[0].pin) == HIGH)

the code works for the first or second button alone in the array.. but not both???

I have to disagree that your first sketch is working. I suppose that a very fast blinking led seems to be "on".

When you describe what should happen in a logic way, then you can put that into code.

The logic is: The led is on, if at least one of the buttons is pressed.
In other words: The led is off, if no button is pressed, else the led is on.

This logic has as a result that the led stays on if a second button is pressed and after that the first button is released. I assume this is okay.

For two buttons it is possible to check both conditions.

if (digitalRead(button.pin) == HIGH || digitalRead(button2.pin) == HIGH)
  digitalWrite(ledPin, HIGH);
else
  digitalWrite(ledPin, LOW);

Or test for LOW:

if (digitalRead(button.pin) == LOW && digitalRead(button2.pin) == LOW)
  digitalWrite(ledPin, LOW);
else
  digitalWrite(ledPin, HIGH);

For multiple buttons, a bool can be used or the number of pressed buttons can be counted.

A fixed number for the array size is easy and has less chance for a mistake:

#define BUTTONS_COUNT 2

It is also possible to use sizeof(). The total size has to be divided by the size of one element:

int count = 0;
for (int i = 0; i<sizeof(buttons)/sizeof(Button); i++) {
  if (digitalRead(buttons[i].pin) == HIGH) {
    count++;
  }
}

if (count == 0)
  digitalWrite(ledPin, LOW);
else
  digitalWrite(ledPin, HIGH);


Uploading Marlin Firmware To Melzi-ATmega1284p I'm trying to flash the Marlin Firmware to my Prusa i3 3D Printer, which uses Melzi 2.0 board. Melzi is a variation of Sanguino, and Sanguino is a variation of the Arduino.

The problem is that the version I'm using of Marlin (this one, development branch) only works with Arduino Mega. I saw that the file pins_RAMPS_13.h says the following (line 15-17):

#if !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__)
   #error Oops!  Make sure you have 'Arduino Mega' selected from the 'Tools -> Boards' menu.
#endif

So I tried to make this part to look like this:

#if !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(__AVR_Melzi_ATmega1284p16mhz__)
   #error Oops!  Make sure you have 'Arduino Mega' selected from the 'Tools -> Boards' menu.
#endif

Does anybody know if there's another repository made for the Melzi board?
Or if I should use another firmware, like Repetier (I tried, fail)?
Thanks for any help.

It looks like the Marlin firmware supports two versions of the Melzi board, although it isn't clear if it specifically includes the 2.0 version. The best thing to do is just try it. In the Configuration.h file find the section where it says:

#ifndef MOTHERBOARD
  #define MOTHERBOARD BOARD_ULTIMAKER
#endif

Now replace BOARD_ULTIMAKER with BOARD_MELZI_1284 and try that. If that doesn't work you can try just BOARD_MELZI. If neither of those work, you are out of luck, unless you are willing to dig in and do the pin mappings yourself.


Why does an Arduino Uno have 2 microcontrollers I was looking at this schematic:

And I noticed that there are 2 microcontrollers (an Atmega328p and a ATmega16U2).  I was wondering why there need to be 2 microcontrollers.  Do they do different things that only 1 of them can do and the other can't ?

Atmega328P is a microcontroller which are the heart of Arduino Uno, where the Atmega8U2 is the USB to serial convertor for arduino communicated with computer.

You can refer to this link for more information about this.


How can I set up outputs without using digitalWrite? Consider the following:

#define IN1 9
#define IN2 10

pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);

void LeftMotor(Direction direction) {
  digitalWrite(IN1, direction == Forward ? LOW : HIGH);
  digitalWrite(IN2, direction == Forward ? HIGH : LOW);
}

How can I modify the LeftMotor method to achieve the same result without using digitalWrite?

digitalWrite() is just a convenience function to hide away complexity from the user, so that she/he can just use a pin number and a value. This complexity takes some time to execute. If this is too slow for you, you need to go a bit deeper into the rabbit hole and use direct port manipulation:

Inside the microcontroller on the Arduino all the special functions for peripherals and such (digital IO, ADC, Serial(UART), SPI, Timer, ...) are configured via Special Function Registers (SFR). These are specific memory places, that are directly connected to the peripherals. You can configure the whole microcontroller by setting these registers to specific values.

For digital IO you first need to know, that the microcontrollers pins are ordered into groups of max 8 pins. These groups are called Ports. Each available port of the microcontroller gets a character, like PORTB. On the Arduino Nano for example PORTD includes the pins 0 to 7.

For each port we have 3 different SFRs (with the x being the character for the corresponding port), where each bit inside the registers corresponds to one pin:

DDRx controls the direction of the pins. If you set a bit to 1 in there, the corresponding pin is set as output. If you set it to zero, the pin will be an input (which is also called High-Z for high impedance, because a digital input pin has a very high resistance).
PORTx controls the output hardware of the digital pins. If you have set a pin as output (as described above) you can use the corresponding bit in the PORTx register to set it's state. If you write a 1 to the bit, the pin will become HIGH (means, the voltage on the pin will go to the same level as Vcc, the supply voltage of the micrcontroller). If you write a zero, the pin will go to LOW (meaning the same level as ground). The PORTx register has a different function, when you configured a pin as input. In this case, a 1 will turn on the interal pullup resistor of the pin, which pulls the level of the pin to HIGH, when nothing is pulling it down to ground (like a switch for example). A zero disables the pullup.
PINx reflects the current state of the pins. If you configured the pins as input, this is the voltage level, that currently lies at the corresponding pin (about the actual voltage levels, see below). A 1 at a bit means, that the corresponding pin is HIGH, else it is LOW.

You can read all of this in the datasheet of the used microcontroller. The datasheet is a must read (at least the relevant chapters), if you want to control the microcontroller via its registers. In most microcontrollers these registers are named as above. But some microcontrollers might define other names. The corresponding datasheet will list all the registers with rather detailed descriptions.

Now let's take that knowledge into actual code. Here I assume an Arduino Nano, though you can exchange that for most other microcontrollers.

// Configure pin D3 as output
DDRD |= (1 << PD3);
// Configure pin D2 as input
DDRD &= ~(1 << PD2);
// Check, if pin D2 is HIGH
if(PIND & (1 << PD2)){
    // Set pin D3 to HIGH
    PORTD |= (1 << PD3);
} else {
    // Set pin D3 to LOW
    PORTD &= ~(1 << PD3);
}

Excourse on bitwise operators: The code above can only be understood by knowing bitwise operators, which are very important for direct port manipulations. I will break down the operations, that are done there:

First we have PD2 and PD3. These are defines from the Arduino core. They are set to the index of the bit, that corresponds to the named pin. So PD2 is defined as 2, PD3 is defined as 3, PD0 as 0.
1 << PD3: The << operator does a bitwise left shift, which means all bits of the value on the left are shifted to the left by the amount standing on the right of the operator. We shift the value 1 three digits to the left here. In binary that looks like this:

0b00000001 << 3 = 0b00001000

That set bit in the result is exactly at the place, where the bits for pin PD3 will be in the Special Function Registers.
DDRD |= (1 << PD3):  This is the same as doing DDRD = DDRD | (1 << PD3), so the |= operator is just an abbreviation for it. The bitwise OR operator | will unite the bits from both sides. If a bit is set to 1 at either side, the result will also have set this bit to 1. This means, that we can set a bit to 1 with this.
~(1 << PD2): The tilde ~ takes the inversion of the data. Alike above, the value inside the paranthesis can be written as binary value 0b00000100. The inversion will flip all bits to the other value: 0b11111011
DDRD &= ~(1 << PD2): The abbreviation is similar to the above. The bitwise AND operator & will also unite the bits of the values around it, but it will only set the resulting bits to 1, if both of the corresponding bits of the values are also set. Here this results in the third bit (the one for D2) being cleared to zero. All other bits (where you can see a 1 at the right value) are left untouched.
PIND & (1 << PD2): This is similar to the above, but now we don't have an inversion. We are doing PIND & 0b00000100 here. All bits of the result will be set to zero, except for the bit for D2. It will only be zero, if the corresponding bit was zero in PIND. Thus we have isolated the needed bit by this way.

You can also combine the same operations on a single register. Let's say we want to set both D2 and D3 as output. Then we can either write this as two seperate statements

DDRD |= (1 << PD2);
DDRD |= (1 << PD3);

or we can combine them into one statement by connecting them with the bitwise OR

DDRD |= (1 << PD2) | (1 << PD3);

The Arduino documentation also provides a site to explain direct port manipulation. Also again you should take the time to look into the datasheet of your used microcontroller. At first it will seems very difficult, but doing these direct port manipulations is a great way of learning how to use the SFRs, and then you can do all sorts of cool stuff with your microcontroller. So it really is worth it. You don't need to read or understand the whole datasheet at once.

  How can I modify the LeftMotor method to achieve the same result without using digitalWrite?

After all this text now to the specific question. On the Nano pin 9 and 10 are PB1 and PB2. You used a conditional inside your digitalWrite() statement, which I will replace by a complete if statement here. So you can use

if(direction == Forward){
    PORTB &= ~(1 << PB1);
    PORTB |= (1 << PB2);
} else {
    PORTB |= (1 << PB1);
    PORTB &= ~(1 << PB2);
}

instead of your two digitalWrite() statements.


How to use RTC memory in NodeMCU to count awakes from deep sleep? Problem: I need to retry at least 3 times (before giving up) to reconnect my NodeMCU if it doesn't get connected to Wifi, through deep sleep cycles in order to save batteries. I thought to use RTC memory to save a counter, but it doesn't work because content of RTC RAM is unpredicatble at first power up.

Following is a NOT WORKING code, but it gives the idea of what I need to achieve. The problem is: the kounter variable is persistent through cycles, but its very first value is unpredicatble.

#define DONEPIN 5
uint32_t kounter;

void setup() {
    digitalWrite(DONEPIN, HIGH);
    //WiFi setup functions...
    // .....
    if (WiFi.status() != WL_CONNECTED) {
        ESP.rtcUserMemoryRead(0, &kounter, sizeof(kounter));
        kounter++
        if (kounter > 3) {
            digitalWrite(DONEPIN, LOW);
        }
        ESP.rtcUserMemoryWrite(0, &kounter, sizeof(kounter));
        ESP.deepSleep(60e6);
    }
}

The simplest trick is to use more than one memory location. Have one, as you have now, as a counter, and then have one or more as a "This has been configured" flag.

Ideally you want the flag to have a very low probability of occurring randomly, so using a combination of a number of memory locations would improve that.

For instance, if you read memory locations 1-4 and look for four specific bytes, that gives you about a 1 in 4 billion possibility of it happening randomly.

If you don't see those four bytes, you set the counter byte to 0 (or whatever you want your initial value to be) and set the other 4 memory locations to contain your 4 flag bytes.

Using 8 bytes for your flag would give you in the order of 1 in 1.8x1019 chance of it occuring randomly.

These "flag byte combination" are often called "magic numbers" and are used all over the place to identify either what something is, or if something is valid.


using special symbols from the U8glib library I enter font symbols into the u8g.setFont() and I get a string of sympols. How do I grab just one of those symbols, for example an arrow?

setFont just tell how display the next drawStr (or similar text output function).

To draw an arbitrary UTF8 char, just use

drawUTF8

C++/Arduino Prototype:

u8g2_uint_t U8g2::drawUTF8(u8g2_uint_t x, u8g2_uint_t y, const char *s)

C Prototype:

u8g2_uint_t u8g2_DrawUTF8(u8g2_t *u8g2, u8g2_uint_t x, u8g2_uint_t y, const char *s);

Description:

Draw a string which is encoded as UTF-8. There are two preconditions for the use of this function:

The C/C++/Arduino compiler must support UTF-8 encoding (this is
default for the gnu compiler, which is also used for most Arduino
boards), and
The code editor/IDE must support and store the C/C++/Arduino code as UTF-8 (true for the Arduino IDE).

If these conditions are met, you can use the character with code value greater than 127 directly in the string (of course the character must exist in the font file, see also setFont).

Advantage: No escape codes are required and the source code is more readable. The glyph can be copied and paste into the editor from a "char set" tool.

Disadvantage: The code is less portable and the strlen function will not return the number of visible characters. Use getUTF8Len instead of strlen.

Arguments:
        u8g2: A pointer to the u8g2 structure.
        x, y: Position of the first character on the display.
        s: UTF-8 encoded text.

Returns: Width of the string.

Note 1: This drawing function depends on the current font mode and drawing color.
Note 2: Use the print function to print the value of a numeric variable.

See also: setFont drawStr print

Example:

u8g2.setFont(u8g2_font_unifont_t_symbols);
u8g2.drawUTF8(5, 20, "Snowman: ☃");


Is it possible to have an Adafruit music maker shield and a sensor connected to the same Arduino? Are the analog I/O pins on the Arduino still available for sensors when there is an Adafruit Music Maker shield attached to it? I want to play a sound file, but only when a PIR sensor senses motion.

If you look at the PCB of the Adafruit Music Maker here:

https://learn.adafruit.com/assets/16643

You can see that there are no connections on the analog I/O of the Arduino.


Arduino communication protocol with python - beyond pyserial and Arduino example TL;DR does someone know of a advance and reliable/redudent USB protocol for communicating between a raspberry pi and Arduino due (native port)

I am trying to learn how to build a little robot which I hope could be autonomous at some point. In terms of hardware I am using an Arduino Due and a raspberry pi 3. The former is connected to DC motors, servos, ultrasonic sensors, light sensors, etc... The pi is responsible for running the picam and sending controlles from an Xbox controller to the Arduino as well as running a django web interface.
Long story short, I am trying to have python reliably communicating with the Arduino over serialusb (using the native port) but with no luck. The simple communication protocol shown in the Arduino example is too weak. I found a GitHub project named arduino-robust-serial https://github.com/araffin/arduino-robust-serial which worked at first but for reasons which are quite long to discuss here was not enough.

My question is as follows: does someone know of a reliable serial protocol around which could be used to have a raspberry pi communicating with an Arduino over usb?

I hope I'm not too vague. But looking online I'm struggling to find resources regarding Arduino which are not beginner blinking light examples.

Thx

Ok, after quite some time looking for something that would allow me to easily control an arduino with the raspberry pi, I found the FIRMATA protocol which allows one to communicate with the arduino through many languages. (a snippet from the github page for SEO purposes is shown at the end of this message).

From there I looked for through the python frameworks, and had a long chat with MrYsLab who helped me integrate the arduino Due to his pymata and pymataExpress frameworks. They work quite well and enable you to have a script that quickly and efficiently communicates with the arduino. I'm sure proper frameworks from ros.org or gobot are better. But pymata worked for me hence my answer to my own question.

processing

https://github.com/firmata/processing
http://funnel.cc

python

https://github.com/firmata/pyduino
https://github.com/lupeke/python-firmata
https://github.com/tino/pyFirmata
https://github.com/MrYsLab/PyMata
https://github.com/MrYsLab/pymata-aio

perl

https://github.com/ntruchsess/perl-firmata
https://github.com/rcaputo/rx-firmata

ruby

https://github.com/hardbap/firmata
https://github.com/PlasticLizard/rufinol
http://funnel.cc

clojure

https://github.com/nakkaya/clodiuno
https://github.com/peterschwarz/clj-firmata

javascript

https://github.com/jgautier/firmata
http://breakoutjs.com
https://github.com/rwldrn/johnny-five

java

https://github.com/4ntoine/Firmata
https://github.com/kurbatov/firmata4j
https://github.com/reapzor/FiloFirmata

.NET

https://github.com/SolidSoils/Arduino
http://www.imagitronics.org/projects/firmatanet/
https://github.com/wbadry/FirmataCSharpClientClass

Flash/AS3

http://funnel.cc
http://code.google.com/p/as3glue/

PHP

https://bitbucket.org/ThomasWeinert/carica-firmata
https://github.com/oasynnoum/phpmake_firmata

Haskell

http://hackage.haskell.org/package/hArduino

iOS

https://github.com/jacobrosenthal/iosfirmata

Dart

https://github.com/nfrancois/firmata

Max/MSP

http://www.maxuino.org/

Elixir

https://github.com/kfatehi/firmata

Modelica

https://www.wolfram.com/system-modeler/libraries/model-plug/

golang

https://github.com/kraman/go-firmata

Qt/QML

https://github.com/callaa/qfirmata

Android/Kotlin

https://github.com/xujiaao/android-firmata

Smalltalk

https://github.com/pharo-iot/Firmata


i2c address instead of assigning pins I found this sketch online and would like to reuse it. I do have a dot-matrix-display, that is accessable through an i2c with the address 0x70. How do I change the code to be able to use the hardware address instead of the Data, Load and CLK pins?

#include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>
#include "LedControl.h"

//Pin definition constants
const int mDataIn=12, mLoad=11, mClk=10;  //Max7219 LED matrix

int h1, h2, m1, m2, s1, s2; // Each digit
int tChange; //Scratch used during change time via pushbutton

// Matrix library instance
LedControl lc=LedControl(mDataIn, mClk, mLoad,1); //Pin assignments and number of matrices (1)

void setup() {

  // Notify Arduimo that the RTC is the external time provider
  setSyncProvider(RTC.get);

  //Initialize the MAX72XX in power-saving mode.
  lc.shutdown(0,false);
  lc.setIntensity(0,1); // Set brightness to a low value
  lc.clearDisplay(0); // Clear the display
  delay(100); // Wait after initializing display

  Serial.begin(9600);
}

void loop() {

  //Isolate hours, minutes, seconds, one digit to each LED matrix column.
  h1=n1(hour());
  h2=n2(hour());
  m1=n1(minute());
  m2=n2(minute());
  s1=n1(second());
  s2=n2(second());

  // Cast as (change integer to) byte, write to LED row.
  // (Row runs from pin to pin on model used.)
  lc.setRow(0,7,byte(h1));
  lc.setRow(0,6,byte(h2));
  lc.setRow(0,4,byte(m1));
  lc.setRow(0,3,byte(m2));
  lc.setRow(0,1,byte(s1));
  lc.setRow(0,0,byte(s2));
  }

  int n1(int num) {  // Function to isolate first digit of 2-digit integer
    num = num / 10; //Integer division by 10 (discard remainder)
    return num;
  }

  int n2(int num) {  // Function to isolate second digit of 2-digit integer
    num = num % 10; //Modulo division by 10 (keep remainder only)
    return num;
  }

How do I change the code to be able to use the hardware address instead of the Data, Load and CLK pins?

That is not possible as this is two totally different LED drivers. MAX72XX uses a protocol with those signals, while the dot-matrix LED display uses I2C.

You can always port the library to the dot-matrix. Or rewrite the sketch with the dot-matrix library.

Cheers!


millis() function always returns same value I'm trying to program an Arduino MKR1000 and I am using the millis() function to emulate a traditional timer.  The problem is that any call to millis() inside the debounceTimer() function returns the same value.  I only added the Serial.print to debug.

I left out a decent bit of the code to simplify your reading of it.  It works by waiting for an interrupt on pin 4 which then calls the runTimers() function and that calls the debounceTimer() function and within that the millis() function is called. The debouncetimer() function keeps getting called until the 10 ms has elapsed and then should end the timer.  The problem is that the millis() function stops returning a value that goes up.

#define doorIntPin 4
unsigned char sysEnabled = 0;
unsigned long debounceTimerPlace =0;
unsigned char debounceTimerOn =0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(doorIntPin, doorOpens, LOW);
  interrupts();
}

void loop() {

}
void runTimers(){
  Serial.print('r');
  while(alarmTimerOn || debounceTimerOn || enablingTimerOn){
     if(alarmTimerOn)
      alarmTimer();
    if(enablingTimerOn)
      enablingTimer();
    if(debounceTimerOn)
      debounceTimer();
  }
}

void debounceTimer(){
  unsigned long time = millis()- debounceTimerPlace;
  Serial.println(millis() & 0xFFFF, DEC);
  if(sysEnabled && time> 10){
    debounceTimerOn=0;
  }
}
void doorOpens() {
  Serial.print('o');
  if(!debounceTimerOn){
      debounceTimerPlace = millis();
      debounceTimerOn=1;
  }
  runTimers();
}

I suspect that in the background an interrupt is being called than increments the value millis() returns and somehow my external interrupt is disabling that.  I don't know why this is happening or how to fix it.

Any ideas?

You never exit the ISR, hence all interrupts are disabled. Do the minimum work possible within an ISR, and have the main loop outside.


How to use unregulated VIN voltage? I have recently bought an Arduino Mega, and I am powering it with a USB charging port, 5V at 1A. I need to use the 1A with a transistor, since the Arduino itself can only supply a maximum of 20mA through one pin.
So I was wondering, is there any way to access this unregulated power source? Would the VIN pin serve this purpose, or is there no way to access the 1A current without pulling apart the USB cable?

The VIN port is connected to the barrel jack. It must only be used if you are powering the board through that jack.

To access the USB power just use the 5V pin - it is directly connected to the USB.

However, the USB, although the socket it is plugged into can supply more, is limited to 500mA. This is because of a 500mA auto-resetting polyfuse on the USB power input (the large gold and dark green rectangle next to the USB socket - mine has either XE05 or 503X on it depending on which way up you hold it).