Make upload stuck on osx 10.10 bare-arduino-project I followed the instructions in here, including to use arduino IDE v 1.0.5, but when I tried to make upload it stuck. I can upload it when using Arduino IDE.

Here is what I got:

  mkdir -p /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject
 /Applications/Xcode.app/Contents/Developer/usr/bin/make reset
 /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/Arduino-Makefile/bin/ard-reset-arduino  /dev/cu.usbmodem1421
 /Applications/Xcode.app/Contents/Developer/usr/bin/make do_upload
 /usr/local/bin/avrdude -q -V -D -p atmega328p -c arduino -b 57600 -P /dev/cu.usbmodem1421 \
        -U flash:w:/Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject/mySecondProject.hex:i

What did I miss?

I use: Bare-Arduino-Project, OSX 10.10, XCode 6.1, Arduino Uno, my Makefile

I'm the maintainer of the Bare-Arduino-Project, thanks for using it :)

Have you installed pyserial and avrdude?

To install avrdude just run brew install avrdude and to install pyserial, you need python installed, then you can run pip install pyserial.

https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md#3-install-pyserial

Hope it helps :)

Next time, feel free to open an issue in the Github repo as it might also help others.

EDIT: my bad, I did not read your Makefile carefully!

the problem is with:

BOARD_TAG         = mega328
# it should be
BOARD_TAG         = uno


Convert int to char[] I'm looking to convert an int value to a char array. currently I've found the following will return [number]

int num = [number]
str = String(num);
str.toCharArray(cstr,16);
Serial.println(cstr);

However, per Majenko's The Evils of Arduino Strings I feel like this code would make my Arduino's heap look like swiss cheese. Is there a better way to change an [int] into a char[n] array that avoids the String class?

itoa is the best route:

int num = 1234;
char cstr[16];
itoa(num, cstr, 10);
-> "1234"

You can read more about using it here.

If you want more control over the format of the number (and don't mind the increased PROGMEM usage) you can use sprintf (or the more secure snprintf) to format it:

sprintf(cstr, "%05d", num);
-> "01234"

Or with PROGMEM string constant:

sprintf_P(cstr, (PGM_P)F("%05d"), num);
-> "01234"

Or with more values:

sprintf_P(cstr, (PGM_P)F("%02d:%02d:%02d"), hours, minutes, seconds);
-> "03:23:11"


Grounding issues Arduino Ethernet Shield makes WS2811 LEDs flicker I have an Arduino Due with an Arduino Ethernet Shield V2 that I use to control multiple daisy-chained WS2811 LED strips.

When I turn on most of the LEDs the Arduino and attached wires seem to become an antenna, picking up fluctuations that make the LEDs flicker, by messing with the data on the WS2811 data line. Touching the data cable, touching the ethernet plug on the shield, or simply hovering my hand over the Arduino adds noise that causes flickering in the lights.

When I pull out the ethernet plug, it stops. (The Arduino continues to update the WS2811 chips, even without network connection)

The flickering is especially strong when I set the first couple of LEDs in the chain to White (biggest draw of current), while having red or green colored LEDs at the beginning causes milder flickering (even if there are LEDs set to White further back in the chain).

Some more observations:

The LED strips are powered from both sides. It doesn't seem to be a power issue.
I tried with a different Arduino Due, a different Ethernet shield, a different router and Ethernet cable, and a different power supply.
The router the Arduino is plugged into, is positioned on the same table, and powered from the same power bar as the LED/Arduino power supply.
I tried running the Arduino and the LEDs from different power supplies but that didn't help. Rather the opposite (which makes sense)
This happens no matter how long the equipment has already run or how hot it is.

Another mystery:
You might notice the lose ground cable from the LED strip connector. When I plug that into the Arduino Due, the LEDs don't get turned on at all. When I plug that ground cable into the Ethernet shield sitting on the Due, then some lights turn on wrong. No matter if Ethernet is plugged in or not (though there's a difference in the 'wrongness' of the lights when Ethernet is plugged in). Note, that the Arduino and the LED strips already share ground 1 foot away as they are both fed by the same 12V power supply.

Where are all these grounding issues coming from and how do I get rid of them? What else could I try?

I suspect that the signal driving the LED strip does not have enough voltage swing. And that ground noise/resistance is what makes the system sometimes appear to work correctly.

With 12 volt LED strips, the data signal into the WS2811 should swing at least 0.3x to 0.7x 12 volts, or below 3.6 volts (low) to above 8.4 volts (high).

The Arduino Due has output signals from 0 volts to 3.3 volts.

Which would explain the observation that if ground is connected directly between Due and LED then the Due output is never high enough to signal the LEDs.

I would try using a logic level converter between the Arduino Due output and the LED strip data input.


Is it possible to use FrSky D8R-II Plus 8ch 2.4Ghz ACCST Receiver with an arduino Uno? I'm in the process of buying a receiver and transmitter for my quad copter project. Would it be possible to use this receiver or a similar one to control the quad. I'm trying to read the signals using Pulse in. I'm inexperienced in RC and I only found one tutorial on how to do this.

I know that the receiver will have to be wired up to the analog pins on the arduino however, the receiver has an operating voltage of 3.5V-10V and an operating current of 100mA which exceeds the 40mA of the arduino board. I have seen videos of people using silar 2.4Ghz receivers on arduino Nanos without problems. Has anyone on this board done something similar and if so, can thou guide me?

I've used plenty of receivers like this with arduino.

The operating current is not really an issue; It is drawing power off of the 5v line, not the digital pins, which is capable of 100mA. In any case they usually have an extra "bat" line that you could plug in to a BEC from one of your speed controllers, and then just connect signal and ground lines to the arduino.

pulseIn works, but not ideally (especially for quadcopters). reading with pulseIn tends to have quite a bit of noise, and runs slow. Those receivers pulse around 50-60Hz, so reading those signals with pulseIn (which has to wait for the signal to finish) will take too long. I say "too long" because in all the open source quad copter programs I've looked at the sensor-read/stabilize update loop needs to run at 100 Hz or more.

What you need to use is the interrupt functionality of the AVR. That way you can detect the time between changes in state of the input pulse without causing the rest of the program to stop. This can get somewhat complicated so I'm not going to write a tutorial here. I recommend you research it yourself and ask new, specific questions here if you have any.

It doesn't magically fix everything for you though; the Uno only has 2 external interrupts. I think most arduino based quads use arduino megas or Leonardos, which have more. I know the APM 2 board has a separate chip converting those 8 single channel PPM signals into a single 8 channel PPM signal that goes into the main controller, despite the fact that it is a mega.

You can look into Aeroquad and Multiwii for inspiration. ArduPilot is open source as well but their code is messier, which makes reading it much more difficult. I don't think it is impossible to use an Uno, but it will be difficult.


How do I make a toggleable Infrared motion detection module I just got an Arduino and an Infrared motion detection module. What I tried making is, that if the module detected movement, a led would turn on, and if it detected movement again, it would turn off. So I wrote this code and tried looking online for solutions, but couldn't find it. I really don't know what to change about my code to make it work. Does anyone have solutions for this?

(Sensor value can be 0 or 1, 0 means nothing detected, 1 means something detected. After detection the value automatically goes back to 0 in a few seconds)

int Sensor = 4;
int led = 13;
bool bool1 = false;

void setup() {
pinMode(Sensor, INPUT);
pinMode(led, OUTPUT);
Serial.begin(9600);
}

void loop() {
int SensorValue = digitalRead(Sensor);

if(SensorValue == 1){
  bool1 = !bool1;
  }

if(bool1 == true){
  digitalWrite(led, HIGH);
  }
if(bool1 == false){
  digitalWrite(led, LOW);
  }
}

Consider using a state machine with 4 states.  Currently you only have 2 states.  One where "bool1" is TRUE and another when "bool1" is FALSE.  The 4 states needed are:

When the LED is OFF & the PIR is NOT-ACTIVE.
When the LED is OFF & the PIR is ACTIVE.
When the LED is ON and the PIR is ACTIVE.
When the LED is ON and the PIR is NOT-ACTIVE.

As you travel between these 4 states, you will find you only want to turn the LED ON when traveling between states 2 & 3.  And you will only want to turn the LED OFF when traveling between states 4 & 1.


SIM800C developer board "SIM not inserted" I bought this SIM800C development board (vendor unknow):

I conected it to an Arduino and put a brand new SIM card in it. This is the model of SIM I'm using:

Problem is, development board doesn't detect SIM card:

at+cfun=1,1
OK
at+cpin?
+CME ERROR: SIM not inserted
at+csmins?
+CSMINS: 0,0

This is the scenario:

6 pin SIM in a 6 pin SIM card holder.
SIM works fine in a cel phone. Send/receive voice call/sms.
Older, working SIM from various providers doesn't get detected either.
Every other non-SIM related aspect works.
No reboots, no flickering.
Board takes care of regulating voltages and signal levels.

I put an oscilloscope probe on the SIM_VDD pin (against board ground) and got this on every power-on:

Two 1.8v and two 3v pulses. That's all.

Please, note that I have no access to all SIM connexions (multi layer PCB).

How do I solve this problem?

The print on the PCB and product description at sellers site states it is GSM/GPRS board. The  module on the board comes from SIMCom. This particular SIM800 module seems to have following capabilities as per SIMCom:

Compliant to GSM phase 2/2+
GPRS multi-slot class 12/10
Quad-band 850/900/1800/1900MHz

I think at the best you can only use a 2G SIM card on this board. Any 3G/4G SIM will not work.

Thanks for those images in the problem description, it gave me relevant keywords to search.


Emulate non-standard keyboard from Arduino I want to emulate keyboard presses in an old C64 microcomputer using an Arduino.

The keyboard connection is a non-standard 20-pin port (i.e. the Arduino keyboard libraries won't be useful) which, as I understand, works as a simple matrix of switches.

Since my Arduino Mega has more than 20 general purpose I/O ports, I understand I can approach the problem by simply mapping these 20 keyboard pins to individual "digital" Arduino ports, and then programming around it, right?

Or is this too naive and I'm missing something here?

I'm new to Arduino, so any comments highly appreciated. Thank you!

Emulating a keyboard matrix is actually harder than you would at first think. It's not just a case of setting certain combinations of pins as HIGH or LOW - you need to actively monitor one side of the matrix as it sweeps across each row and control the other side depending on the buttons that are pressed or not pressed on the current row. And all that has to be done fast enough that the C64 doesn't see buttons constantly bouncing up and down.

Further, you really need all your outputs to be open drain so as not to interfere with each other or the rest of the system (depending on just how the C64 system works), and Arduinos can't do open drain natively - instead you have to emulate it by switching between INPUT and OUTPUT + LOW which adds extra latency.

If you only want access to a few of the buttons a better arrangement would be to add a small N-channel (logic level) MOSFET or an NPN BJT between the two sides of the matrix for whichever button(s) you want to control (check the schematics for which pins and which way round to connect it). Activating the transistor would then be the same as pushing the button down. It can even be in parallel to the existing button so as to not break the keyboard.


Sending >255 bytes array to arduino I am trying to send a 50x50 bitmap bytearray from my python client to arduino where it should be displayed on a screen.

I need to receive 350 bytes to have the data to show the bitmap but as soon as i initialise the array with > 255 elements it does weird things (i guess because of the memory):

When initialising the array with size 254 it does the expected:

  Transmission of 350 completed in 2.805466s (arduino) Received: 253
  elements

with size 350 I only get

  "Received: 93 elements"

How can i split the bytes i receive with the available memory and then build the bitmap accordingly or what is a better way to do it? I would like to have it transmitted via serial rather than building the qrcode in arduino (as i couldn't get the libraries required working in my setup).

My python client does basically this:

for element in qrCodeBytes:
    countElementsSent+=1
    ser.write(element)
    print("Sending " + str(element))
ser.write("$".encode()) #stop char

My arduino code is based on the popular Serial input basics guide
https://forum.arduino.cc/index.php?topic=288234.0

 const byte numChars = 254;
 byte receivedChars[numChars]; // an array to store the received data

boolean newData = false;

void setup() {
 Serial.begin(114000);
 Serial.setTimeout(10000);
 Serial.println("<Arduino is ready>");
 display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
 display.clearDisplay();
 display.display();
}

void loop() {
 recvWithEndMarker();
 showNewData();
}

void recvWithEndMarker() {
 static byte ndx = 0;
 char endMarker = '$';
 char rc;

 // if (Serial.available() > 0) {
   while (Serial.available() > 0 && newData == false) {
     rc = Serial.read();
     if (rc != endMarker) {
       receivedChars[ndx] = rc;
       ndx++;
       if (ndx >= numChars) {
         ndx = numChars - 1;
       }
     }
     else {
     receivedChars[ndx] = '$'; // terminate the string
     Serial.println("Received: " + String(ndx) + " elements");
     ndx = 0;
     newData = true;
     }
   }
}

void showNewData() {
 if (newData == true) {
 Serial.println("This just in ... ");
 display.clearDisplay();
 drawBitMap(receivedChars,50,50,0);
 display.display();
 newData = false;
 }
}

void drawBitMap(unsigned char *img, int width, int height, int position){
  if (position ==0){
   display.drawBitmap(128/2-(width/2), 64/2-(height/2), img, width, height, 1);
  } else if (position == 1){
   display.drawBitmap(128-62,1, img, width, height, 1);
  } else if (position == 2){
   display.drawBitmap(0,5, img, width, height, 1);
  }
}

You use type byte for the variable ndx. Type byte is 8 bits, so the max value is 255. The variable ndx is incremented and after 255 it continues counting from 0.


Is there a way to update Arduino uno Over The Air I have the Arduino uno with a Ethernet W5100 Shield and would like to remotely sketches.  Is there a way to update Arduino uno over the air?  If not, is there a wired network arduino solution that will allow update over the air.

I've done this on the esp8266 using there tools but I can't find one for the Uno.

Thanks

Not with WiFi, nor with Ethernet. People have managed it with Bluetooth, but only because it can create a transparent serial bridge. The bootloader only talks serial, so you have to use something that is serial to program it.

The only possible way is to use another WiFi (or Ethernet) device, such as the ESP8266, to act as a serial bridge to connect the Arduino's serial port (and reset signal) to your computer over WiFi. A bit of a waste of an ESP8266 since that is then the sole task it would have (unless you craft a far more complex sketch for the ESP8266 to allow it to do other things as well).


Attiny85 SoftwareSerial not working on battery power I have a very small test project running on an Attiny85 (set to internal 8MHz).

Everything works when powering the circuit from an Arduino (3.3 or 5.0 volt). But when changing the  power to a 18650 battery with a voltage of around 4.0v the Attiny85 still works, because the LED blinks, but nothing is coming through via the UART. What could be the reason for this?

#include <SendOnlySoftwareSerial.h>
#define PHOTO_RESISTOR_PIN A1
#define UART_TX_PIN 0
#define LED_PIN 1

SendOnlySoftwareSerial esp(UART_TX_PIN);

void setup() {
  esp.begin(9600);
  pinMode(PHOTO_RESISTOR_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  pinMode(UART_TX_PIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_PIN, HIGH);
  int light = analogRead(PHOTO_RESISTOR_PIN);
  esp.println(light);
  delay(1000);
  digitalWrite(LED_PIN, LOW);
  delay(1000);
}

Unless you connect the ground of your ATTiny to the ground of your USB UART interface there is no circuit for the electrons to flow around.

It works when powered from the computer because everything shared the same ground connection.


Power RFID module using GPIO I am building an ESP8266 device that uses RFID but need to conserve battery power.

The ESP is a Wemos D1 Mini and the RFID module is a RC522 (still waiting for it to arrive), which needs 3.3 V. I'm powering the ESP with a battery shield and 3.3 V.

But I don't want to connect the RFID module directly to the battery shield because it will be sucking voltage constantly. Instead, I want to be able to control its power using the ESP.

So I thought the easiest would be simply to connect the RC522's 3v3 line to one of the ESP's available GPIO pins, set it to output, and when I need  RFID, set the GPIO pin high, to turn on the RFID module.

Is this an acceptable solution, or do I need to wire in a transistor and capacitor somewhere?

No, this is not an acceptable solution.  The RC522 needs in excess of 100mA to operate, and an ESP8266's GPIO pin can only supply 12mA maximum.  You will damage the ESP8266.

You need to use a P-channel MOSFET with the gate pulled HIGH as a high side switch.

simulate this circuit – Schematic created using CircuitLab

Set the GPIO to LOW to turn on the MOSFET. Set it HIGH or to INPUT to turn off the MOSFET.

Note 1: Set the communication IO pins to INPUT before powering off otherwise they could back-power the target device through the ESD diodes in the IO pins.


Multiple peripherals using SPI with a Mega I am using a Mega 2560 and 2 x AD9833 programmable waveform generators.
The AD9833's use a SPI protocol and I have used vwlowen's code as a jumping off point (I'm not usng the display just the generators). I added a channel variable to select the slave device.
It all works fine until I try to add a second AD9833. I saw this post about more than 1 peripheral using SPI & a Mega, that says I can use any pin for slave selection (SS) but the following code only ever works if I use pin 53. The upshot if which is that I can send the same data to both i.e. both share the same SS pin as long as that pin is 53. Any other SS pin selection is ignored by the devices. I tried pin 49 for both & no change, I''ve tried 53 & 49 yet only the device on 53 changes.
So what's going on here? What's so special about pin 53 that it cant be replicated by another output pin?
/*
Amended code for AD9833 Waveform Module originally from vwlowen.co.uk
Common SPI terminology & pinout on AD9833
MOSI - DATA
SCLK - CLK
SS   - FSYNC
MISO - not implemented i.e. ther is no MISO pin on the AS9833
*/

#include <SPI.h>

const int SINE     = 0x2000;                // Define AD9833's waveform register value.
const int SQUARE   = 0x2028;                // When we update the frequency, we need to
const int TRIANGLE = 0x2002;                // define the waveform when we end writing.

const float refFreq = 25000000.0;           // On-board crystal reference frequency

const int FSYNCA = 53;                       // Standard SPI pins for the AD9833 waveform generator.
//const int FSYNCB = 49;
const int CLK    = 52;                       // CLK and DATA pins.
const int DATA   = 51;

unsigned long freq = 1000;                   // Set initial frequency.

void setup() {

  pinMode(FSYNCA, OUTPUT);
  // pinMode(FSYNCB, OUTPUT);

  SPI.begin();
  SPI.setDataMode(SPI_MODE2);
  delay(50);

  AD9833reset();                                   // Reset AD9833 module after power-up.
  delay(50);
  AD9833setFrequency(freq, SQUARE, FSYNCA);        // Set the frequency and Sine Wave output
 // AD9833setFrequency(freq, SINE, FSYNCB);

}

void loop() {

// TODO: PC control via USB

}

// AD9833 documentation advises a 'Reset' on first applying power.
void AD9833reset() {
  WriteRegister(0x100, FSYNCA);   // Write '1' to AD9833 Control register bit D8.
  delay(10);
 // WriteRegister(0x100, FSYNCB);
 // delay(10);
}

// Set the frequency and waveform registers in the AD9833.
void AD9833setFrequency(long frequency, int Waveform, int channel) {

  long FreqWord = (frequency * pow(2, 28)) / refFreq;

  int MSB = (int)((FreqWord & 0xFFFC000) >> 14);    //Only lower 14 bits are used for data
  int LSB = (int)(FreqWord & 0x3FFF);

  //Set control bits 15 ande 14 to 0 and 1, respectively, for frequency register 0
  LSB |= 0x4000;
  MSB |= 0x4000;

  WriteRegister(0x2100, channel);
  WriteRegister(LSB, channel);                  // Write lower 16 bits to AD9833 registers
  WriteRegister(MSB, channel);                  // Write upper 16 bits to AD9833 registers.
  WriteRegister(0xC000, channel);               // Phase register
  WriteRegister(Waveform, channel);             // Exit & Reset to SINE, SQUARE or TRIANGLE

}

void WriteRegister(int dat, int channel) {

  digitalWrite(channel, LOW);         // Set FSYNC low before writing to AD9833 registers
  delayMicroseconds(10);              // Give AD9833 time to get ready to receive data.

  SPI.transfer(highByte(dat));        // Each AD9833 register is 32 bits wide and each 16
  SPI.transfer(lowByte(dat));         // bits has to be transferred as 2 x 8-bit bytes.

  digitalWrite(channel, HIGH);        //Write done. Set FSYNC high
}

What's so special about pin 53

Pin 53 is the slave select pin of the SPI peripheral. As such it has a bearing on how the SPI peripheral operates.
It is intimately tied to the master/slave operation in that when it's an input SPI works in slave mode, and when it's an output it runs in master mode.
So to use SPI in master mode, whether you use pin 53 or not, it must be in OUTPUT for SPI to work at all.
There is nothing much wrong with your methodology, but one thing is missing: the initial state of the chip select pins.
You should always start with all chip select pins disabled (i.e., HIGH) rather than in an unknown (probably low - I'd have to check the datasheet) state - the exception might be pin 53 which SPI might itself set HIGH for you.
So if you add:
digitalWrite(FSYNCA, HIGH);
digitalWrite(FSYNCB, HIGH);

right after setting the pinMode for your pins and still use both pins 53 and 49 then it should work.


What is the advantage of using a motor shield if I want to use a stepper motor? I know that it is possible to connect a stepper motor directly to an arduino (as displayed here). I know that another option is to use a motor shield (for example the Arduino Motor Shield or the Adafruit Motor Shield).

What I would like to know: What are the actual advantages of using a motor shield?

Is it just a question of convenience? Or does a motor shield do something that could not easily performed without a shield? Does it allow me to connect more motors than I could connect directly without a shield (power supply comes to mind)?

The example you linked to isn't actually connecting the Arduino directly to a stepper motor. It's going via a ULN2003A driver. That's a very common Darlington transistor array, which basically just lets you use a small current to switch a larger load.

That's necessary because the Arduino pins can't safely source enough current to drive the stepper motor directly. It might work for a while, but it would damage your Arduino sooner or later.

Motor shields usually have a similar driver in them, but can also provide additional functionality which you might find useful. For example, the Adafruit shield you linked to is controlled by the I2C bus, and has its own on-board PWM. That means you can control several motors without needing any extra output pins on your Arduino.

In short, motor shields aren't necessary. They can be helpful though, especially if you aren't familiar with the underlying electronics, or you don't want to build it yourself.


1.7MHz Square wave generator const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

I got it from here, look down to the answers

This program supposed to generate a square-wave of frequency around 1.7MHz but it is not working for me. I have tried the simulation on Proteus 8 and there is no output. Only one error shows during the compilation which is the 'loop' function is missing, I have added one and still there is no output. Please somebody help me.

In the setup there is some settings for timer2, but no change of prescaller, so the timer stays stopped.

Obviously it was started by calling soundBuzzer() somewhere in code. But this function name is now kinda misleading. Just set prescaller in the setup and it should be working.


Using an external header file I have a project that is part of a larger repository, and shares header files with non-Arduino C programs.

I know that it's possible to use these headers by copying them to the libraries folder, or the sketch folder, but I would rather use them with a relative path (which seems to not work), so I can avoid copying files around for every repository clone or update.

Is there a solution that doesn't involve moving/copying the header file?

EDIT:
Although there is no full solution for this question,
I have since found that using the PlatformIO
IDE instead solves the problem.

You can use header files with an absolute name, like:

#include "c:\Temp\x.h"

Another way that might help is to make the include path like:

#include "q:\x.h"

And use Windows to map driver letter Q to the path you need.


Connector for I2C sensor Im about to develop some home automation. It should be possible to connect new sensors to the main computer. Thats a Arduino.

What can be used as a connector for the I2C sensors? It should be customer friendly. So something like RJ11 or USB. What can be used for that?

Is it possible to send data wirelessly from a I2C sensor?

Regards

What can be used as a connector for the I2C sensors? It should be customer friendly. So something like RJ11 or USB. What can be used for that?

Almost anything you like. Whatever is easy to get hold of and use. You only need 4 wires, and they are all low voltage, so nothing too fancy is needed.

  Is it possible to send data wirelessly from a I2C sensor?

No. But you can connect the I2C sensor to an Arduino then use that with a wireless interface of some form to send the data wirelessly.

One thing for you to know though:

I2C is not suitable for long distance communications. A few inches to a foot or so is about the limit. Anything longer and you will start running into communication problems. For longer distance communications you need to use a more reliable protocol.


ESP8266 (connected to Arduino) only works when plugged into USB power The Wi-Fi connects when the Arduino is powered by my computer and a serial console is connected, but not if I plug into an outlet.

UPDATE

It seems this is a power issue. I am powering the esp8266 from the Redboard 3.3v line that is only rated for 150mA. I will be switching to the 5v line with a 1A regulator.

I also switched to 9600 baud for communicating with the esp8266, added retries around all of esp8266 commands, and added reconnect logic in case the esp8266 reboots. With the changes, it works okay even with the underpowered 150mA line.

It's still a mystery to me why it works so well when connected to my Macbook.

It sounds like your power supply is inadequate to the task.

The ESP8266 is notoriously finicky about having a noise free power supply capable of delivering a lot of instantaneous power. If you are using a wallwart style supply it should promise at least 1A and more is better. Even though the actual use is more like 250 mA.


Power management circuit i'd like to have a esp-01 powered on and controlled with a push button only.
so imagine the device is off, the user press the momentary push button. in the setup the esp8266 turn on a mosfet or something similar to give himself power using another line. the user release the button and the device is on. i want to be able to understand long button press and double press and similar stuff too. even when device is already powered on. so i need to have a pin attached to the button somehow
this is what i have till now, thanks to a very skillfull friend of mine

the vcc is 5 v and pin tollerance is only 3v

it must be completely off when not pressed for long battery duration

You need to isolate your button from the logic output using a diode. For example:

simulate this circuit – Schematic created using CircuitLab

In this method M1's gate is normally pulled up by R2. It can either be pulled down by M2 (switched by the "HOLD" signal) or by the switch via D1.

The BTN input is pulled up by R1, and can be pulled down by the switch. M2 can't pull it down because the diode is reverse biased and blocks current trying to flow from BTN via M2 to ground.

R3 is just a pull-down on the gate of M2 to keep it off when HOLD is floating (the power is off).

If you need to interface the 5V "BTN" signal with a lower voltage-tolerant input pin just use a couple of resistors as a voltage divider to reduce the voltage to within the proper levels for the pin.


What is the use of decoupling capacitor? I dont understand what does the word "decoupling" mean? Where and Why it is used? Can anyone give me a brief idea>?

Quite simply put, it's a little reservoir of energy for a chip or other device to dip into when it needs to get a little extra power.

In Electronics nothing happens instantly.  When a chip needs more power it has to get it from the power source.  The power source then has to respond to that by providing more energy, and that then has to make its way down the wires or traces to where it needs to be.

By placing a small capacitor near where the power is consumed the capacitor can respond to that call for more power much faster than the power supply.


How to drive motors and use an ultrasonic sensor simultaneously? I have a L298 motor driver, which I coded with an Arduino Nano.
The code is very simple at the moment:

// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;
void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  Motors_FWD_PWM_Initialize();

  // accelerate from zero to maximum speed
  for (int i = 0; i < 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i >= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  MotorsOff();
}
void loop()
{
  demoTwo();
  delay(1000);
}

void Motors_FWD_PWM_Initialize()
{
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
}

void MotorsOff()
{
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}

Currently I have two questions:

Q1: I have an ultrasonic sensor, how can I write the code so that the motors work and 'keep an eye out' with the ultrasonic sensor simultaneously? i.e. When a certain proximity is reached I would like the robot to stop.

Q2: Also I would like my robot to 'rove' around. How can I make it so? I was thinking having a number of subroutines, and making the arduino randomly choose one.

For the first question, you could simply implement an interrupt routine to regularly check the status of your sensor and when it achieves the desired threshold it triggers the action to stop the motor.

You can achieve this by setting timer1. There is a library here for example, where you set the period to execute a desired function, when some distance is detected you just stop the motors.

The second question could be done exactly like you said. Say you have some paths saved in memory, you can just create some options for them and execute whenever you want using switch/case command.

http://playground.arduino.cc/code/timer1


Programming Arduino in Pascal? My question is simple: there is any Pascal or Pascal-class (FPC, Delphi, mikroPascal) programming language for Arduino?

Preferably (I hope I don't ask too much) that language should not be older than 10 years.

Update:
Let's not start a flame war about "why the xxx programming language is so much better Pascal" and keep focus on the core of this question. I know that Pascal has it flaws (nothing its perfect, right?). I accept them and I still want to use it :)
Many thanks.

Not Pascal, but Ada, which is much less restrictive than Pascal while enjoying the same advantages over low-level programming, and much more actively supported with language revisions as recently as 2012 and the formally provable SPARK language, for when you need your code to work.

Any processor which gcc supports can potentially support Ada, whose Gnat compiler is fully part of gcc.

That's not the whole story because you also need run-time system support for Ada's facilities, but for the Arduino's AVR processor there is a well established environment in the form of the AVR-Ada project.

It generates nice tight little executables, you'll be amazed how much less space simple Gnat executables take compared to Arduino ones - unless you've already made the same comparison between Arduino and C ... which after all uses the same gcc compiler.

For ARM-based Arduinos (Arduino Due at least) the same is possible, though the support is newer and possibly less well established, see the Cortex-GNAT project.

Leaving the Arduino, Ada has also been demonstrated on the MSP430 processor - my own project, sadly neglected at the moment.


How do I hook up a 3V device to a 74AHCT125 (Quad Level-Shifter)? I have this level shifter that I'm trying to feed a 5V power source and then hook up a 3V device.

I've got the 5V source hooked up fine (on the top pinouts), but having trouble figuring what the "power out" would be that's 3V.

Here's the data sheet.

It's not a level shifter. It's a buffer chip that can be used to level shift in one direction only.

It is good for shifting from a low voltage logic signal (3.3v, say) up to a 5V logic signal. It can't shift down from 5V to 3.3V.

Basically it works by having a fixed voltage that it considers to be a logic HIGH, and any voltage above that will be output as 5V. Any voltage below will be output as 0V.  This is the "TTL Logic Level" specification in the datasheet.

So if you have a sensor that emits a 3V logic signal the HIGH logic value will be above its fixed threshold and will trigger a 5V HIGH on the output.

In contrast "CMOS" logic uses a percentage of the supply voltage to set the thresholds (usually > 0.6 x Vcc), and a 3V signal is less than that (3.3V is about bang on it, so is "iffy"), so won't work (or not reliably).


Determining which section of code uses the most flash I'm running into the 32k flash ceiling of my 328p. The code is pretty compact but I need help making it smaller.

Is there an analysis tool (part of avr?) that can tell me which functions take up the most space?  Obviously looking at the source code won't help because I don't know how the compiler decides to reorganize things.

I've moved strings to PROGMEM, but I'm still hitting the ceiling.

What are some tips for space saving?
What are some ways of seeing what's taking up the most space?

Moving strings to PROGMEM will only exacerbate the problem, since PROGMEM is the 32k flash.

You can easily get your "symbol table" from the compiled .elf file by using avr-objdump -t <.elf file>.

It results in a list something like this:

... scrolls past ...
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
00800110 g       .bss   00000000 __bss_start
000008a2 g     F .text  00000022 main
00000126  w      .text  00000000 __vector_4
00000000  w      *ABS*  00000000 __heap_end
00000126  w      .text  00000000 __vector_9
000003ae g     F .text  000000d0 delay
00000126  w      .text  00000000 __vector_2
00000126  w      .text  00000000 __vector_21
00000126  w      .text  00000000 __vector_15
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
008001c3 g       .stab  00000000 __heap_start
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
000008ff  w      *ABS*  00000000 __stack
0000008d g     O .text  0000000a port_to_input_PGM
00800110 g       .data  00000000 _edata
008001c3 g       .stab  00000000 _end
00000126  w      .text  00000000 __vector_8
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000a08  w      .text  00000000 exit
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
00000126  w      .text  00000000 __vector_14
00000126  w      .text  00000000 __vector_10
000002a8 g     F .text  00000090 __vector_16
00800100 g       .data  00000000 __data_start
00000480 g     F .text  00000076 __vector_18
00000126  w      .text  00000000 __vector_20
00000108 g       .text  00000000 __do_global_ctors
... etc ...

The lines you are interested in are .text sections.  The first big number is the HEX location in memory.  The second one is the important one - that is the size.

You can see from that snippet that the function delay is located at address 0x3ae and is 0xd0 bytes in size.

If you're on Unix or OSX you can employ the more advanced searching tools that are at your disposal.  For instance, to just list the "global" .text entries:

$ avr-objdump -t <elf file> | grep '\.text' | grep ' g '

Which for my test program results in:

00000079 g     O .text  0000000a port_to_mode_PGM
00000918 g     F .text  00000040 _ZN5Print7printlnEv
00000a00 g       .text  00000000 __tablejump__
000006c2 g     F .text  00000040 _ZN14HardwareSerial4peekEv
000008c4 g     F .text  00000054 _ZN5Print5writeEPKhj
000000d4 g       .text  00000000 __trampolines_start
00000a0c g       .text  00000000 _etext
000006a0 g     F .text  00000022 _ZN14HardwareSerial9availableEv
0000012a g     F .text  0000002a loop
00000774 g     F .text  00000080 _ZN14HardwareSerial5writeEh
00000126 g       .text  00000000 __bad_interrupt
000000d4 g       .text  00000000 __trampolines_end
00000200 g     F .text  000000a8 digitalWrite
00000592 g     F .text  0000010e _ZN14HardwareSerial5beginEm
00000182 g     F .text  0000007e pinMode
00000097 g     O .text  00000014 digital_pin_to_port_PGM
000000d6 g       .text  00000000 __dtors_end
00000754 g     F .text  00000020 _ZN14HardwareSerial5flushEv
0000051c g     F .text  00000076 __vector_19
00000990 g     F .text  00000026 _ZN5Print7printlnEPKc
000000f8 g       .text  00000000 __do_clear_bss
000000ab g     O .text  00000014 digital_pin_to_bit_mask_PGM
00000000 g       .text  00000000 __vectors
000009fc g       .text  00000000 __tablejump2__
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
000008a2 g     F .text  00000022 main
000003ae g     F .text  000000d0 delay
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
0000008d g     O .text  0000000a port_to_input_PGM
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
000002a8 g     F .text  00000090 __vector_16
00000480 g     F .text  00000076 __vector_18
00000108 g       .text  00000000 __do_global_ctors

From that I can see that the function _ZN14HardwareSerial5beginEm is the biggest and takes up 0x10e bytes.  That strange named function is a "C++ Munged" name.  It actually corresponds to HardwareSerial::begin() and is the parent class name for Serial.begin().


Can I power an NodeMCU trough VIN providing 5v I have a spb 8266 board, an ESP-12E NodeMCU.
I broke my micro USB.

There's this piece of information but my case is unclear:

Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?

(The board only has 3.3V and no 5V)

Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?

Yes. That is the pin's purpose.  You can use any voltage from about 4.5V up to 20V, although higher voltages will cause more heat from the on-board 3.3V regulator.

VIN just connects to the 5V of the USB.


Restoring all fuse bits on AtMega328P-PU I'm worked with Low Fuse bits in AVRDUDEPROG 3.3. Fuses was non-inverted. And by mistake I enabled SUT1 and SUT0, when SUT0 was enabled. And when I programmed avr,
it shows me error that avrdude.exe: initialization failed, rc=-1. I have read I can restore it with Avr Fuse Doctor, but I can't buy or make with pcb. Can I recover avr with:

#include <avr/io.h>

int main(void) {
    DDRB = 0xFF;
    while(1) {
        PORTB ^= 0xFF;
    }
}

and load it to another avr and connect it to broken avr?

Can I make doctor on breadboard or Can I do it with usbasp/isp?

Can I load a new bootloader in it?

The following is from:
https://www.allaboutcircuits.com/projects/atmega328p-fuse-bits-and-an-external-crystal-oscillator/

"The two bits to be avoided unless you are absolutely certain you know what you are doing are bit7, the RSTDISBL (external reset disable) bit and bit 5, the SPIEN (Serial Peripheral Interface Enable) bit. Disabling either one is often the cause for "bricked" Atmel µCs; "leave them alone" is good advice."

According to the article SUT0 and SUT1 are clock start up time related bits. It doesn't seem as though it is necessary to use anything special to change them.

You will find the information at the website very usefu. I know I have.

The High Voltage (other names too) programmer you have mentioned should not be necessary if you only changed the SUT0 and SUT1 fuses.

HOWEVER, if you did change the SPIEN or RSTDISBL fuses, you should either get one of the special programmers or just purchase another 328P microprocessor.

If you search the internet for "AVR High Voltage programmer" you will find many ideas for how to build one.

This link :https://electronics.stackexchange.com/questions/33/arduino-as-avr-programmer/71
provides good information.


Explanantion of Addressing I'm new Arduino user and I'm trying out a SPI protocol to interface a SRAM, specifically, the 23LCV512.

I have found the instructables steps to interface a SRAM using the SPI bus on an Arduino UNO very helpful (http://www.instructables.com/id/Interface-an-SRAM-bus-to-your-arduino/), but there is one  point that i would like some explanation for:

In the mem_demo.ino and other various SPI.h code, I have seen variations of the following, however I do not understand why you would have to do this? I think here that we are communicating the right shifting of an input address 16 places along with 8 bits of '1'.

SPI.transfer((uint8_t)(address >> 16) & 0xff);
SPI.transfer((uint8_t)(address >> 8) & 0xff);
SPI.transfer((uint8_t)address);

Commenting these lines out for the write did not effect the writing to the SRAM, but reading caused it to return mostly 0's.

I really appreciate any help iIget, I do not have a lot of experience with memory addresses and electronics, thank you.

It is actually slightly confusing owing to the (actually redundant) & 0xff in there.

What is happening is first the address is right-shifted so as to place the byte of interest at that moment in the lowest 8-bits (address >> 16 for instance to get bits 16-23 moved to bits 0-7) and then the lowest 8 bits are masked off by ANDing them with 0b11111111 (0xFF). This removes any bits that are above the 8 bits we are interested in - however the fact that it's cast to uint8_t and also passed to a function that expects uint8_t makes that masking redundant. Any bits above the first 8 are discarded anyway.

So to take an example address of, say, 100,000 (which is 0x186A0 in hex) and run those three commands on it, we end up with:

SPI.transfer((uint8_t)(address >> 16) & 0xff);

0x186A0 >> 16 = 0x00001
0x00001 & 0xFF = 0x01

SPI.transfer((uint8_t)(address >> 8) & 0xff);

0x186A0 >> 8 = 0x00186
0x00186 & 0xFF = 0x86

SPI.transfer((uint8_t)address);

(uint8_t)0x186A0 = 0xA0

The end result as you can see is three SPI transfers each sending a single byte:

0x01, 0x86, 0xA0

And that corresponds to the protocol for that chip, which is basically:

<Command>, <Address H>, <Address M>, <Address L>, <Data>...

For instance:

0x02, 0x01, 0x86, 0xA0, 0x69

You send the "WRITE" command, send the three bytes of the address you want to write to, then follow that with the data to write. Or you send the READ command, send the three bytes of the address you want to read from, then the data is returned to you a byte at a time.


Confusion around LEDs on a breadboard I am just starting out with an Arduino Diecimila and am playing around with LEDs, and am confused by why some circuits result in an LED not lighting up.

Successful Scenarios:

Yellow LED from pin13 to 16B on the breadboard, Green LED from 16A to GND. This works both LEDS light up.
Yellow LED from pin13 to 16A on the breadboard. Wire from 16E to 14E. Green LED from 14A to GND. This works and both LEDs light up.

Failed Scenarios:

Yellow LED from pin13 to 16A. Green LED from 16E to 14E. Yellow LED from 14A to GND. No LEDs light up. I would assume that all the LEDS are in series, and all 3 should light up, I assumed this would be exactly the same as my second successful scenario where the LED is acting the same as the wire.
Yellow LED from pin13 to 16A. Wire from 16E to 14E. Yellow LED from 15A to GND. Green LED from 16B to 14B. Here I have both Yellow LEDS lit, but the Green LED is not lit. I was expecting that the Green LED would have been in parallel and should have lit up.

In both failed scenarios I have swapped around the LEDs and proved that all the LEDs function.

There must be some basic concept that I am not understanding with the circuits, any ideas?

Scenario 1 fails because yellow and green LEDs have forward voltages of about 2V each, so when putting 3 in series, you need a forward voltage to light them that exceeds the 5V available.

Scenario 2 fails because the wire you have in parallel with the LED provides a path with a very low voltage drop (close to 0V), so the path through the LED with a ~2V voltage drop is not taken (and if you remove the wire, the same reasoning as in scenario 1 applies, so nothing would work).

BTW, you should never run LEDs without a series resistor, as your experiments will surely demonstrate to you soon ;-)


Passing array to library function I'm trying to pass an array to a library (written in c++) but the error:

undefined reference to `MyLib::arrayTest(int*)'
collect2: error: ld returned 1 exit status
Error compiling.

Is being produced.

My Code Is As Follows:

Testing.ino:

MyLib test = MyLib(5,4,6);

void setup(){
    int arr[10];

    test.arrayTest(arr);

    Serial.println(arr[0]);
}

MyLib.h:

class MyLib {
    public:
        MyLib(int x, int y, int z);

        void arrayTest(int* n);

MyLib.cpp:

void arrayTest(int* n){
    n[0] = 15;
}

Any help is greatly appreciated :)

This function:

void arrayTest(int* n){
    n[0] = 15;
}

is lacking the class qualifier:

void MyLib::arrayTest(int* n){
    n[0] = 15;
}


I got this ILI9341 *i 'm not sure * from ebay and i cant manage to use any librarys I have Arduino Uno R3 i can't mange to upload code for the display .
I tried to use librays from this  http://www.buydisplay.com/default/arduino-2-4-inch-tft-lcd-touch-shield-li9341-library-for-mega-due-uno

After uploading

In file included from C:\Users\radum\Downloads\Libraries-Examples_RTP_for-2.4-2.6-2.8-3.2-inch (1)\Libraries-Examples_RTP_for-2.4-2.6-2.8-3.2-inch\Examples_RTP-Software-SPI_2.4inch-3.2inch\Graphic_Test\Graphic_Test.ino:8:0:

C:\Users\radum\Documents\Arduino\libraries\UTFT/UTFT.h:200:42: fatal error: hardware/avr/HW_AVR_defines.h: No such file or directory

#include "hardware/avr/HW_AVR_defines.h"

compilation terminated.

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

But the file exists in the specified folder .
What should i do?

Do a google search for MCUFriend LCD library. I believe you want this library


Serial Enable Maxim RS485 Pin If I want to use a MAXIM 485 for a RS485 communication, is there any option to include the Control DE and RE' pin in a natural manner in the code, instead changing the control pin everytime I made a Serial.print()?

Should I overload the HardwareSerial object in order to add those pin operations everytime?

No, there isn't - you have to do it manually. And don't forget to flush.

You could inherit HardwareSerial if you really wanted - or just write a couple of functions to do the sending and controlling of the DE pin.


Powering a water pump with nodemcu I want to use a nodemcu to water my plants. I connected a pump with a 2N2222 transistor (I know i should add a diode and a pull down on the gate). The pump is DSL370 and when it is off i measure 4.4V on the Vin pin while using a 2A charger connected to the USB port. When the pump is active, the vin voltage drops to 4.1V and the LCD becomes hard to read. I measured the current the pump uses and it is 300mA. What is the reason for the voltage drop? I thought the charger should be able to handle it.

Your charger may be able to handle 300mA, but you're pulling that power through your Arduino and that isn't good.  The pump should have a separate power supply, or at least be powered in parallel with the Arduino.  Don't pull power for a motor from the Vin pin unless you just want to destroy the Arduino.


My car only moves when it is plugged directly into both my pc and battery pack? i built a car that works with four motors,one motor driver(specifically the l293d),the arduino and the battery pack with four AA-Batteries. The motors work fine though, but they only work when it is connected to the laptop and the battery pack.I've also removed the METAL insulation from the copper wire and now it is copper.Sadly i have also connected the two poles together and there was some lightning but no fire thankfully(by accident of course).if anyone else had the same issues and fixed them please contact me.
Thank you very much stranger.

The best thing you can do is post a schematic, not a frizzy thing along with a picture of the parts that you modified and links to all of the other parts. You state: "orange arduino led is flashing and making a weird sound" How does a LED make a sound, they are not designed to. The best thing you can do for yourself is read the Arduino cookbook and do some online tutorials on basic electronics and the arduino.


Power maximum output power for each pin A have Arduino Mega 2560. I found in the spec that the maximum output current for each I/O pin is 40 mA.

Can i use 40 IO in parallel? That's mean 40*40ma*5 volt = 8000 mw = 8 watt.

What about the heat?!

There are also limits on the total power of groups of pins,

  The sum of all IOH, for ports J0-J7, G2, A0-A7 should not exceed
  200mA.
  The sum of all IOH, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
  The sum of all IOH, for ports G3-G4, B0-B7, H0-H7 should not exceed 200mA.
  The sum of all IOH, for ports E0-E7, G5 should not exceed 100mA.
  The sum of all IOH, for ports F0-F7, K0-K7 should not exceed 100mA.

So you are already limited to 800mA.

Secondly, you have to be careful to change all the pins at exactly the same time. Otherwise some pins will be low, and others high creating effectively a dead short. Or if you make sure the pins are inputs before changing, some pins will be on sooner, and those pins will then for a short period, handle all the current, and thus exceeding their limit for a brief moment. Which isn't that bad, but still not ideal.

So definitely don't use digitalWrite to change all the pins, one after the other.


Controlling Dynamixel Ax-12 With Arduino Mega I want to controll two dynamixel ax-12 servos using a arduino mega and I don`t know the commands that I should send to them using Serial.

Could anyone help me with this?
(And please keep in mind that I don`t want any more hardware. Just arduino board)

With Dynamixel library you can use servo this easily:
#include <DynamixelSerial.h>

void setup(){
   Dynamixel.begin(1000000,2);  // Inicialize the servo at 1Mbps and Pin Control 2
}

void loop(){
    Dynamixel.move(1,0);
    delay(2000);
    Dynamixel.move(1,500);
    delay(2000);
    Dynamixel.move(1,1000);
    delay(2000);
}

Example moves servo and makes pauses of 2 sec.
Installation is easy:

Installation:
Copy the files from DynamixeSerial to your IDE libraries folder.

DynamixelSerial folder can be found here: https://sourceforge.net/projects/dynamixelforarduino/files/?source=navbar


giving delay function to output I want my arduino to give the output at a specified delay .The delay is calculated from a polynomial equation.

unsigned long t=40*Vin*Vin-760*Vin+4320;
delay(t);
digitalWrite(ledPin,HIGH);

but while doing this i was unable to get the delay accurately while observing it through oscilloscope??

I suggest you look into using a hardware timer rather than using delay(), I suspect it will give you more accurate timing.

Timer configuration is not as straight forwards as using delay - they don't work in milliseconds or microseconds, but instead in multiples of clock cycles, which (I find) makes configuring them a little difficult to understand, but it is possible to set the interval of a timer within its own interrupt routine.

Another advantage to using timers is that your code can do other things whilst waiting between interrupts.

Have a read here for more information and simple examples:
http://playground.arduino.cc/code/timer1
or just Google "Arduino timers" for other examples and explanations.


Serial.println(): Where is the text printed? When I used Serial.println() in the code I naively believed I would see the characters that I sent displayed on that little black area just under the interface (just like a terminal).

#include <Servo.h>

int moveServo;

Servo myservo;

void setup()
{
  myservo.attach(0);
  Serial.println("      Hello Earth");
  Serial.println();
}

void loop() {
}

Can someone tell me just where Hello Earth would be displayed?

The IDE on your computer has a menu item under the tools menu called "Serial Monitor." On my Mac, at least, it is indeed a black area under the source editor for the current sketch.

It won't work unless you call the Serial.begin() function in your setup method before the first Serial.print()/println()/write() function call.

Something like this:

//Set up the serial port @ 9600 baud for display back to the computer
Serial.begin(9600);
delay(25);
Serial.println("Hello world!":);


ESP8266 + DHT11 AWS IOT Thing not updating thing shadow - was working before I was able to get this working - https://www.youtube.com/watch?v=8hpro1olRK0 - send an SMS and email of temperature and humidity data from AWS IOT using esp8266 + dht11 but all of a sudden it stopped updating the shadow.

Here is the code

#include <ESP8266WiFi.h>
#include <DHT11.h>
#include <AmazonIOTClient.h>
#include <ESP8266AWSImplementations.h>

Esp8266HttpClient httpClient;
Esp8266DateTimeProvider dateTimeProvider;

AmazonIOTClient iotClient;
ActionError actionError;

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

// Pin 2 will be used to read sensor data
int pin = 2;

// Initializing the sensor
DHT11 dht11(pin);

//Function to convert Celsius to Fahrenheit
double Fahrenheit(double celsius) {
  return ((celsius * 9 / 5) + 32);
}

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

  // Connecting to Wi-Fi
  WiFi.mode(WIFI_STA);
  Serial.println();
  Serial.println();
  Serial.println("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  iotClient.setAWSRegion("us-west-2");
  iotClient.setAWSEndpoint("amazonaws.com");
  iotClient.setAWSDomain("al1x5kb4rzh0x.iot.us-west-2.amazonaws.com");
  iotClient.setAWSPath("$aws/things/esp8266/shadow/update/accepted");
  iotClient.setAWSKeyID("AKIAJJQ6ASLIDIPBE4PQ");
  iotClient.setAWSSecretKey("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");
  iotClient.setHttpClient(&httpClient);
  iotClient.setDateTimeProvider(&dateTimeProvider);
}

void loop() {
  int err;
  float temp, humi;

//Reading the sensor data
  if ((err = dht11.read(humi, temp)) == 0) {
    Serial.print(" temperature:");
    Serial.print(temp);
    Serial.print(" humidity:");
    Serial.print(humi);
    Serial.println();
  } else {
    Serial.println();
    Serial.print(" Error No :");
    Serial.print(err);
    Serial.println();

  }
// Converting the float data to char arrays
  char sTemp[10], sHumi[10];
  dtostrf(humi, 6, 2, sHumi);
  dtostrf(temp, 6, 2, sTemp);

// Creating the thing shadow to be sent to aws iot
  char shadow[100];
  strcpy(shadow, "{\"state\":{\"reported\": {\"Humidity\":");
  strcat(shadow, sHumi);
  strcat(shadow, ", \"Temperature\":");
  strcat(shadow, sTemp);
  strcat(shadow, "}}}");
  Serial.print(shadow);

  char* result = iotClient.update_shadow(shadow, actionError);
  Serial.print(result);

  delay(60000);
}

Output as expected

Connecting to
NETGEAR53
.........
WiFi connected
 temperature:31.00 humidity:32.00
{"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
443
POST $aws/things/esp8266/shadow/update/accepted HTTP/1.1
Content-Type: application/json
Connection: close
Content-Length: 65
Host: al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
x-amz-content-sha256: 923ed1ae613a9e14b45e4d080b092daf5cf61118041dc5225956299d5b0f8d49
x-amz-date: 20180323T034259Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIAJJQ6ASLIDIPBE4PQ/20180323/us-west-2/iotdata/aws4_request,SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date,Signature=a10f0969043e609743412478567c10290b8c000185f2824e4a9cf07bb96cf279

{"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}

I was facing a similar problem: trying to update a thing's shadow on AWS IoT with no success. After some research, I found out that I was using an outdated library. In this question they advise to use heskew's aws-sdk-arduino, on iot-get-shadow-and-cleanup branch:

https://github.com/heskew/aws-sdk-arduino/tree/iot-get-shadow-and-cleanup.

Additionally, I think you have a little error on your code. As far as I know, AWSPath, it should look like:

iotClient.setAWSPath("/things/esp8266/shadow");

At least that works for me, and they use it this way on this video.

That's all I can tell... I am learning at this moment as well.
Hope it helps!!


Most efficient way to store number in EEPROM? I would like to store temperature readings in eeprom, the value from -55.00 to 125.99. What is the most space efficient way to store these numbers with two significant digits along with epoch timestamp?

Thanks

My best off-the-top-of-my-head figure is 6 bytes.

4 bytes for the timestamp (assuming a 32-bit value).  Two byte for -32768 to +32767.

Multiply the temperature by 100 to make it into the integer range -5500 to +12599. That then fits comfortably inside a 16-bit signed integer.

However, there are other tricks you can use.

For instance, if you know the time of one reading you don't need to store the time of the next - only how much later it is.  One byte can then store up to 255 "whatevers" later than the previous entry - be that seconds, minutes, hours, whatever.

Similar with the temperature.  You can just store the difference from the previous reading as a single byte if you know that successive readings will never deviate by more than +/-1.27 degrees.

Also, you can check to see what the last saved temperature was, and only save a new temperature if it has changed from before.

Another thing is the resolution of your data.  You say 2 decimal points, but if the values are all multiples of 0.05 then what is the point of storing at 0.01 resolution?  Just store how many 0.05s there are (divide by 0.05) then multiply it out again afterwards to get the original temperature.  Most useful when coupled with a temperature difference to increase the storage range.

There's many tricks, you see, and which work best depend exactly on what you want to do with the data.


ESP8266, sporadically no write access to the file system I have an ESP8266 project which reads my gas consumption. The hardware and the project run satisfactorily. Sporadically, the ESP8266 can no longer write to its file system and therefore cannot save any data. As soon as I upload the complete data and the sketch to the device again, it works for a few months. After that, the mistake occurred again and again. What could that be?

The ESP8266 then has an "Exception" error. Unfortunately, I have not yet been able to find the reason for the error, why it always happens.

Does anyone have a tip on how I can isolate the problem?

https://github.com/HomeAutoUser/ESP-Gaszaehler-GZ16/tree/pre-release_v1.91

I have faced the same issue with my water leak detector, based on esp8266. It was caused by memory leak in the ESP binaries, so, I've updated it to ver 2.6.3

So, you can try to log (print to serial) free memory amount:

extern "C"
{
    #include "user_interface.h"
}
uint32_t free = system_get_free_heap_size();


bh1750 lightsesor won't work ok, im having problems with my bh1750, here is all info i got:

board: esp32s nodeMCU v. 1.1

Pins:

Wiring: (the 2 reds go to pin 21 and 22)

code:

#include <BH1750.h>
#include <Wire.h>

BH1750 lightMeter;

void setup(){

Wire.begin();
Serial.begin(115200);
lightMeter.begin();
if (lightMeter.begin()) {
Serial.println(F("BH1750 initialised"));
}
else {
Serial.println(F("Error initialising BH1750"));
}
}

void loop() {
uint16_t lux = lightMeter.readLightLevel();
Serial.println(lux);
delay(500);
}

Sorry for bad formating

Serial output:

13:01:41.926 -> [BH1750] ERROR: received NACK on transmit of address

13:01:41.926 -> [BH1750] ERROR: received NACK on transmit of address

13:01:41.926 -> Error initialising BH1750

13:01:41.926 -> [BH1750] Device is not configured!

13:01:41.926 -> 65534

13:01:42.430 -> [BH1750] Device is not configured!

13:01:42.430 -> 65534

13:01:42.932 -> [BH1750] Device is not configured!

13:01:42.932 -> 65534

and that goes on forever

Hope someone got an answer :D

Your code looks good. I2C configuration is default which depends on your board manager.
Then your wiring may be wrong.

Using a multimeter to check supply voltage on the BH1750 module. It should be 3.3V
Using a multimeter to check the connection between the BH1750 module with ESP32.
Difference ESP32 vendor may provide a difference I2C pinout. Make sure you connect everything correctly.
Using an oscilloscope or logic analyzer to capture data on an I2C bus.
If everything good, try to use another module.

From your log, I guessed, the power supply is good. I2C connection is your problem.
More, you should use the different color wire for the difference signal. It helps prevent unexpected connections.


Any explanation for this behavior? For the below code snippet
const char* fr_fbdb(char tag[30]) // fn for retrieving data
{
  char full_path[120];
  const char *_dt ;
  strcpy(full_path , base_path);
  strcat(full_path , tag);
  Serial.print( "retrieving from " );
  Serial.println(full_path) ;
  Firebase.get(firebaseData, full_path);
  _dt = firebaseData.cstrData();
//  Serial.print("while ext: ");
//  Serial.println(_dt);
  return _dt ;
}

void retreive_sch()
{
  int no_tag = strlen(*tag) ;
  //Serial.print("no. of tags in the DB: ");
  //Serial.println(no_tag);
  const char *_data[no_tag];

  Firebase.get(firebaseData, "/SCHEDULE DETAILS/SELECTED");
  sch_no = firebaseData.cstrData();

  Serial.print("extracting schedule");
  Serial.println(sch_no);

  strcat(base_path , sch_no); // base path w/ sch no.

  for (int i = 0 ; i < 6 ; i++)
  {
    _data[i] = fr_fbdb(tag[i]);
    Serial.print("while ext: ");
    Serial.println(_data[i]);

  }

  for(int i=0 ; i<6 ; i++)
  {
    Serial.print("after extraction:");
    Serial.println(_data[i]) ;
  }
}

This is the output:
retrieving  schedule changes -- setup
extracting schedule3
retrieving from /SCHEDULE DETAILS/SCHEDULE3/DATE
while ext: [1609612200000,\"inf\"]
retrieving from /SCHEDULE DETAILS/SCHEDULE3/FREQ FR
while ext: \"-2\"
retrieving from /SCHEDULE DETAILS/SCHEDULE3/FREQ TO
while ext: \"-2\"
retrieving from /SCHEDULE DETAILS/SCHEDULE3/WEIGHT
while ext: 29
retrieving from /SCHEDULE DETAILS/SCHEDULE3/TIME
while ext: \"6:30\"
retrieving from /SCHEDULE DETAILS/SCHEDULE3/frequency
while ext: \"-1\"
after extraction:"root":[]
after extraction:\"-1\"
after extraction:keep-alive
after extraction:\"-1\"
after extraction:"root":[]
after extraction:\"-1\"

As you can see, the output of the same variable _data[] inside that particular function changes.
Any idea why?

The problem is these lines of code in your function fr_fddb():
  Firebase.get(firebaseData, full_path);
  _dt = firebaseData.cstrData();

You didn't share enough code to make this clear, but firebaseData appears to be a global which you reuse. When you call its .cstrData() method you're getting a pointer to the same buffer each time, and that buffer is overwritten each time you call Firebase.get().
You can verify this by printing the pointer value each time through, like so in your retrieve_sch() function:
  for (int i = 0 ; i < 6 ; i++)
  {
    _data[i] = fr_fbdb(tag[i]);
    Serial.print("while ext: ");
    Serial.println(_data[i]);
    Serial.printf("_data[i] pointer %p\n", _data[i]);
  }

You'll likely see that the 6 pointers are identical. The value is changing because you keep reusing the same string.
The easy fix is:
  Firebase.get(firebaseData, full_path);
  _dt = strdup(firebaseData.cstrData());

This allocates memory and stores in it a duplicate of the string that was fetched from Firebase. Your function will now return that and firebaseData can safely be reused.
This solution will require you to free that memory at some point when you're doing using it by calling free(_dt); or whatever you're holding the pointer in when you're done. I leave that as an exercise for you.


arduino nano V3 updated schematics Does anybody know where to find an updated scematics of Arduino Nano V3? All the Nano drawings I found (even in the Arduino official site) are based on ATMEGA 168 , no one including ATMEGA 328!!!

Thanks

Mike

Go for the manufacturer of this board website i.e. www.gravitech.us. You can get the eagle files and all the data you need. Alternatively, you can download the eagle file of nanov3 directly using this link: http://site.gravitech.us/Arduino/NANO30/ArduinoNano30_Eagle.zip


Sending a struct over i2c How would you send a struct from an i2c slave when requested by an i2c master?
Slave Struct Respdonder Sketch (Seeeduino Xiao)
#include <Wire.h>

struct TransmitData
{
  int a;
  int b;
  int c;
  int d;
  float e;
  float f;
  float g;
  float h;
};

TransmitData data;

void setup()
{
  Serial.begin(9600);
  Wire.begin(2);
  Wire.onRequest(requestEvent);

  data.a = 1;
  data.b = 2;
  data.c = 3;
  data.d = 4;
  data.e = 5.1;
  data.f = 6.1;
  data.g = 7.1;
  data.h = 8.1;
}

void loop()
{
  delay(100);
}

void requestEvent()
{
  Serial.print("sending ("); Serial.print(sizeof data); Serial.println(" bytes)");
  Wire.write((byte *)&data, sizeof data);
}

Master Struct Requester/Reciever Sketch (Arduino MEGA)
#include <Wire.h>

struct TransmitData
{
  int32_t a;
  int32_t b;
  int32_t c;
  int32_t d;
  float e;
  float f;
  float g;
  float h;
};

TransmitData data;

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

void loop() {
  Serial.print("requesting ("); Serial.print(sizeof data); Serial.print(" bytes)... ");
  if (Wire.requestFrom(2, sizeof data)) {
    Wire.readBytes((byte*) &data, sizeof data);
    Serial.println("done");

    Serial.println(data.a);
    Serial.println(data.b);
    Serial.println(data.c);
    Serial.println(data.d);
    Serial.println(data.e);
    Serial.println(data.f);
    Serial.println(data.g);
    Serial.println(data.h);
  }
  else {
    Serial.println("could not connect");
  }
  delay(500);
}

The serial output on the slave device is:
sending (32 bytes)

The serial output on the master device is:
requesting (24 bytes)... done
1
0
2
0
0.00
0.00
5.10
6.10

int isn't guaranteed to be the same size across platforms. Use fixed width integer types instead.
https://en.cppreference.com/w/cpp/types/integer
struct TransmitData
{
  int32_t a;
  int32_t b;
  int32_t c;
  int32_t d;
  float e;
  float f;
  float g;
  float h;
};


Code to obtain PWM output I tried code to obtain 100KHZ PWM output with a 41.66% duty cycle by reading an analog value from A0, which is compared with a reference 5V value for obtaining PWM value.

Can someone help me with the code? Any help is very much appreciated.

Here is my code.

int Pwmpin=9;//Pwm Output Pin
int Fchange= A0;//Frequency change through Potentiometer

void setup() {
  pinMode(Pwmpin, OUTPUT);//Pwm pin as Output
  Serial.begin(9600);
  TCCR1A=_BV(COM1A1)|_BV(COM1B1);//Non-inverted Mode
  TCCR1B=_BV(WGM13)|_BV(CS11);//Prescalar 8
}

void loop(){
  float freq=0;
  float count=10000,countt=0,Pinput=0;
  while(1){
    ICR1=count;//variable Frequency
    countt=16*count;
    freq= int(16000000/countt);
    OCR1A=int(count/2);
    Serial.print("Pwm Freq =");
    Serial.println(freq);
    count=10000;
    Pinput=analogRead(A0);//Read input value
    Serial.print("adc value is:");
    Serial.println(Pinput);
    Pinput=(Pinput/0.0113);
    Serial.print("pwm value is:");
    Serial.println(Pinput);
    count=count+Pinput;
    if(count>=100000) {
      count=10000;
    }
    delay(1000);
  }
}

Read the datasheet.
Figure out which pen mode works for you and which prescaler and top you need.
Set timer1 to that mode.

After that all you need is to load the duty cycle register with the desired value.

For your application leave the top value alone.

Your code is far from that.


Controlling an LED with the 74HC4067E multiplexer I am testing a 74HC4067E MUX setup with my Arduino Uno which I would like to use to selectively light up many LEDs, one at a time. For this first test, I am using a modified version of the blink tutorial. Essentially, I am setting the 4 control pins to digital LOW and setting the input to HIGH, through a resistor appropriate for my LED. I am also providing 5V to the Vcc pin on the MUX. I don't really know why I am doing this, but it seems to work. Here is my code:

int led_input = 0;
int led_ctrl_1 = 1;
int led_ctrl_2 = 2;
int led_ctrl_3 = 3;
int led_ctrl_4 = 4;

void setup() {
    pinMode(led_input, OUTPUT);
    pinMode(led_ctrl_1, OUTPUT);
    pinMode(led_ctrl_2, OUTPUT);
    pinMode(led_ctrl_3, OUTPUT);
    pinMode(led_ctrl_4, OUTPUT);
}

void loop() {
    // control signal
    digitalWrite(led_ctrl_1, LOW);
    digitalWrite(led_ctrl_2, LOW);
    digitalWrite(led_ctrl_3, LOW);
    digitalWrite(led_ctrl_4, LOW);

    // input signal
    digitalWrite(led_input, HIGH);
    delay(500);
    digitalWrite(led_input, LOW);
    delay(500);
}

I know, the code could be more efficient.

The blue LED is hooked up to I0 and blinks as it should. The problem comes when I try to change the control pin values. When I change it to, say 6...

// control signal
digitalWrite(led_ctrl_1, LOW);
digitalWrite(led_ctrl_2, HIGH);
digitalWrite(led_ctrl_3, HIGH);
digitalWrite(led_ctrl_4, LOW);

... and I move my LED to I6, I get no blink. I've tested all the pins and it doesn't seem like there is a signal coming from any of them. I assume that I am using the chip wrong, but I'm not sure how. Pictures of my setup follow... any help is greatly appreciated!

Arduino pin 0 maps to chip pin 1 (through resistor) as input.
Arduino pins 1-4 map to chip pins 10, 11, 14, and 13 in that order.
I have a 5V going to chip pin 24.
The LED is connected long leg to chip pin 9 in the images, the grounded.

Pin 15 on that MUX is the enable pin, you need to tie it to ground. Otherwise, it's just floating, and it only would have worked by accident.

Also, you state:

  I am also providing 5V to the Vcc pin on the MUX. I don't really know why I am doing this, but it seems to work.

The chip needs power to work. The Vcc pin is where you give it the +5V power. Without that, it might still work, but only by accident and depending on the inputs on the other pins.


OneButton with pins A6 and A7 I noticed that OneButton library does not work with pins A6 and A7 (with A1 and A2 it works good) on my Arduino Nano. Is it because A6 and A7 are Analog only? There is possibility to make them work properly?

sketch example is here https://github.com/mathertel/OneButton/blob/master/examples/TwoButtons/TwoButtons.ino

Pins A6 and A7 are analog only pins. They have no digital functionality at all.

You can see that pins 19 and 22 only have ADCn on them - no Pxn for digital operation (ignore the colour scheme of those pins - that's an error in the datasheet).


Arduino code for turning an led on by one clap and then off by one clap I want my Arduino to turn on a LED when sound sensor detects a clap (noise) and keeps the LED on until the sound sensor detects another clap (noise) which turns the LED off.

int Sensor = A0;
boolean status_lights = false;

void setup() {
  pinMode(Sensor, INPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  int status_sensor = digitalRead(Sensor);
  if (status_sensor == 0)
  {
    if (status_lights == true)
    {
      status_lights = false;
      digitalWrite(13, LOW);
    }
    else {
      status_lights = true;
      digitalWrite(13, HIGH);
    }
  }
}

My sound sensor has 3 pins.
sound sensor details

EDIT: My code only turns on the led but dosen't turn it off when I clap.

If the sound level is below the threshold, the DO pin of the sensor signals a high value. If the sound level exceeds the threshold, i.e you clap you hands, the DO is pulled to GND and the signal gets LOW for a short while. After this short while the signals gets HIGH again.

Now look at you loop:

void loop()
{
  int status_sensor = digitalRead(Sensor);

  if (status_sensor == 0)
  {
    // you enter this block if you clap your hands and the
    // mcu is fast enough to capture the signal / DO pin (LOW)
    // within the short time interval
    // I'm sure it is fast enough to enter this block multiple
    // times in the interval the clap is active.
    if (status_lights == true)
    {
      status_lights = false;
      digitalWrite(13, LOW);
    }
    else
    {
      status_lights = true;
      digitalWrite(13, HIGH);
    }
  }
}

You see, the LED is toggled as long as the LOW interval of the sensor is active (DO=LOW).

I interpret you statement "My code only turns on the led but dosen't turn it off when I clap." so, that the LED is on, when the program starts without a clap. That means that the environmental noise is loud enough to activate the sensor. Then the loop above is iterated permanently and you switch on and off the LED at a very fast speed. That's like you would apply a PWM waveform on the LED pin. The LED is on but dimmed to about 50%.

To find out if I'm right, just add a delay in the loop. My assumption seems to be correct, if the LED blinks with one herz (one time per second).  The you can adjust the sound threshold until the LED stops blinking.

void loop()
{
  int status_sensor = digitalRead(Sensor);

  // Add the delay here ..........
  delay(500);

  if (status_sensor == 0)
  {

If you have calibrated the sensor, remove the delay from the code and add a new delay after changing the LED states. That should be much shorter, because it's only there to ensure that you don't toggle the LED while the sensor is active.

    if (status_lights == true)
    {
      status_lights = false;
      digitalWrite(13, LOW);
    }
    else
    {
      status_lights = true;
      digitalWrite(13, HIGH);
    }
    // wait until the clap is over
    delay(100);


Is there any way to run binary code from RAM? I am looking for an inexpensive single board computer that I could program in assembly language, using limited facilities to load the object code from a PC and simple I/O peripherals.

Ideally I would like to be able to write in a reasonable time all the code on the machine myself. I don't want an OS in the way, as I want to have a program that writes in RAM some code and then branches to execute it.
Arduino would probably be my best choice, as far as system simplicity suitable for assembly programming goes, but it has a Harvard architecture and it won't allow me to execute from RAM.

Years ago I was using a Von Neumann architecture 8-bit CPU that could branch execution to any address, no matter whether it was mapped to ROM, RAM or whatever. This is what I would like to do now.

I probably could write and load in Flash memory an interpreter of op codes written in RAM, but it is a very complex and time-consuming solution, unless virtual machines of this kind exist already.

Any suggestions on other workarounds with Arduino or of other micro-controllers I might use?

Thanks!

Pierre

In my opinion the interpreter idea is much more feasible. The notion of writing, in assembler, code that itself generates machine code, in RAM, and then executes it, is itself incredibly complex.

You haven't said why you want to do this, so this is somewhat of an X-Y problem.

  I don't want an o.s. in the way ...

The normal Arduinos do not have an OS in the way - basically the code you write is what gets loaded onto the chip.


Switching a dual h bridge in parallel I'm using a dual h bridge to control two dc motors on an inverted pendulum (cart-pole system).  At the moment, I have to send two different pulse width modulated signals to the two enable pins to control the two motor speeds and four digital write commands to control the directions.

Ideally, I want to switch the two motors simultaneously in the same direction and with the same speed.  So, I'd like to be able to control both motors' speeds with only one pulse width modulation signal and control both motor directions with only two digital write commands.

Is there a way I can do with with Arduino?  Can one PWM signal from a single arduino pin be sent to two enable pins at the same time? Can the same be done for a single digital output pin?  If so, how can I accomplish this?

You can connect a single output to as many input loads as you like, provided the current is sufficient to hold the output voltage within the input thresholds. See the datasheet for the H bridge to find out what the input load and thresholds are, and compare them with the output from the Arduino.


Flash a .hex to an ATtiny45 with Arduino I'm trying to upload a hex file to an ATtiny45 with an Arduino. I uploaded the Arduino ISP sketch to my board. I connected the ATtiny as shown below:

Then I go to CMD and type:

avrdude -c avrisp -p t45 -b 19200 -P COM6 -U flash:w:main.hex:i

And it gives me this error:

Please define PAGEL and BS2 signals for ATtiny45!

I double checked the connections and i tried to uplad a bootloader with Arduino IDE as written in this article: Programming Hex-code on an Attiny85 with the Arduino. I can uplad sketches with ArduinoIDE with no error.

Googling the error gives this tutorial. Towards the bottom of the page they say

  You’ll probably get the following message, but don’t worry, the upload should have worked anyway:

  avrdude: please define PAGEL and BS2 signals in the configuration file for part ATtiny85

So it seems this can be ignored and the part has been programmed!


Using digital pin 11 for DMDCon and IR remote I have a project where I would like to control a countdown clock using a remote with:

Arduino Uno R3 Development Board

Funduino Uno Protoshield Board

Freetronics Dot Matrix Display Connector

Arduino IR Reciever

Both the DMDCon and the IR use digital pin 11. Can these two share the pin 11 or is there a workaround of sorts?

The workaround would be to configure the https://github.com/shirriff/Arduino-IRremote library referenced in your question to any available digital input.


Working on my second project and I'm confused about proper procedure for turning on the arduino The first project I did was just making the led blink (it was pulsing a signal to pin 13. I'm guessing most of you have seen similar tutorials).

Today I plugged in some wires and resistors and wrote a program for a volt meter.

How am I to stop the pulses on the output pins from my previous project from messing everything up in the newer project in that interval of time after plugging in the usb and before compiling/ uploading the new code?

The question occurred to me when I saw the led blinking from the last project, before I could hit the upload button... maybe I'm wrong, but I'm envisioning this causing problems for me in the future as my circuits become more and more complex.

If you've rewired an Arduino board for a new project, such that outputs from the currently-loaded sketch may cause problems, temporarily jumper from ground to Reset, to hold the MCU (ATmega328, etc.) in reset until you are ready to load the new sketch.  Pull the jumper upon starting a download, of either your new project or an empty sketch as suggested in Majenko's comment.  Typically, Arduinos are reset at the beginning of each download.

Arduino boards (Uno, Nano, Mega, et al) that use an additional chip (FT232, Atmega16U2 or 32U4, CH340G, etc) as a USB interface should be able to register as USB devices even when the MCU is reset.  Arduino boards without a separate USB chip (Leonardo, Micro, et al) should not.


Trying to understand Classes I have searched about class and int but I still don't understand.

I have seen this code online I want to understand it

class Motor {

  int enablePin;
  int directionPin1;
  int directionPin2;
  public:

  //Method to define the motor pins
  Motor(int ENPin,int dPin1,int dPin2){
    enablePin = ENPin;
    directionPin1 = dPin1;
    directionPin2 = dPin2;
};

class Motor {

This says to start defining a class. A class is like a "container" that holds both data and functions (methods). After defining the class, it becomes like a new variable type that you can declare multiple instances of.

  int enablePin;
  int directionPin1;
  int directionPin2;

These define the 3 integer variables (int=integer; whole numbers like 2, 3, 1000, -5, etc.) that belong to the class and have the identifiers given (enablePin, etc.) Since not otherwise specified, these variables are private, meaning that only other functions in the class can access them. Other parts of the program are not allowed to access these variables.

public:

This means that the following definitions are accessible by parts of the program that exist outside the class.

Motor(int ENPin,int dPin1,int dPin2) {
  enablePin = ENPin;
  directionPin1 = dPin1;
  directionPin2 = dPin2;
}

This defines the only "member function" in this class and because it shares the same name as the class (Motor), it is called a "Constructor", and allows you to pass arguments to an object created from the class -- in this case, if you declare an object of class Motor by myMotor = Motor(1, 2, 3);, the constructor is called with parameters 1, 2, and 3. This constructor happens to just set the private variables to be the same as the arguments passed in.

But... All of this is basic C++, so a book or course on C++ programming would be better in-depth resource to understand this.

The code snippet also is incorrect because it has unbalanced curly-braces -- there is one to open the definition of the class and one to open the definition of the constructor, but only one closing brace.


Arduino I/O Shield relay won't switch I have an Arduino Uno and the I/O Shield wired up and I'm trying to switch (i.e. engage) a relay on the I/O Shield, but nothing seems to be working.

I've identified the input pins correctly and am able to send digital signals to it and it responds correctly. I also see the LED next to the relay light up when I do a digital write on the Arduino to a specific relay pin.

I'm starting to think that I might need to use an alternative power source or that I am not using the Arduino API correctly to switch the relay. At the moment I do a digitalWrite(13, HIGH), delay, and then do a digitalWrite(13, LOW) - pretty simple.

The shield is just powered by the Arduino at the moment, and I haven't been able to find where I might be able to plug in power, so I'm assuming the Arduino supplies it with all of the power it needs.

#include <Arduino.h>

int relayPin = 13;

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

void loop() {
            digitalWrite(relayPin, HIGH);
        delay(5000);
        digitalWrite(relayPin, LOW);
        delay(5000);
}

Unless you share a schematic, it will be very difficult to provide a good answer.

Here are the things that you might be doing wrong:

1) Using a power supply which is not able to provide enough current to the relay.

2) Using a power supply of wrong voltage as required by relay coil. The relay might be needing 12 V and you might be trying to power it up with a 5 V power supply.

3) You might be trying to drive the relay directly with your GPIO pin (without using any external transistor switch).

4) Trying to raise a dead relay. There is a possibility that the relay is damaged. Check it by powering it up directly using a battery or another adequate power supply that you got.


ESP-01 + UNO won't detect gateway Apparently, this combination of hardware won't accept anything other than WiFiEsp.h together with SoftwareSerial.h (if anyone knows something better/newer than these two, please let me know).
Thing is: I can connect to wifi, send and receive data (to an apache server inside my home network) just fine. After my project was almost done, I decided to connect it to a real server on the internet only to discover that ESP-01 couldn't detect my gateway.

#include "WiFiEsp.h"
#include "SoftwareSerial.h"

int pinWifiRX = 6;
int pinWifiTX = 7;

char ssid[64]    = "*****";
char pass[32]    = "************";

SoftwareSerial Serial1(pinWifiRX, pinWifiTX);

int wifi_status;

void setup() {

  Serial.begin(9600);

  Serial1.begin(9600);
  while(!Serial1) (true);

  WiFi.init(&Serial1);

  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println(F("No shield"));
    while (true) {}
  }

  IPAddress localIp(192, 168, 1, 60);
  IPAddress subnetMask(255, 255, 255, 0);
  IPAddress gateway(192, 168, 1, 36);

  WiFi.config(localIp);  // <--- this line is accepted and works, but the other 3 gives compilation errors
//  WiFi.config(localIp, gateway);
//  WiFi.config(localIp, gateway, subnetMask);
//  WiFi.config(localIp, gateway, subnetMask, gateway);

  wifi_status = WiFi.begin(ssid, pass);

  if (wifi_status == WL_CONNECTED) {

    IPAddress ip;

    ip = WiFi.localIP();
    Serial.print(F("[WiFiEsp] IP Address: "));
    Serial.println(ip);

    ip = WiFi.subnetMask();
    Serial.print(F("[WiFiEsp] Subnet Mask: "));
    Serial.println(ip);

    ip = WiFi.gatewayIP();
    Serial.print(F("[WiFiEsp] Gateway: "));
    Serial.println(ip);

//    ip = WiFi.getDNS();  // <--- function doesn't exist
  }

}

void loop() {}

Results in:

[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 2.2.1
[WiFiEsp] IP address set 192.168.1.60
[WiFiEsp] Connected to *****
[WiFiEsp] IP Address: 192.168.1.60
[WiFiEsp] Subnet Mask: 255.255.255.0
[WiFiEsp] Gateway: 192.168.1.0

As one can see, Subnet Mask is corret, but it "detects" Geteway 192.168.1.0 when it should be 192.168.1.36. This way, I can connect to any device in LAN, but cannot access any address on the internet.

I even tried to send some AT commands directly to SoftwareSerial.h, but I don't get any response.

Will I have to start the whole project over from scratch (using another hardware combination), or is there a way to change gateway by hand? Better yet, is there a way to make it detect the gateway's address correctly?

EDIT: could it be related to the firmware I installed to the ESP-01? I followed this tutorial and got it from this link.

Thanks in advance.

EDIT: in this example, i used the WiFi.config(localIp) function to set a fix IP. I don't really need that, it was just an attempt to make it get the correct Gateway address. Even if I comment that line, the Gateway is still wrong.

I've had some progress in my researches towards this problem.

In fact, Arduino gets the correct gateway address from my DHCP server, but displays the wrong one. There must be a bug somewhere in WiFiEsp library somewhere.

To debug this, I made a few changes to the following files:

WiFiEsp-Master/src/WiFiEsp.h

void config(IPAddress local_ip, IPAddress gateway);
void config(IPAddress local_ip, IPAddress gateway, IPAddress subnetMask);

WiFiEsp-Master/src/WiFiEsp.c

void WiFiEspClass::config(IPAddress ip, IPAddress gateway)
{
  EspDrv::config(ip, gateway);
}
void WiFiEspClass::config(IPAddress ip, IPAddress gateway, IPAddress subnetMask)
{
  EspDrv::config(ip, gateway, subnetMask);
}

WiFiEsp-Master/src/utility/EspDrv.h

static void config(IPAddress local_ip, IPAddress gateway);
static void config(IPAddress local_ip, IPAddress gateway, IPAddress subnetMask);

WiFiEsp-Master/src/utility/EspDrv.cpp

void EspDrv::config(IPAddress ip, IPAddress gateway) {
  LOGDEBUG(F("> config"));

  // disable station DHCP
  sendCmd(F("AT+CWDHCP_CUR=1,0"));

  // it seems we need to wait here...
  delay(500);

  char buf_ip[16];
  sprintf_P(buf_ip, PSTR("%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]);

  char buf_gateway[16];
  sprintf_P(buf_gateway, PSTR("%d.%d.%d.%d"), gateway[0], gateway[1], gateway[2], gateway[3]);

  int ret = sendCmd(F("AT+CIPSTA_CUR=\"%s\",\"%s\""), 2000, buf_ip, buf_gateway);
  delay(500);

  if (ret==TAG_OK)
  {
    LOGINFO1(F("IP and gateway addresses set"), buf_ip);
  }
}

void EspDrv::config(IPAddress ip, IPAddress gateway, IPAddress subnet)
{

  LOGDEBUG(F("> config"));

  // disable station DHCP
  sendCmd(F("AT+CWDHCP_CUR=1,0"));

  // it seems we need to wait here...
  delay(500);

  char buf_ip[16];
  sprintf_P(buf_ip, PSTR("%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]);

  char buf_gateway[16];
  sprintf_P(buf_gateway, PSTR("%d.%d.%d.%d"), gateway[0], gateway[1], gateway[2], gateway[3]);

  char buf_subnet[16];
  sprintf_P(buf_subnet, PSTR("%d.%d.%d.%d"), subnet[0], subnet[1], subnet[2], subnet[3]);

  int ret = sendCmd(F("AT+CIPSTA_CUR=\"%s\",\"%s\",\"%s\""), 4000, buf_ip, buf_gateway, buf_subnet);
  delay(500);

  if (ret==TAG_OK)
  {
    LOGINFO1(F("IP, gateway and subnet mask addresses set"), buf_ip);
  }
}

These few changes should be enough to implement fix IP address and specify manual address for gateway and subnet mask (please feel free to correct me if I'm wrong).

But after doing this, I realized the gateway continued to be "192.168.1.0". Then I added this piece o code to the function EspDrv::readUntil, inside EspDrv.cpp:"

        ringBuf.push(c); // this line was already there
        Serial.print(c);

This way, I could see exactly all responses for the AT commands sent by WiFiEsp library. When asked, the results were:

+CIPSTA:ip:"192.168.1.60"
+CIPSTA:gateway:"192.168.1.36"
+CIPSTA:netmask:"255.255.255.0"

Then I realized the problem wasn't the gateway, but the DNS. If the library sends command "AT+CIPSTART=3,"TCP","www.google.com",80", the result was:

Not connected

busy p...

And, if increased the timeout value to 15000 instead of 5000, the result was:

DNS ERROR

Now my problem is partially solved. I can connect to an external server if I use an IP address, but I can't set a domain name because it won't be resolved by the DNS.

Apparently the firmware version of my ESP-01 won't accept "AT+CDNSCFG=?" required to set/retrive DNS address. I tried to set 8.8.8.8 as the DNS, but the result was "NOT OK".

I will stick to this "solution" for now, but would be glad to hear any comment about what I described here and a more final solution.

Thanks.


Motor code for the "Pirate: 4WD Arduino Mobile Robot Kit with Bluetooth 4.0", will not work The board is the RoMeo BLE V 1.0 and I have set the board to Arduino UNO on the board part of the arduino IDE, as I cannot find the RoMeo Board.

This is the code for the motors.

``int speedPin_M1 = 5;     //M1 Speed Control
int speedPin_M2 = 6;     //M2 Speed Control
int directionPin_M1 = 4;     //M1 Direction Control
int directionPin_M2 = 7;     //M1 Direction Control

void setup(){

}

void loop(){
    carAdvance(150,150);
    delay(1000);
    carBack(150,150);
    delay(1000);
    carTurnLeft(150,150);
    delay(1000);
    carTurnRight(150,150);
    delay(1000);
}

void carStop(){                 //  Motor Stop
  digitalWrite(speedPin_M2,0);
  digitalWrite(directionPin_M1,LOW);
  digitalWrite(speedPin_M1,0);
  digitalWrite(directionPin_M2,LOW);
}

void carTurnLeft(int leftSpeed,int rightSpeed){         //Turn Left
  analogWrite (speedPin_M2,leftSpeed);              //PWM Speed Control
  digitalWrite(directionPin_M1,LOW);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,HIGH);
}

void carTurnRight(int leftSpeed,int rightSpeed){        //Turn Right
  analogWrite (speedPin_M2,leftSpeed);
  digitalWrite(directionPin_M1,HIGH);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,LOW);
}

void carBack(int leftSpeed,int rightSpeed){             //Move backward
  analogWrite (speedPin_M2,leftSpeed);
  digitalWrite(directionPin_M1,LOW);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,LOW);
}
void carAdvance(int leftSpeed,int rightSpeed){          //Move forward
  analogWrite (speedPin_M2,leftSpeed);
  digitalWrite(directionPin_M1,HIGH);
  analogWrite (speedPin_M1,rightSpeed);
  digitalWrite(directionPin_M2,HIGH);
}

After I upload the code, nothing happens. The boards light blinks and then after that nothing occurs. How do I get the Motors moving according to the code in the loop?

To formulate my comments as answer:

Your board has some features involving the motors/servos:

Since the PCs USB port cannot provide enough current for the motors, they can be switched off wit the Motor Power Switch. It has to be set to OFF, when you connect the board to an USB port. For operating the motors the board needs it's own power supply (a battery in your case), which can provide enough current. So in this case, you have to switch the Motor Power Switch to ON, to enable the motor drivers. Attention: If you turn on the motors while being connected to the USB port, you can damage your board and also your USB port.
The motors are connected to the pins 4, 5, 6 and 7. If you don't need the motors, you can use these pins for other purposes. For this, the board let's you disconnect the motor driver from these pins. If the jumpers, that are marked with "Motor Control Terminal Jumpers" in the image on this documentation page, are inserted onto the jumper pin pairs (in the image they are already inserted), the motor drivers will be connected to the mentioned pins. If the jumpers are not inserted there, the motors will not work, since they are not connected to the controlling pins.

Note, that you need to use pinMode(pin_number, OUTPUT); in the setup() function for all pins, that you want to use digitalWrite() on, because only this way, the corresponding pin will be set to an output (can only then output a digital signal on digitalWrite()). analogWrite() will configure the corresponding pin for you, but it is a good practice to set it as OUTPUT in setup anyway, to make it clear for readers, that this pin is an output.