'Servo_Pointer' was not declared in this scope I can't seem to find the error I made; can anyone help me?
The error message: 'Servo_Pointer' was not declared in this scope
I get the error at the end of the code with the line: Servo_Pointer.write(servo_pos)
The code:
const int photo_left = A0;    // select the input pins for the photoresistor
const int photo_right = A1;
const int ledPin_1 = 2; // These leds will be used for the testing of the pointing of the servo motor
const int ledPin_2 = 4;
const int ledPin_3 = 7;
const int ledPin_4 = 8;
const int ledPin_5 = 12;
const int photoValue = 0;  // variable to store the value coming from the photoresistor
const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin_1, OUTPUT);
  pinMode(ledPin_2, OUTPUT);
  pinMode(ledPin_3, OUTPUT);
  pinMode(ledPin_4, OUTPUT);
  pinMode(ledPin_5, OUTPUT);
  Serial.begin(9600);
  #include <Servo.h>
  Servo Servo_Pointer;
  Servo_Pointer.attach(9);
  int servo_pos = 0;
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading  ) {
    readings[thisReading] = 0;
  }
}

void loop() {
  Servo_Pointer.write(servo_pos); // tell servomotor to go to position in variable 'servo_pos'
  delay(15);          // waits 15ms for the servo to reach the position
  // turn the ledPin on
  delay(15);
}

You should make Servo Servo_Pointer; global, i.e. place it outside the setupfunction, e.g. after the line int average = 0;.
In your code, it is a local variable within the setup function. When this function ends, the local variables within this function (such as Servo_Pointer ) do not exist anymore.
By making the variable global, you can use it anywhere. However, it's not a good coding practice to use global variables when not needed.
A benefit of making the variable global is that you can see the memory consumption of the instance of Servo_Pointer when compiling.
Also see the comment of timemage below: Don't put #include statements in the middle of your code, put them in the beginning of your code.


How is AVR Assembly in Eclipse or at Linux command line done? I'm trying to learn AVR development in C and Assembly for the Arduino Uno (Atmel 328p microprocessor) in Linux.

I've found many good guides on how to install and setup the AVR plugin for Eclipse, and I've no problem building and uploading C code.
However there doesn't seem to be any menu options for creating an assembler project, nor can I seem to find the correct syntax for using the cli avr-as for assembling my programs into a .hex file.

If you don't mind using make, I'd recommend copying the Makefiles from ChibiOS. For me it works quite well and it's much more aligned to my daily experience with Linux.


Popen command restarts arduino So I am trying to make a Mac OSX program with Cocoa that will be able to control my Arduino via serial. I currently have the C command

popen("echo 7 > /dev/cu.usbmodem1411", "r");

to try to send the number 7 over serial to the Arduino. I know that the path     /dev/cu.usbmodem1411 is correct because the Arduino is responding, however it seems to "crash" or simply restart whenever this command is received from the Mac. Sorry this may be a question for StackOverflow, but I thought I would start here.

I think the problem is more going to be that you don't have a serial connection to the arduino. ie, if you look in the Arduino IDE, you assign a serial port to the application. When you upload your sketch, a connection is made, the arduino resets (by design) and your sketch is uploaded.

What it appears you are doing here is opening a new connection and sending the character (which is ASCII) which in turn sends the arduino into reboot to look out for a sketch being uploaded.

I'm not familiar with popen and maybe you can use it and keep the connection open and even monitor the data stream, but I would say instead of writing directly to the device as you've done, use an application that will initialise the port properly (ie open it and leave it open) so that you can continue to use/monitor it.

A quick google search has brought up Mike's PBX Cookbook which has some good info about it. I've personally used minicom (a guide for installing minicom) and CoolTerm, I have used Screen but it was so long ago I don't remember why I moved on.

edit: I just followed the link submitted by the first commenter (sorry name not available in the edit screen), and although you've responded with "that's not it", it actually is, you just haven't realised it since your popen command is actually opening the port and triggering the RTS mentioned in that post


MCP23017: 16x2 LCD showing black boxes I've researched a lot but I couldn't find a solution to my problem, which is that after properly following all steps from this Website: http://www.danielealberti.it/2014/02/collegamento-diplay-lcd-ad-arduino-via.html

and after using the Library LIQUIDTWI2:

(https://drive.google.com/file/d/0BwSP1-P3E2UJY1loYWtWQVRWNlU/edit?usp=sharing)

for I2C connections, the LCD keeps displaying black boxes on the top row.

I'm pretty sure that I have wired (as shown in the tutorial linked above) and programmed everything correctly but I'm still getting the black boxes. Is the problem related with the MCP23017 pin expander or with something else?

I'm using an Arduino UNO

Quite often such situation occurs when the display does not reset properly (the reset from the IDE does not necessarily reset the display!).

So, once the sktech has been uploaded to the board, I would first try to do a reset on the Uno board (using the RESET button). If that doesn't do the trick, I would recommend to make the contrast adjustable (all my LDC displays showed "black boxes in the upper row" on delivery and I had to ajust the contrast).

If that also has not the desired effect, there is no alternative to debugging your code. Without the code itself, we cannot guess what might be wrong.


Arduino: load variables with values read from SD card I am having a bit of trouble loading values stored on an SD card and assigning them to variables within my program. I can achieve this as one big block of data, but would much prefer them to be saved to variables whilst in a loop or some other process.

My txt file has the following 6 ints & floats values, which are displayed vertically in the file:

2
0.003200
312
1
0.720000
8

Each of these values I want assigned to variables data1,....2,3,4,5,6. Unfortunately, the code I use below will never achieve this, but I am clueless as to any theory to solve this problem. Thanks in advance.

myFile = SD.open("test.txt", FILE_READ);
    if (myFile) {
    while (myFile.available()) {
        data = myFile.read();
    }
myFile.close();
}
else {
    Serial.println("Read Error");
}

File implements Stream just like Serial. so you can use parseInt and parseFloat

int n = File.parseInt();
float x = File.parseFloat();
Serial.println(n);
Serial.println(x, 6);


Reading/writing to Arduino GPIO pins from raw C code I'm interested in writing a C program without the Arduino IDE and related libraries and am trying to figure out how I can access the GPIO pins for read and write.

My assumption is that the GPIO pins are - at the hardware layer - just memory addresses, and so if I know what their address is I can send/receive data to and from them.

For writing to the digital pins, do I just send an int with a value of 0 or 1 to the pin's address? If so, what might that code look like? Can I then assume I could poll that address for a value, which would be either 0 or 1?
Can I assume the same for analog pins, but instead of binary values, I'd get an integral value between 0 and 1023?

And if I'm way off here, and pins are not accessed via memory addresses, then how?

Again, the solution I'm looking for wouldn't involve Arduino software, just the Arduino hardware (an AVR or ARM MCU). Bonus points for C pseudo-code examples! Thanks in advance!

In theses cases you are right, using register address is the way to read/write data from/to digital pins.
In the case you use analog input, the process is similar but you have to follow some procedures before getting the value of the data.

GPIO REGISTERS

For AVR micro-controllers these registers are:
DDRn – Data Direction Register
PORTn – Port Output data Register
PINn – Port Input Register
n- Indicates the port name i.e. A, B, C & D
If you have arduino board and want to use these pins, look for mapping pictures about arduino and avr pins.

The following is an example from the Arduino website.

DDRD is the direction register for Port D (Arduino digital pins 0-7). The bits in this register control whether the pins in PORTD are configured as inputs or outputs so, for example:

DDRD = B11111110; // sets Arduino pins 1 to 7 as outputs, pin 0 as input
DDRD = DDRD | B11111100; // this is safer as it sets pins 2 to 7 as outputs
                         // without changing the value of pins 0 & 1, which are RX & TX

See the bitwise operators reference pages and The Bitmath Tutorial in the Playground

PORTD is the register for the state of the outputs. For example;

PORTD = B10101000; // sets digital pins 7,5,3 HIGH

You will only see 5 volts on these pins however if the pins have been set as outputs either by using the DDRD register directly or by using the  pinMode() function.

For analog read

You just need to include the headers and start using the registers. They hold the equivalent hexadecimal values for your microcontroller. And the procedure is described in the datasheet. All you have to do is to translate it to code.

// this code scans ADC1 for an analog signal upon request, using 8Mhz processor clock

#include <avr/io.h>
#include <stdint.h>       // needed for uint8_t

int ADCsingleREAD(uint8_t adctouse)
{
    int ADCval;

    ADMUX = adctouse;        // use #1 ADC
    ADMUX |= (1 << REFS0);   // use AVcc as the reference
    ADMUX &= ~(1 << ADLAR);  // clear for 10 bit resolution

    // 128 prescale for 8Mhz
    ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

    ADCSRA |= (1 << ADEN);    // Enable the ADC
    ADCSRA |= (1 << ADSC);    // Start the ADC conversion

    while(ADCSRA & (1 << ADSC)); // waits for the ADC to finish

    ADCval = ADCL;
    ADCval = (ADCH << 8) + ADCval; // ADCH is read so ADC can be updated again

    return ADCval;
}

int main(void)
{
    int ADCvalue;

    while (1)
    {
        ADCvalue = ADCsingleREAD(1);
        // ADCvalue now contains an 10bit ADC read
    }
}

For more information about analog read, see this.


SD-Card-Module doesnt work with external power supply Problem description

I am trying to build a datalogger with an Arduino UNO. I have connected a SD card module to the Arduino. I have planned to catch the measurement data from the analog input pins. Everything works fine if connected to the usb port. But if I run the Arduino over an external power supply, the SD.open-method fails (It simply returns false).
The problem occurs even, if I connect the external power supply additional to the USB connection. So the problem can't be a missing serial connection.

Note that the problem only occurs, if SD.open is in WRITE-mode.
(File dataFile = SD.open("datalog.txt", FILE_WRITE);)

What I've already tried:

running the SD-card example code, which is included in the SD card library.
trying different types of file-system formattings (FAT, FAT32, with different cluster-sizes)
powering the sd-card reader with 3.3V instead of 5V

Arduino wiring

Look at the pictures to check if there are some mistakes with the wiring:

Specifications of the power supply

And here are the specifications of the power supply:

Manufacturer: MyVolts
Model: DD282MU
Input: 100-240V (AC) - 50-60 Hz
Output: 9V, 1A (DC)

I hope you can help me with my problem. And of course, I hope there is a solution for the problem at all. Thank you.

Okay, thank you all for your efforts.

Finally, after changing the PSU and connecting the Arduino to another usb-port without operating system, I found the solution.

The problem was the SD-Card itself:
I swapped the SD-card with a newer (maybe more expensive(?)) one and it just works now. No matter if you connect the Arduino with the PSU or over an usb connection.
My assumption is, that there could be a different clock speed of the sd-card module on different voltages, which causes the problem. The old sd-card can't handle the fast speed and runs into an error (or just rejects it) on a write attempt...

Anyway, thank you again for your efforts!


ATmega328P of Arduino Pro Mini not responding While I was trying to change the fuse bits of ATmega328P of my Arduino pro mini using a USBasp device to operate it at 3.3 V/8 MHz, it failed due to the bad connection I guess. After that, the USBasp programmer can't detect the chip.

Does the MCU get bricked/locked?

How can I recover this?

Is there any way to solve this problem using an AVR Dragon board? If yes, please let me know the whole process.

Does the MCU get bricked/locked?

Yes, it's possible. The chip requires a valid clock to run, even when programming, so if the clock settings are corrupt or were set wrong it will no longer be programmable through ICSP.

  How can I recover this?

Depending on what has actually happened you can either supply an external clock signal to the chip to get it working again, or you may need to reprogram the chip through the parallel programming interface, also known as HVP (High Voltage Programming).

  Is there any way to solve this problem using AVR Dragon board?

Yes, the Dragon can do parallel programming. You can read more about how to fix fuses with it here.


Atmega328p low voltage I am using atmega328p in my PCB prototype, due to some reason I can use only 4 volt for power supply.
My question is that
"How to run atmega328P through 4 voltage"

Shouldn't be a problem. The minimal voltage required to run at 16MHz is 3.8 Volt. No extra steps required.


When connecting, client.connect() returns 0 I'm using an arduino UNO with ethernet shield. When following a few guides online for a school project I came across this issue. First code sample:

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

    EthernetClient client;

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 1, 25);
    byte server[] = { 64, 233, 187, 99 }; // Google

    void setup() {
      Ethernet.begin(mac, ip);
      Serial.begin(9600);
      delay(1000);
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      if (client.connect(server, 80)) {
        Serial.println("connected");
        client.println("GET /search?q=arduino HTTP/1.0");
        client.println();
      } else {
        Serial.println("connection failed");
        Serial.println(client.connect(server, 80));
      }
    }

This doesn't work unfortunately. We successfully connect to our network, but client.connect() doesn't work and returns 0. Expected result:

SUCCESS: 1
TIMED_OUT: -1
INVALID_SERVER: -2
TRUNCATED: -3
INVALID_RESPONSE: -4

According to the documentation it shouldn't be able to return this. Why wouldn't this work? Thanks in advance.

You need to provide more than just the IP address. The Arduino also needs to know the default router address in order to send packets to the right place.

Unfortunately there isn't a way of giving it that information without also giving it a DNS address, so you have to do that as well.

You need to have:

IPAddress gateway(192, 168, 1, 1);
IPAddress dns(8, 8, 8, 8);
IPAddress ip(192, 168, 1, 25);

And then in setup:

Ethernet.begin(mac, ip, dns, gateway);

Alternatively you can rely on DHCP to give you all the details, and just use:

Ethernet.begin(mac);


Which pins are represented by these constants from ABR library? The following code comes from AtTiny serial library that I want to use:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

// change these to use another pin
#define TX_PORT PORTB
#define TX_PIN  PB0
#define TX_DDR  DDRB
#define TX_DDR_PIN DDB0

I have no idea which pins to connect. What do these constants mean and where are they documented?

The mapping can be found in the io.h file but also in Arduino core files.

Below is the pin mapping:

                        ATtinyX4
                      +----U----+
  (VCC)-------------1-|VCC   GND|-14------------(GND)
  (D10)-------------2-|PB0   PA0|-13----------(D0/A0)
  (D9)--------------3-|PB1   PA1|-12----------(D1/A1)
  (/RESET)----------4-|PB3   PA2|-11----------(D2/A2)
  (D8)--------------5-|PB2   PA3|-10-------(D3/A3/SS)
  (D7/A7)-----------6-|PA7   PA4|-9---(D4/A4/SCL/SCK)
  (MISO/SDA/D6/A6)--7-|PA6   PA5|-8------(D5/A5/MOSI)
                      +---------+

The serial library uses:

#define TX_PIN  PB0

Which is ATtinyX4 Pin #2, or Arduino attiny core digital pin D10 https://github.com/damellis/attiny/blob/master/variants/tiny14/pins_arduino.h.

Cheers


Timer question: Phase Correct PWM at specific frequency I am trying to create a sinusoidal wave segmented in 64 Frame, each holding a Duty cycle precisely varying from 0x00 to 0xff. This is for an Arduino Nano.
I have trouble understanding the following:

Which Wave Generator Mode and Matches will cause an interrupt at the constant Frame as well as help do a phase correct/fast PWM for the varying Duty Cycle?
How to tell which pin to use? I guess OC0B means Pin5 according to Pin Mapping but I'm not sure I truly understand.

This is what I have for the moment.
const byte waveFrame = 126;
const byte wave[]    = {
    0x80,0x98,/*a total of 64 values*/,0x67
};
byte frame = 0;
void setup(){
    pinMode(3,OUTPUT);
    noInterrupts();
    TCCR0A = (1<< WGM00)  // Phase correct PWM with top as OCR0A
           | (1<<COM0A0)  // Toggle OC0A on match
           | (1<<COM0B1); // Clear/Set OC0B on Compare Match when up/down-counting.
    TCCR0B = (1<<  CS01); // Prescaler of 8 (16MHz/8= 2MHz)
    TCNT0  = 0;           // Counter restarted
    OCR0A  = waveFrame;   // Constant frequency/64 for each frame
    OCR0B  = 0;           // Duty Cycle
    interrupts();
}
ISR(TIMER2_COMPA_vect){
    OCR0B = wave[frame & 0x3f]; //Rolls around
    frame++;
}

Thank you! I've lost a little bit of hair on this.

pinMode(3,OUTPUT);

Pin 3 on the Nano is OC2B. It's PWM is controlled by Timer 2. You
want to use pin 5 (OC0B), since you are using Timer 0. Or
switch to Timer 2.

Phase correct PWM with top as OCR0A

Note that this is the description of mode 5. If you want this mode, you
have to set both the bit WGM00 in TCCR0A (which you did)
and the bit WGM02 in TCCR0B (which you didn't). Here you have set
mode 1: phase correct PWM with top = 0xff.


Industrializing Arduino - 24V io? (Electronics) I would like to make an arduino board that is capable of handling 24V i/o.

Powering the Arduino would be done through either a linear or switching regulator of some sort. Low amperages, so efficiency isn't the main problem.

For input:
24v to 5v input scaling could be created with a voltage divider.

As far as I know, there will never run a high current into the arduino? So the power loss is minimal?

For output:
5v to 24v can be easily achieved using a MOSFET? Since this will ramp up the possible load (higher amperages) given that I'm using a 24v supply/separate line.

So I could choose to make half the I/O only input and half only output.

Could I combine the MOSFET and voltage divider, and in what way?
Are my "assumptions" about the I/O correct, or are there beter ways of handling it?
What other things should I think of? Over voltage protection? Polarity inversion? Protection against too high currents?

You mentioned 2 items: the supply voltage to the Arduino and scaling up to 24V output.

If the supply voltage you have available is 24V, then I would suggest you look for a DC-DC converter that scales down to 12V. Or, if you are looking to design your own PCB then perhaps use a 78xx voltage regulator. The 78xx are 3 pin devices and only require 2 caps to operate - I suppose a heat sink will not be needed.

To scale up the outputs to 24V I would suggest one of the following options:

a) Relay board /
These will take the 5V from your Arduino and close a mechanical switch. If the relays are good quality they will go on for ages. And you can switch loads from 0 to 240V and more, DC or AC.
Plus of the relays are sturdiness and that they are quite forgiving for short current overloads. Minus are that relays are " slow" when compared to semiconductors and they can arce when the contacts open - especially when driving inductive loads and that. Arcing will wear down your contacts and in extreme cases generate EMI that might interfere with your electronics. Arcing can be remediated in AC with a capacitor accross the contacts or in DC with a flyback diode.

If you will make your own PCB don't forget the flyback diode on pins connecting to the relay coils or you will possibly fry the Arduino due to a voltage spike!

Many of these boards are available on the web, so it's a quick solution.

b) Optocouplers /
Also a good option. Functionally they act as a relay. They are a bit less forgiving to current overloads, so chose them wisely.
They are silent and fast acting. Available for AC or DC and up to 600V.
Minus side is that the tend to be a bit more expensive than relay boards. I'm talking about industrial grade devices and not some el-cheapo web site :-)

c) MOSFETS or Bipolar transistors /
If you are designing your PCB then this could be an option.
Here you can use a MOSFET or a PNP transistor of the adequate ratings and you would be done. Though maybe considering yur time investment the options above could be less expensive in the end.
I this case you get complete control of PCB layout which might be a consideration.
If you go this way, don't forget to add a flyback diode to the output of these devices to protect from spikes when switching inductive loads (= motors, solenoids).

A big advantage of Relays and Optocouplers is the galvanic isolation they provide, both from the load to the board as between the loads themselves.

If you could supply more detailed specs of the loads, environments etc I can help you narrow down your choices.


Current Draw for LED Projects I am working on a project with LED strips that would consume 12V and 20A. The problem is that the household wall outlet limitation is 15A, and 20A current draw would potentially start a fire. I have been searching for tutorials of large current LED project, and none of them really addresses the current draw problem.

I found an adequate power supply. It is Meanwell RSP-320-12. http://www.mouser.com/ProductDetail/Mean-Well/RSP-320-12/?qs=Uzd%2Fwh%252bZzhBChmc2p7rgKQ%3D%3D.

How can I make it work with a 15A wall outlet limitation?

Thanks in advance!

Drawing 20A on 12V means 240W which on 110V is 1A and a bit (a bit more once you consider efficiency of the conversion).

The spec sheet of the power supply you linked says that it will draw 2.7A max on a 115V input.

The power supply will convert the high voltage low amps into low voltage high amps.


Setup/Debug affordable 9DOF IMU I bought a 9 DOF IMU from AliExpress (pictures below), asking because this seems to be somewhat of a common issue (and I'm a bleeding noob). I tried setting up this board using example codes from Adafruit - presuming this would work and it's a compatible board (and it just looked exactly the same). However, surprise - several errors.

Using this guide I attempted to run the pitchrollheading example - it reports LSM303 not found. The wiring is according to this guide, A4 (SDA) and A5 (SCL) are connected, 5V in, Ground of IMU to Ground of Arduino (Arduino uno, like in the guide)

Next I debugged the lines on the board using the multimeter: 5V on line in vs ground, 5V on the SDA/SDC lines (seemed fine)

Then I debugged using the i2cdetect library, however it reported empty.
 0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
 00:          -- -- -- -- -- -- -- -- -- -- -- -- --
 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 70: -- -- -- -- -- -- -- --

Using analog read I can get values that seem to change with board movement, that would confirm that - in theory - the board works.

Questions

Making sense from debugging: What could be somre reasons the board not listed using the i2cdetect library (also tried a script)?
Is there an easy way (or would you recommend spending time to investigate) to use the rawdata from the arduino's analog in lines to compute pitch,roll and heading?
Would a project like this be typically orders of magnitude easier to set up with a raspberry pi (I have one setup and ready)? (more libraries?)
Are IMU's usually easy to setup, and is it likely this would be easier with a more expensive IMU (e.g. MPU9250/6500)?

Thank you in advance, and please remember: I'm a noob, I ask for your patience and advice.

I re-soldered all connections and used new wires. Now the board is recognized by the i2cdetect library. Upon multimetering all connections using the continuous mode (the one that looks like a loudspeaker), I noticed my breadboard sometimes does not conduct properly. Cheap breadboards and/or cables are at fault here, as far as I can tell - a rookie mistake. I'm guessing the ground connection is the only one I have not measured before


Can I connect a voltage, higher that the 1.1V bandgap voltage, to an ADC pin Can I (attempt to) measure a voltage that is higher that the ADCs Vref, without damaging my IC?

I'm trying to measure the battery voltage using a resistive divider, and using the internal 1.1V bandgap voltage. I selected the resistors so the voltage would be around 1V when fully charged.

My project can however also be power by a wall-adapter, which exceeds the batteries voltage, resulting in a voltage higher than 1.1V at the ADC.

In the datasheet the table of ADC Characteristics seems to indicate that the maximum input voltage is Vref. Though I'm not sure if that's the maximum voltage is can convert, or if that's the maximum voltage that's allowed.

Elsewhere in the datasheet it says: Single ended channels that exceed VREF will result in codes close to 0x3FF, which seems to indicate it isn't a problem to exceed Vref (as long as it's below Vcc).

The part I'm using is an ATtiny13A, but the relevant sections of the datasheet seem identical to the ATMega328.

Yes, you can go above VRef.

  Voltage on any Pin except RESET

  with respect to Ground ................................-0.5V to VCC+0.5

And as the ADC reference says anything above VREF will give you the maximum value (it will saturate).

So powered from 5V you can apply anything from -0.5V to +5.5V safely. That's basically the supply voltage plus one diode drop for the ESD protection diodes within the pin.

The ADC is just comparing two voltages. The VREF isn't used to power anything.


Wemos mini pro switch power from servo with mosfet bs170 I got a servo connected to a wemos/arduino with a capacitor(470uf). Before I didn`t use a cap.

Now with the cap the device use to much power while sleeping(capacitor on the servo). I want to switch off the power to the servo with a MOSFET. I tried this with a BS170 N channel MOSFET. There is a youtube movie with the same settings except for the mainboard. They use an Arduino uno instead a wemos.

When I test the circuit with a led everything is working. When I use a servo instead a led, nothing happen. There is a little sound from the servo(I think not enough voltage).

When I check the voltage without anything hooked on the drain of the mosfet the output is perfect(5V). If I connect a led or a servo the voltage will drop to 3v.

Wemos mini pro has 3.3v output on the gpio pins.

Can someone explain me what I doing wrong? I saw and read some articles about Mosfet. I think it`s not clear enough for me.

My supposition:

The MOSFET's R(DSON) is too high and causing a large voltage drop.

A servo uses more current than a little LED.  That current passing through the MOSFET, with an R(DSON) of potentially up to 5Ω, reduces the voltage available to the servo, causing it to not work. Further more, ground for the servo is raised up above the real ground level adding an offset into the logic levels that could cause communication issues.

Suggestion: Pick a MOSFET with a lower R(DSON) (ideally measured in the milli-ohms), and a lower V(GS) threshold (something around 1-2V max would be good).


What can I do in this situation I only currently have 2 arduinos and I find that any project I build I feel bad because I have to rip it apart to get the arduino because I want to build something else. Is there a way to get arduinos for cheap? (I'm new to arduino)

Possibly not "genuine" Arduinos, but eBay has many sellers in China and Hong Kong who sell boards that are just like Arduinos, if you're willing to wait several weeks for delivery.

I was able, just now, to find an Arduino UNO compatible board for US$3.59, plus less than $2 shipping to the US. Note that they do not come with tech support, and none of the profit goes to support the official Arduino developers.


Trying to measure change in light levels over time I have two LDR's attached to my Arduino Uno and an RGB LED as an output component. The two LDR's are at different offboard heights in order to see the change in light between them. I want to code on Arduino so that if the difference in light between the two LDR's does not change by a large amount over a 1 hour period (i.e stays similar), it will make the RGB  LED flash. I know that I have to use an if and else statement to do this, but does anyone know how I can code it so that I can achieve the above statement?

Thanks

Break this into pieces. Solve the pieces one at a time.

Write code that reads the 2 photocells and calculates the difference between them. Log that difference to the console.

Then add a global variable to remember the old difference, and a max difference. Each time you take a new set of readings and calculate the difference, compare it to the old difference. If the new difference is greater than the old difference, update the max difference. Then update the "old difference" with the new reading.

Figure out how to use millis() to record a starting time, and monitor the reading difference until an hour has passed. If the reading difference is below your "large amount" threshold, start the light blinking.

Then you need to decide what to do about times greater than an hour. Do you track the max difference over the most recent 60 minutes and flash the light if it is below your threshold? Maybe save a difference reading every 5 minutes into a ring buffer with 12 entries (an hour's worth of entries) and keep checking the ring buffer for a difference value greater than your threshold? (You should be able to Google search "C ring buffer" for sample ring buffer code. It's actually quite simple to implement.

You might also want to calculate a moving average difference reading, and compare each reading to that. I recommend using an Exponential Moving Average (EMA).

I have code in my project that uses EMA to calculate a single brightness value rather than a difference, but the idea is the same. Here is an excerpt from my code:

Define a global:

float   photocellAverage =      0;

#define sampleCountToAverage 100  //The larger the number of samples, the more slowly the average will change with each new reading.

Then

int photocellValue = analogRead(photocellPin);
photocellAverage -= photocellAverage / sampleCountToAverage;
photocellAverage += float(photocellValue)/sampleCountToAverage;

For you, you'd be calculating a difference reading and an EMA of that difference reading:

float   photocellDifferenceAverage =      0;

int photocell1Value = analogRead(photocell1Pin);
int photocell2Value = analogRead(photocell2Pin);
int photocellDifference = photocell1Value - photocell2Value;
photocellDifferenceAverage -= photocellDifferenceAverage / sampleCountToAverage;
photocellDifferenceAverage += float(photocellDifference)/sampleCountToAverage;


Sense checking Arduino Uno barebones schematic I have had some difficulties finding a barebones Arduino board and have had the following made. I just wanted to see if anyone could spot any issues? I think it has everything. I'm really trying to get it as minimalistic as possible, but at the same time able to use a power source like a 12v/24 battery. Any help would be greatly appreciated. Many thanks

You shouldn't put a capacitor under the chip like that. In fact I don't much like the layout of the whole crystal circuit at all.
You need capacitors on the 7805 regulator - around 10µF on both the input and output.
The RESET pin needs a pullup resistor otherwise the chip won't function at all.
You need decoupling capacitors on all VCC pins on your main chip.
Instead of meandering ground traces you should use a ground pour.
Running from the kind of voltages you propose the 7805 is going to melt. You will need a BigAss™ heat-sink on it. For those kind of voltages you would be better using a switching (aka buck) regulator. Maybe as an off-board module to keep your board simple.


Arduino uploading to the wrong port I purchased a half dozen fake Arduinos hoping to build a bunch of projects without paying a fortune. I have all the drivers installed, and the port shows up in the Arduino IDE. The problem is when I try and upload the code I get the following error:

  can't open device "/dev/cu.wch": No such file or directory

I played around a little and tried running:

sudo ln -s cu.wch\ ch341\ USB\=\>RS232\ 1a1220  cu.wch

After running this a new port shows up called cu.wch, and if I select that it works.

The issue is the Arduino's port is cu.wch ch341 USB=>RS232 1a1220, but for some reason the IDE is trying to write to cu.wch. By linking the folders I can fix this but since it is a hack every time I restart my computer I have to rerun the command. Is there a way I can either rename the Arduino port or permanently link the folder?

I am using OSX 10.10 and Arduino IDE v1.6.3

I would guess the problem is the IDE not properly handling device names containing spaces. Consider your symlink a workaround rather than a hack - unless you want to repair the IDE itself.


is PIN To PIN matching mcu against Atmega328P-AU available? I want to upgrade my product which is based on Atmega328p-AU, having the problem of programming memory. I don't want to change the PCB of the product. Is PIN To PIN matching MCU against Atmega328P-AU available?

The only other AVR chip with more program memory in the 32/TQFP form factor is the ATMEGA4808 at 48 kB.

Unfortunately, the pinout is not the same compared to the ATMEGA328P-AU:

ATMEGAx8P family datasheet

ATMEGAx08 family datasheet


8-segmet LED's on Adafruit Trinket I would like to have an array of eight 7- and 8-segment LED numerical displays on my Adafruit Trinket.
I know that there are some prebuilt arrays of 4 LED's. So 2 in array would do just fine.
However, my Adafruit Trinket doesn't have enough ports for that. I have heard something about connecting it to a small piece of controlling hardware that makes me able to have way less ports in need.
What is the appropriate way of connecting a lot of those LED's on only a few ports on a micro controller?

My ideal output would be as follow:
88 88:88:88 or maybe 88 88.88.88
So ideally there would be a small space between the first group of 2 digits and the rest.
Basically, the last 6 digits will represent a time in minutes, seconds and hundreds of seconds.

For LED displays, I advise using a MAX7219.

This circuit:

can manage up to 8 digits (7-segments + 1 LED for DP or colon separator) or up to 64 LEDs
needs only 3 pins to manage display
can be daisy-chained if you need to interface with more than 64 LEDs
requires only 1 resistor to be fully functional
is easily supported on Arduino with this library

I have used it in several circuits and happy with it.

Note that there also other libraries that support this circuit but I haven't used them.

This circuit has only one downside: its price (about $10 each); but the price is counter-balanced by its simplicity and the fact you don't need any additional component (e.g. transistors) besides a simple resistor.


I am trying to read input from 5th PIN of PORT B? In a nutshell i want to read a PORTB 5th pin without using digitalRead API ( i am trying to learn baremetal using arduino-uno-r3)

Just to Learn How internal register works i did not used digitalRead API, instead i have used DDRB register to set the 5 bit of DDRB as Low indicating PORTB 5th pin is in input mode then i am using an if statment to check if 5th bit of PINB is high or low my expection was that when i connect arduino pin 13 to 5v  if statment will become TRUE.

void setup() {
  // put your setup code here, to run once:
  DDRB = DDRB & ~(1<<5);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(PINB & (1<<5)){
     Serial.println("Got data");
    }
}

When i executed above code i am constantly getting if as TRUE

There seem to be several, separate issues in your question.

One is a simple matter of language. In English, “1st” is an abbreviation
for “first”, which is an ordinal adjective applied to an item in a list
meaning that there is no other item before it in that list. In the same
vein, “5th” means “fifth”, which applies to the item that has exactly
four items before it. For instance, the list of pins of port B is {PB0,
PB1, PB2, PB3, PB4, PB5}. PB0 is the first in the list, and PB4 is the
fifth. The fact the first item bears the number 0 makes this confusing.
Thus, I recommend avoiding ordinal adjectives altogether and instead
calling the pins by their names, like “digital 13” (Arduino naming) or
“PB5” (AVR naming).

The second issue, and probably your main concern, is about the floating
input pin. You cannot expect a reliable reading from a floating input. I
will not try to explain why, as the issue has been discussed ad nauseam
here and elsewhere. Just do a Web search. The simplest solution is to
use the built-in pull-up resistor and externally connect a push button
between the pin and ground. You will read LOW whenever the button is
pressed:

void setup() {
    pinMode(13, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    if (digitalRead(13) == HIGH)
        Serial.println("HIGH");
    else
        Serial.println("LOW");
}

The last point is about going bare metal and learning how to use the I/O
registers directly. A small warning first: you have to keep in mind that
this is board-specific. You tagged your question with both “arduino-uno”
and “arduino-mega”, but these boards have different pin mappings
(digital 13 is PB7 on the Mega). The general way of using the DDRx,
PORTx and PINx registers is the same across all AVR chips, but is not
portable to Arduinos based on a different architecture.

So let's assume this is intended to work only on an Uno, Nano, or
other board based on an ATmega328P.
Judging from the example code you show, you seem to
already understand pretty well how these registers work. There is no
problem in your code, beside the fact that it requires an external
pull-up. If you want to enable the internal pull-up, you have to set the
appropriate bit in PORTB. This can seem confusing, as the same register
is used for pull-up control (when the pin is in input mode) and for
output control (when the pin is an output). Essentially, each GPIO pin
has four distinct electrical states which are controlled by to I/O bits:

│ DDRxn │ PORTxn │ state        │
├───────┼────────┼──────────────┤
│   0   │    0   │ INPUT        │
│   0   │    1   │ INPUT_PULLUP │
│   1   │    0   │ OUTPUT LOW   │
│   1   │    1   │ OUTPUT HIGH  │
└───────┴────────┴──────────────┘

The example program above can be translated to low-level AVR style as
follows:

void setup() {
    DDRB &= ~_BV(PB5);  // input mode
    PORTB |= _BV(PB5);  // enable pullup
    Serial.begin(9600);
}

void loop() {
    if (PINB & _BV(PB5))
        Serial.println("HIGH");
    else
        Serial.println("LOW");
}


ESP-01 not waking correctly up after deep sleep I have an ESP-01 that I want to measure pool temperature with. It will send the data over MQTT to the broker.

I have connected RST to GPIO16 so I can use the deep sleep functionality. Currently I am testing sending a "hello world" to the MQTT broker, and everything works fine when booting up the first time, but it seems like the ESP never wakes up correctly after the first deep sleep.

My script looks like this:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// Set ADC mode
ADC_MODE(ADC_VCC);

// WiFi settings
const char* ssid = "Network";
const char* password = "Password";
IPAddress ip(192, 168, 0, 100);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);

// MQTT settings
const char* mqtt_server = "192.168.0.110";
const int mqtt_port = 1883;
const char* mqtt_user = "User";
const char* mqtt_pass = "Password";
const char* mqtt_client_name = "poolsensor";
const char* mqtt_topic = "pool";

// Data wire plugged into D1 on the ESP8266 ESP-01 - GPIO 5
#define ONE_WIRE_BUS 5

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

// Pass our OneWire reference to Dallas Temperature
DallasTemperature DS18B20(&oneWire);

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {
  delay(10);

  // Annuonce connection
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  // Setup WiFi config and connect
  WiFi.mode(WIFI_STA);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're connected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");

    // Attempt to connect
    if (client.connect(mqtt_client_name, mqtt_user, mqtt_pass)) {
      // Success
      Serial.println("connected");
    } else {
      // Fail
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

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

  // Start WiFi setup
  setup_wifi();

  // Set MQTT server
  client.setServer(mqtt_server, mqtt_port);

  // Set resolution to 0.25
  DS18B20.setResolution(10);

  // Start sensor
  DS18B20.begin();
}

void loop() {
  if (!client.connected()) {
    reconnect();
  } else {
    // Get temperature
    /*
    DS18B20.requestTemperatures();
    float temp = DS18B20.getTempCByIndex(0);

    if ((temp > -20) && (temp < 60)) {
      client.publish("pool/temperature", String(temp).c_str(), true);
    }
    */

    client.publish("pool/temperature", "hello world");
    Serial.println("published temperature");

    delay(1000);

    // Sleep
    ESP.deepSleep(60 * 1000000);

    delay(3000);
  }
}

Everything looks good in the serial monitor when compiling and uploading code, as the code runs the first time:

Connecting to Network
......
Connected, IP address: 192.168.0.100
Attempting MQTT connection...connected
published temperature

And I can see in my MQTT debugger that it receives hello world. After around 60 seconds, the following is shown in the serial monitor (lots of gibberish):

{l�l��|��d�|�d�b<����s�c$�#��ng�lgn���cxp��${$sd�s��'�c�ncp��

This is the last message I ever receive from the ESP, so I assume it never deep sleeps again and runs over the code again.

Anyone experienced the same, or see a bug in my code?

Pretty sure you will need gpio 16 connected to reset in order for this to ever work, it’s tricky but not impossible. Have a read here:

https://randomnerdtutorials.com/esp8266-deep-sleep-with-arduino-ide/


How do i improve this Code? (or how to pass a Char String into a Function to behave like a Variable) Sorry i am a beginner and amateur when it comes to coding, can somebody help me to make the code inside the loop() less "monkey-like" by using a proper function?
I have tried a lot and at some point i am running out of ideas about how to even phrase the question on google.
My main problem when writing a function for this case is that i don't know how to pass a variable into a function which has to be written out as part of a Variable but also as part of Char Strings if that makes sense.
If you look at the code inside the loop() i actually only had to pass the number to the function, like "3" to change some Variables and Char Strings accordingly. I would be able to solve the issue with those Char Strings but i am completely clueless how to handle the Variable (rmd3, rmd4...).
"3" as in:
Variable:        rmd3,    Char String      "rmd3 = 1",   Variable Value:  rotary_mode = 3   and Char String:     "rotary_mode = 3"
This is a simplified version of my code but boils down to where i am stuck at. It refers to a rotary selector i am using which has 6 Positions (rmd1 - rmd6). However if i knew how to solve this issue i could use it in many other situations as well.

Bounce rmd3 = Bounce(45,10);    //rotary selector on pos.3
Bounce rmd4 = Bounce(44,10);    //rotary selector on pos.4
int rotary_mode = 0;            //Rotary Mode

void setup() {
  Serial.begin(11520);
  pinMode(45, INPUT_PULLUP);   //pin of pos.3
  pinMode(44, INPUT_PULLUP);   //pin of pos.4
  }

void loop() {
             rmd3.update();
             if (rmd3.fallingEdge()) {
                Serial.print("rmd3 = 1");
                rotary_mode = 3;
                Serial.print("rotary_mode = 3");
             }
             if (rmd3.risingEdge()) {
                Serial.print("rmd3 = 0");
                rotary_mode = 0;
                Serial.print("rotary_mode = 0");
             }

             rmd4.update();
             if (rmd4.fallingEdge()) {
                Serial.print("rmd4 = 1");
                rotary_mode = 4;
                Serial.print("rotary_mode = 4");
             }
             if (rmd4.risingEdge()) {
                Serial.print("rmd4 = 0");
                rotary_mode = 0;
                Serial.print("rotary_mode = 0");
             }
}´´´

Pseudocode:

´´´void loop() {
int rmd_int;            //Mode numbers as int from 1 to 6
char rmd_char = [2];    //Mode numbers as char from "1" to "6"

              rmd3.update();
              rmd_int = 3;
              rmd_char = "3";
              void selected_mode(rmd_int, rmd_char);
}

void selected_mode(int rmd_int, char rmd_char ){
             if (rmd[rmd_int].fallingEdge()) {
                Serial.print("rmd[rmd_char] = 1");
                rotary_mode = [rmd_int];
                Serial.print("rotary_mode = [rmd_char]");
             }
             if (rmd[rmd_int].risingEdge()) {
                Serial.print("rmd[rmd_char] = 0");
                rotary_mode = 0;
                Serial.print("rotary_mode = 0");
             }
}```

The question is somewhat confused, but I think I got what you mean. Your
code suffers from too much repetition. You only showed the handling of
two selectors, but you want to handle 6 of them. Repeating all the logic
6 times would make the code unwieldy and hard to maintain. So you
want to put the logic in a function and just call that function six
times.

I actually only had to pass the number to the function, like "3" to
change some Variables and Char Strings accordingly

You do not need to pass the number as a string: you can use
Serial.print() to format the number instead. And you do not need to
write a function either: you can just put a for loop inside the
loop() function:
const int rmd_count = 6;

Bounce rmd[rmd_count] = {
    Bounce(48, 10),  // rotary selector on pos. 0
    Bounce(47, 10),  // rotary selector on pos. 1
    Bounce(46, 10),  // rotary selector on pos. 2
    Bounce(45, 10),  // rotary selector on pos. 3
    Bounce(44, 10)   // rotary selector on pos. 4
    Bounce(43, 10)   // rotary selector on pos. 5
};

void loop() {
    for (int i = 0; i < rmd_count; i++) {
        rmd[i].update();
        if (rmd[i].fallingEdge()) {
            Serial.print("rmd[");
            Serial.print(i);
            Serial.println("] = 1");
            rotary_mode = i;
            Serial.print("rotary_mode = ");
            Serial.println(i);
        }
        if (rmd[i].risingEdge()) {
            Serial.print("rmd[");
            Serial.print(i);
            Serial.println("] = 0");
            rotary_mode = 0;
            Serial.println("rotary_mode = 0");
        }
    }
}

The key to using for loops is to structure your data in arrays,
instead of collections of variables named with numbers. Thus, instead of
rmd3 you would use rmd[3]. Note that array indices start at zero.
Obviously, you could put the body of the for loop inside a function,
but at this point that would not help much in simplifying the code.

Edit: As a clarification, and per Delta_G's suggestion, I'll try to
explain the difference between an array and a collection of variables.
Each variable you define is mapped by the compiler (technically, the
linker) to a memory area. You can think of the variable names as
convenient names assigned to those memory locations. If you write:
Bounce rmd0(48, 10), rmd1(47, 10), rmd2(46, 10), ...;

You get:
      ┌───────┐        ┌───────┐        ┌───────┐
rmd0: |       |  rmd1: |       |  rmd2: |       |  ...
      └───────┘        └───────┘        └───────┘

In the picture above, the boxes are the memory areas. They are large
enough to hold a Bounce object, i.e. their size is sizeof(Bounce).
Each one has a name. You have no control over where, within the memory,
those variables are allocated: it's the linker's call.
In contrast, when you declare an array, you get a single variable
which is mapped to a contiguous memory area large enough to hold the
whole array:
Bounce rmd[6] = { ... };

Gives:
     ┌───────┬───────┬───────┬───────┬───────┬───────┐
rmd: |       |       |       |       |       |       |
     └───────┴───────┴───────┴───────┴───────┴───────┘

The individual cells do not have a name, and you instead use indices to
access them. For instance, rmd[0] references the first cell. Please,
note that in this example there is no variable named rmd0: if you try
to use that identifier the compiler will complain it is not defined.
Again, an array is not a “collection of variables”: it is a single
variable.
The array cells do behave in some sense much like individual variables
(they are called lvalues), as you can use rmd[0] in the same way you
would have used rmd0 in the previous code. The point of using an array
is that the indices do not need to be literals: you can use a variable
instead (rmd[i], where i is a variable), which comes handy when you
want to loop over all the cells.

Edgar pointed out that I can write the variable rmd3 by int i = 3
and rmd[i].

I hope it is now clear that this is not the case. There is no variable
named rmd3 unless you create it explicitly. Declaring an array named
rmd does not create such a variable.

[Can I] "form" a variable by "characters"?

Your question is not very clear, but my guess is you are talking about
computed variable names. This is a programming technique where you
access a variable by computing its name at run time. For example, you
combine the strings "rmd" and "3" in order to build the name of the
variable "rmd3". Then you use this computed name to access the variable
that has this name.
Computed variable names are quite often supported by interpreted
languages. For example, in PHP this is called variable variables:
$foobar = 42;           // the variable we want to access
$start = "foo";         // one piece of the name
$end = "bar";           // the other piece
$name = $start . $end;  // build the name from its pieces
print $name . "\n";     // prints the variable name: "foobar"
print $$name . "\n";    // prints the variable's value: "42"

Computed variable names are not supported by C++, which is the
language you use to program an Arduino. And for a good reason: when the
compiler translates your program to machine code, the names of the
variables are lost, they do not make their way to the actual Arduino.
And this is a good thing, as you would not want those names to consume
memory on the microcontroller.
Note that the names are present in the .elf file, as they could be
useful for debugging. If you were programming for a PC, you program
could in principle look into the file and find those names. On Linux you
would do that with the dlopen() and dlsym()
functions, from the libdl library. The libdl technique is, however, very
far from the capabilities of your typical Arduino, orders of magnitude
more complex than a simple array, and perfectly useless for your use
case.


How do I connect Arduino directly to MySQL server using the URL? I started a project with my Arduino Mega 2560 that gets some values from sensors. I'm using MySQL Connector, https://launchpad.net/mysql-arduino, and this library allows me to connect to a server using the IP address, and it worked on localhost.

This is the code:

/* Setup for all libraries */
#include <SPI.h>
#include <Ethernet.h>
#include <sha1.h>
#include <mysql.h>
#include <OneWire.h>

/* Setup for Ethernet Library */
byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xB3, 0x05 }; // MAC address must be unique; this is the Ethernet shield address
IPAddress server_addr( 177, 156, 122, 113 ); // Server addr

/* Setup for all others variables */
int DS18S20_Pin = 2; // Temperature sensor
float temperature;
float placasTensao;
float placasCorrente;
float geradorEolicoTensao;
float geradorEolicoCorrente;
float bateriaTensao;
float bateriaTemp;
float correnteSaidaControlador;
float correnteSaidaConsumo;

OneWire ds(DS18S20_Pin);  // On digital pin 2

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

/* Setup for connection and all variables of the database */
char user[] = "";
char password[] = "";
char INSERT_SQL[1000];
char temperature_convt[10], placasTensao_convt[10], placasCorrente_convt[10], geradorEolicoTensao_convt[10],
     geradorEolicoCorrente_convt[10], bateriaTensao_convt[10], bateriaTemp_convt[10], correnteSaidaControlador_convt[10],
     correnteSaidaConsumo_convt[10];

void setup(){
  Ethernet.begin(mac_addr);
  Serial.begin(9600);
  delay(1000);
}

void loop(){
  temperature = getTemp();
  convert(temperature, temperature_convt);
  snprintf(INSERT_SQL, "INSERT INTO data.data VALUES (%s, 1, 1, 1, 1, 1, 1, 1, NULL)", temperature_convt);
  sendData();
  delay(20000);
}

// Convert a float variable to string
void convert(float data, char *value){
  dtostrf(data, 7, 3, value);
}

// Saves all data on database
void sendData(){
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password)){
    delay(500);
    Serial.println("Starting SQL!");
    Serial.println(INSERT_SQL);
    my_conn.cmd_query(INSERT_SQL);
    Serial.println("Query Success!");
    my_conn.disconnect();
    Serial.println("\n");
  } else {
    Serial.println("Connection failed!");
    Serial.println("Make sure all cables are properly connected!\nIf they are, restart the Arduino!\n");
  }
}

// Returns the temperature from one DS18S20 in degree Celsius
float getTemp(){
  byte data[12];
  byte addr[8];
  if (!ds.search(addr)) {
      // No more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }
  ds.reset();
  ds.select(addr);
  ds.write(0x44,1);
  // Start conversion, with parasite power on at the end
  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad
  for (int i = 0; i < 9; i++) { // We need 9 bytes
    data[i] = ds.read();
  }
  ds.reset_search();
  byte MSB = data[1];
  byte LSB = data[0];
  float tempRead = ((MSB << 8) | LSB); // Using two's complement
  float TemperatureSum = tempRead / 16;
  return TemperatureSum;
}

Now, how can I connect to a server using the URL? Is there a library like MySQL Connector that allows me to use the URL instead of the IP address?

All I want is to do exactly the same thing that I'm doing with MySQL Connector, but using the URL of the server instead of the IP address.

You are using DHCP, so this step might be optional.
Specify your network addresses (actually we want to specify DNS only but have to specify IP in 2nd argument, so likely have to specify gateway and subnet too):

IPAddress dns_addr( 8, 8, 8, 8); // GOOGLE DNS server, could be any DNS
IPAddress gateway_addr( , , , );   // put your gateway addr
IPAddress ip_addr( , , , );   // put your IP addr
IPAddress subnet( , , , );   // put your subnet mask

void setup(){
                  Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, subnet);...

Now you could modify Connector::mysql_connect method (or create new method) as follows (only function declaration is changed, body is not):

boolean Connector::mysql_connect(/*IPAddress server*/const char *server, int port, char *user, char *password)
{
  int connected = 0;
  int i = -1;

  // Retry up to MAX_CONNECT_ATTEMPTS times 1 second apart.
  do {
    delay(1000);
    connected = client.connect(server, port);
    i++;
  } while (i < MAX_CONNECT_ATTEMPTS && !connected);

  if (connected) {
    read_packet();
    parse_handshake_packet();
    send_authentication_packet(user, password);
    read_packet();
    if (check_ok_packet() != 0) {
      parse_error_packet();
      return false;
    }
    print_message(CONNECTED);
    Serial.println(server_version);
    free(server_version); // don't need it anymore
    return true;
  }
  return false;
}

Modify the header file also:

boolean mysql_connect(/*IPAddress server*/const char *server, int port,
                                 char *user, char *password)

Now you can supply URL:

if (my_conn.mysql_connect("http:\\www.mysqlserver.com", 3306, user, password))...


Arduino and ESP8266 Two-way Communication I've searched the internet quite a bit and all I find is how to make two esp8266 communicate. What I am trying to do is connect a single esp8266 to the arduino and have a two-way communication between them.

I want to send and receive data on both the Arduino and ESP8266. The concept is to send data to the esp8266 over WiFi connection and then send that data to the Arduino. The Arduino will manipulate it and send it back over WiFi.

I feel like this would be a common beginner example to have a two-way communication over a TX/RX connection, but I can't seem to find any. All examples I find are strictly one as sender and other as receiver.

See How can I verify that my ESP8266 is working? asked 2 hours before.

use something like https://www.sparkfun.com/products/12009 or https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion

Usual way is let the Arduino direct the ESP, but if you are able to program ESP too, then any communication can work the same way as between twou ESPs or two Arduinos (with the level shift in mind)


Arduino ,How I can see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0,A1.. pins I am working in my project and I want to see the output of my sensors as (0 or 5).
The maximum read was 770 and the minimum read was 0. So, how can I see the  value (0 or 5) on my screen, where I connected my sensors output to analog input A0, A1 pins.
I did the following code, but it didn't work:

void setup(){
Serial.begin(9600);
}
void loop()
{
if (analogRead(0)<385)
      Serial.print("0");
 else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(1)<385)
      Serial.print("0");
   else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(2)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(3)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(4)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(5)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

delay(1500);
}

Note: I have 5 light sensors in my circuit.

You can use DigitaRead command instead of analogread. It will give result in only 1 or 0. Hopefully this will help you.


multiple definition of local variable in linking I am trying to make my own library and it uses some local variables with the same name as some variables in ino. Compiler complains about it. I stripped it to (nonsence but simple) example

mylib.h:

#ifndef MYLIB_H
#define MYLIB_H
int doit();
#endif

mylib.cpp:

#include "mylib.h"
int value;
int doit(){
    return value++;
}

example.ino:

#include "mylib.h"
int value;
void setup(){
    value=3;
    pinMode(13,OUTPUT);

}
void loop() {
    digitalWrite(13,(value==doit()) );
}

compiling:

$ make
/usr/bin/avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p example.o mylib.o .lib/arduino.a -lm -o example.elf
mylib.o:(.bss.value+0x0): multiple definition of `value'
example.o:(.bss.value+0x0): first defined here
collect2: error: ld returned 1 exit status
/home/gilhad/GIT/HW/Arduino/minipro//../Arduino.mk:436: recipe for target 'example.elf' failed
make: *** [example.elf] Error 1

I am not usint the value in the .h file, so why it collides with similary named variable from another module?

Should not be it private to the module until exposed via .h file?

The common practice is to write Arduino libraries using C++ classes:

  The core of the header file consists of a line for each function in
  the library, wrapped up in a class along with any variables you need.

class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

In this way you can specify what is private (variables and methods only seen within the class) and what is public (variables and methods that can be seen outside the class).  In the given example, the variable called "_pin" is private to the class Morse.

In your case, you would want to make a private class variable called "value".  Because it is private, you are free to re-use the name when not inside the class.


Help with wiring? Fritzing example inside I am trying to prep my wiring for a 8x8 Led Matrix w/ Bluetooth according to the following instructable:

http://www.instructables.com/id/Arduino-SPI-7-Bi-color-LED-Matrix-Scrolling-Text-D/?ALLSTEPS

Instead of soldering everything together I'd much rather use a breadboard. I'm new to wiring, breadboards, and Arduino's in general. I was wondering if anyone could look over my sketch and see that the connections I've made are valid.

I'm basing my wiring off this image (See original instructable for higher resolution):

I realize the bluetooth module isn't the same. I'm just using this as a reference. The wires leading off the top of the board will be going to the LED Driver module.

EDIT: Thanks for the feedback guys. I have decided to go with the Innogear HC-05 module. I've adjusted the wiring according to that model.
As per the suggestions, I've switched my power and ground rail and eliminated the resistors and ground for TX communication. (I've still kept a ground for the BT).
Here's my new attempt:

Those are, in fact, the same board. When you look at this image (from Amazon)...

...you can see that there are really six pins, just two of them aren't soldered.

Your circuit:

On the power rails, you have the 5V and ground switched. It'll work okay, but you're asking for trouble later on when trying to work with it and accidentally plugging a wire into the wrong rail.
Also, from the reviews on Amazon, it says that it can be powered with 5V since the breakout board provides voltage conversion. However, no one specifically mentions the TX/RX, so I'd not risk it. This module (seems to be same chip) costs less and a reviewer specifically says that it converts voltage for both power and the TX/RX.

I'm not going to verify the resistor values, since you don't seem to need them if you get the other module I listed.
If you still did want to do the 5V/3.3V conversion, you should connect the power wire to the 3.3V pin, not the 5V rail on the breadboard

tl;dr: it seems as you just need to skip the resistors for the yellow wire and make a direction connection. I'm not 100% sure about that specific part but there was another one that a reviewer specified that this was okay.

Note: I cannot comment on the other wires for the shields, but at a quick glance it looks good.


RF transmitter with external 8-12v power not working properly So I have this pair of transmitter and receiver

RPI is powered by USB from laptop
Transmitter is connected to Attiny85 being interfaced from RPI at 3v3
Receiver is connected to Arduino at 5v

If I have transmitter VCC connected to RPI 5v, data pin to Attiny85 running at 3.3v and all of them having same ground - all works fine, but obviously range is not great.
At this point same ground connects: transmitter, Attiny, RPI.

So I've tried using external power supply for transmitter.

I have power brick with DC output running at 12v

DC output positive goes to VCC, negative to common ground.
At this point same ground connects: transmitter, Attiny, RPI, power brick.
This doesn't work at all, receive nothing.

I have YwRobot breadboard power, which is broken and now supplies 8v on 5v pins

I've connected same power brick DC output to YwRobot DC in, positive 5v from board (actually pushing 8v) goes to VCC, negative from board goes to common ground.
At this point same ground connects: transmitter, Attiny, RPI, YwRobot.
This setup transmits data some times, still worse results than connecting VCC to RPI 5v.

Am I missing something? Does external power supply has to be something specific? I've thought as long as grounds are connected any power supply can be used on transmitter.

Update:
This 433MHz transmitter with PCB integrated antenna from my thermostat (powered by 2xAA) has no problem penetrating 3 walls and floor in my house. Sorry for my ignorance, but I need to achieve similar form factor and performance. 2.4GHz modules also require a lot of pins limiting what else can be done with Attiny85.

Update:
Attiny is using manchester and software serial (part of Arduino IDE) on attiny core.
RPI is using serial, not sure which version, installed using sudo apt-get install python-serial

Those 433MHz modules are tricky. I got the best results with 3V3 on the receiver, and 5V on transmitter. You should add an external antenna.

While it would be prudent to remove the little loop antenna, you don’t need to. I got an okay signal at 25 meters with line-of-sight. Metal, or brick will block the signal even at a meter or so - there’s no penetration. Consider a 2.4GHz module for high penetration at low range, or a LoRa module for high range (up to 10km).

A 433MHz antenna I’ve used with good results (can be cut for any frequency really)

Use the same material for both antenna and radials - copper is good - and optionally stiffen the radials with bicycle spokes on the inside ... make sure there is no electrical contact between the radials and the spokes; tape or heatshrink tube. I found coax cable to suck hard for this application, so I recommend using shielded headphone wire or something similar... just connect the shield to 0V/GND.

As for your breakout power module, I’ve had the same issue. Those modules are dangerous, avoid them. Use 7805 and LM1117 instead. Or just one 5V source (your powerbank?) and a TO-92 LM317 set to 3V3 output (max 100mA). Tiny 3V step-down converters like this can supply 800mA.
https://m.banggood.com/5V-To-3_3V-DC-DC-Step-Down-Power-Supply-Buck-Module-AMS1117-800MA-p-933674.html
( you can find them a lot cheaper )


Why should a pin be set as an input if it can read input when set as output? I recently created a circuit to read the value from two sets of buttons using only two analog pins. It involves setting one pin HIGH and reading the input on the other pin and then swapping. With both pins set to OUTPUT I can still read in values with analogRead() without having to keep switching pin modes.

My question is why is that the case? What is the point of setting a pin to INPUT if OUTPUT can still read in values? Are there any disadvantages of doing so?

The reason for this is because analogRead() has absolutely nothing to do with what mode the pin is in.  That mode only has any meaning in the scope of digital operations - i.e., when using digitalRead() and digitalWrite().  When using analogRead() the Arduino code switches the pin into analog mode first and then reads from it.


What does 16u and 128u mean? The below is a snippet of a code for operating SI4455 Rf module with Arduino. I have some doubts which I'd like to seek some help in clearing.

byte numOfBytes = *pSetPropCmd++;

    if (numOfBytes > 16u) // What does this 16u mean?
    {
        /* Initial configuration of Si4x55 */
        if (SI4455_CMD_ID_WRITE_TX_FIFO == *pSetPropCmd)
        {
            if (numOfBytes > 128u) // What does this 128u mean?
            {
                /* Number of command bytes exceeds maximal allowable length */
                return SI4455_COMMAND_ERROR;
            }

            /* Load array to the device */
            pSetPropCmd++;
            WriteEZConfigArray(numOfBytes - 1, pSetPropCmd);

            /* Point to the next command */
            pSetPropCmd += numOfBytes - 1;

            /* Continue command interpreter */
            continue;
        }

In the above snippet, what does 16u and 128u mean?. I think its meaning u for unsigned, but still not clear as what does 16u and 128u mean.

Rgds
VD

It means that it is a unsigned value. Because the compiler checks for signed and unsigned in the same operation this is used (amongst others) to avoid warnings.

This is explained on stackoverflow here https://stackoverflow.com/questions/14844119/define-foo-1u-2u-4u-what-does-1u-and-2u-mean


Possible configure ESP8266 as wifi shield for Arduino? I know there's sketch to make ESP8266 becoming a simple web server. ESP8266 is cheap, small and consume less power compared to a Arduino Wifi shield.

Due to a more complex functionality requirement, I wish to place the web server code inside the Arduino itself (UNO, Nano or Pro Mini maybe). Is it possible to do this by configuring ESP8266 as a wifi bridge/shield to the Arduino? Or some mechanism methods which can route network traffics from ESP8266 to/from Arduino?

Updated
It connected to 4 relays & one I2C RTC DS1307.
It needs to sync RTC time with NTP server, and implement a web server which allows on-demand turn on/off each individual relay or by scheduling (e.g: turn on/off different relay at particular time of day). If RAM spaces allows, would like to implement a password access scheme for the web server as well

The ESP has 40 kb of ram and the average SPI flash rom used by ESP modules have 1 ~ 8 MB of code space. The average Arduino has much less of both. Uno R3 has the ATMega328, with 2kb of SRAM and 32kb of code space. Your trying to drive a truck with a mini cooper engine.


Controlling relays with IR and button What I have:

1 x 8 channel relay
1 x IR receiver
1x Arduino Uno
1x momentary switch
1x breadboard
1x 10K resister

I think the wiring is all ok as for the most part things are working as they should..ish.

Just a few bugs I need to fix.

The goal was to toggle just 2 relays (at the moment) on/off with the hardwired switch and individually toggle the a relay using an IR remote control.

Like I said this sort of works....

If I press the momentary button it does indeed toggle both relays...yeah!
then as long as the 2 relays are toggled to the on position by the momentary switch I can toggle each relay using buttons on a remote.

However if I turn the relays off with the momentary button I can't turn them on with the remote. Also if I turn off one of the relays with the remote and then press momentary switch it alternates the toggle between the 2 relays rather than just turning the other one off.

I have been using various example sketches to achieve all this and just trying to stitch them together as best I can but something is telling me that the approach is all wrong and that I should maybe be looking into Boolean's perhaps?

Hope you can shed some light on this for me.

#include <IRremote.h>
#define irPin 8
IRrecv irrecv(irPin);
decode_results results;
const int buttonPin = 2;
const int relay1 = 13;
const int relay2 = 12;
int relay1State;
int relay2State;
int buttonState;
int lastButtonState;
long lastDebounceTime = 0;
long debounceDelay = 50;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(buttonPin, INPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
}

void loop() {
  if (irrecv.decode(&results)) {
    switch (results.value) {
      case 0xFF30CF:
        Serial.println("Button 1 Pressed");
        relay1State = ~relay1State;
        digitalWrite(relay1, relay1State);
        delay(250);
        break;
      case 0xFF18E7:
        Serial.println("button 2 pressed");
        relay2State = ~relay2State;
        digitalWrite(relay2, relay2State);
        delay(250);
        break;
    }
    irrecv.resume();
  }

  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        relay1State = !relay1State;
        relay2State = !relay2State;
      }
    }
  }

  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
  lastButtonState = reading;
}

So according to your comments this should be the code if no mistake was made

#include <IRremote.h>
#define irPin 8
IRrecv irrecv(irPin);
decode_results results;
const int buttonPin = 2;
const int relay1 = 13;
const int relay2 = 12;
int relay1State = 0;
int relay2State = 0;
int masterState = 0;
int buttonState;
int lastButtonState;
long lastDebounceTime = 0;
long debounceDelay = 50;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(buttonPin, INPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
}

void loop() {
  if (irrecv.decode(&results)) {
    switch (results.value) {
      case 0xFF30CF:
        Serial.println("Button 1 Pressed");
        relay1State = !relay1State;
        digitalWrite(relay1, relay1State);
        delay(250);
        break;
      case 0xFF18E7:
        Serial.println("button 2 pressed");
        relay2State = !relay2State;
        digitalWrite(relay2, relay2State);
        delay(250);
        break;
    }
    irrecv.resume();
  }

  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        masterState = !masterState;
        relay1State = masterState;
        relay2State = masterState;
      }
    }
  }

  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
  lastButtonState = reading;
}

what I've done is create a masterState that only changes whenever you press the buttonPin and by pressing it will also change both relays to the value of new masterState independently of their actual state.

Another advice: is a bad practice to not initialize variables before use, because when you declare it is not granted that they are automatically equal to zero.


Arduino Due as Triggered DMA SPI Slave is possible? Is it possible for arduino Due to act as DMA-SPI-slave device which can exchange SPI data (uint16_t TX[10] and RX[10]) in triggered slave mode?

I have a setup in which time period is very short (~500uS/cycle). so I need to exchange data with another Microcontroller (acting as 'Master') within the mensioned time limit. Some other tasks are also to be processed. This is why I have to go for DMA and fast data transfer without intervension of processor. All the codes available are to be used in Master mode of SPI. Not a single one is in SLAVE mode.
I wrote a code but I cannot implement a transfer triggered by SPI hardware. Also how to implement data transfer complete Interrupt after all 10 datas(16bit) have been transferred and received?
Here is my initialization code:

    void DMAslaveBegin()
{
    // Configure the pins for SPI in peripheral mode
    PIO_Configure(
        g_APinDescription[PIN_SPI_MOSI].pPort,
        g_APinDescription[PIN_SPI_MOSI].ulPinType,
        g_APinDescription[PIN_SPI_MOSI].ulPin,
        g_APinDescription[PIN_SPI_MOSI].ulPinConfiguration);
    PIO_Configure(
        g_APinDescription[PIN_SPI_MISO].pPort,
        g_APinDescription[PIN_SPI_MISO].ulPinType,
        g_APinDescription[PIN_SPI_MISO].ulPin,
        g_APinDescription[PIN_SPI_MISO].ulPinConfiguration);
    PIO_Configure(
        g_APinDescription[PIN_SPI_SCK].pPort,
        g_APinDescription[PIN_SPI_SCK].ulPinType,
        g_APinDescription[PIN_SPI_SCK].ulPin,
        g_APinDescription[PIN_SPI_SCK].ulPinConfiguration);
    PIO_Configure(
        g_APinDescription[PIN_SPI_SS0].pPort,
        g_APinDescription[PIN_SPI_SS0].ulPinType,
        g_APinDescription[PIN_SPI_SS0].ulPin,
        g_APinDescription[PIN_SPI_SS0].ulPinConfiguration);
    //pmc_enable_periph_clk(ID_SPI0);
#if USE_SAM3X_DMAC
    pmc_enable_periph_clk(ID_DMAC);
    DMAC_Disable();
    DMAC->DMAC_GCFG = DMAC_GCFG_ARB_CFG_FIXED;  //Fixed priority arbiter
    DMAC_Enable();

#if USE_SAM3X_BUS_MATRIX_FIX    // not active here
    MATRIX->MATRIX_WPMR = 0x4d415400;
    MATRIX->MATRIX_MCFG[1] = 1;         //Single Access
    MATRIX->MATRIX_MCFG[2] = 1;         //Single Access
    MATRIX->MATRIX_SCFG[0] = 0x01000010;
    MATRIX->MATRIX_SCFG[1] = 0x01000010;
    MATRIX->MATRIX_SCFG[7] = 0x01000010;

#endif  // USE_SAM3X_BUS_MATRIX_FIX
#endif  // USE_SAM3X_DMAC
    //  initialize SPI controller - Slave mode
    SPI.begin(_pin);
    SPI_Disable(SPI0);
    REG_SPI0_CR = SPI_CR_SWRST;     // reset SPI
    REG_SPI0_CR = SPI_CR_SPIEN;     // enable SPI
    REG_SPI0_MR = 0x10;              // DLYBCS=0, PCS=0, MODFDIS=1, PS=0, MSTR=0(slave)
    REG_SPI0_CSR = 0x80;            // DLYBCT=0, DLYBS=0, SCBR=0, 16 bit transfer, Mode 0/1
    REG_SPI0_IDR = ~SPI_IDR_RDRF;
    REG_SPI0_IER = SPI_IDR_RDRF;
    NVIC_EnableIRQ(SPI0_IRQn);
    SPI_Enable(SPI0);
}

Is this a valid condition for DMA?
How can I utilize SPI ISR handler like system in DMA for my code so that the complete transaction (simultaneous Transmit & Receive) becomes fully automatic without processor utilization?

I think I have discovered a solution while searching:
https://github.com/avrxml/asf/blob/master/sam/drivers/spi/spi_dmac_slave_example/spi_dmac_slave_example.c

It is an example for atmel's sam3X8EK. But the MCU cores are same. Though the code serves different purpose, we can manage to mold it in the direction we need.
Only thing remained to do is to push an array through it.
Fellows, what do you think?


Reconnect to I2C with a different address (ATTiny85) My project requires to reconnect to an I2C bus as a slave. I can't reset my ATTiny physically because I2C + my project + a pin to trigger the reset isn't possible due to the limited amount of pins available on the ATTiny85. I searched the reference and different forums. If there was an answer to my question, I couldn't find one.

Thanks in advance.

(I want to try to make a plug-and-play kind of experience with a product. I want the chip to join with a defined address (100 or so), get a new address from the master and then reconnect to the I2C bus).

You only need to reinit the I2C slave.

The TinyWireS lib I found lets you just call TinyWireS.begin() with the new slave address. Though it doesn't have a way to stop the I2C connection. But the lib is hackable enough that with the ATTiny's specsheet you can add an end() to it.

However I believe that it may be better if the newly connected ATTiny acts as a master first and requests a free address from a known fixed slave acting as a dhcp server.


Quaternion values from BNO055 not available I am trying to obtain Quaternion values from a BNO055 connected to ESP32-PoE board by Olimex.

Code

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup() {
  // put your setup code here, to run once:
  Wire.begin(13, 16, 400000);
  Serial.begin(115200);

  if (!bno.begin()) {
    Serial.println("No BNO055 Detected!");
    while(1);
  }
  delay(100);
  bno.setMode(Adafruit_BNO055::OPERATION_MODE_NDOF_FMC_OFF);
  bno.setExtCrystalUse(true);
}

void loop() {
  // put your main code here, to run repeatedly:
  imu::Quaternion quat = bno.getQuat();
  imu::Vector<3> euler = quat.toEuler();

  Serial.print("W: ");
  Serial.print(quat.w());
  Serial.print(F(" "));

  Serial.print("x: ");
  Serial.print(quat.x());
  Serial.print(F(" "));

  Serial.print("y: ");
  Serial.print(quat.y());
  Serial.print(F(" "));

  Serial.print("z: ");
  Serial.print(quat.z());
  Serial.print(F(" "));

  Serial.print("X: ");
  Serial.print((float)euler.x());
  Serial.print(F(" "));
  Serial.print("Y: ");
  Serial.print((float)euler.y());
  Serial.print(F(" "));
  Serial.print("Z: ");
  Serial.print(float(euler.z()));
  Serial.print(F(" "));
  Serial.println("");
  delay(200);
}

output

W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00

The sensor seems to be working since I tried a simple script and the values are avaiable.

Is there some specific setting missing during setup() in order to obtain Quaternions.

Purpose

For Absolute orientation, the Quaternion values need to be converted to Euler .

Apparently in the setup() it is preferable to have a delay(1000) as opposed to delay(100).

Code

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
#include <math.h>

#define DEG (180/M_PI)

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup() {
  // put your setup code here, to run once:
  Wire.begin(13, 16, 400000);
  Serial.begin(115200);

  if (!bno.begin()) {
    Serial.println("No BNO055 Detected!");
    while(1);
  }
  delay(1000);
  bno.setMode(Adafruit_BNO055::OPERATION_MODE_NDOF_FMC_OFF);
  bno.setExtCrystalUse(true);
}

void loop() {
  // put your main code here, to run repeatedly:
  imu::Quaternion quat = bno.getQuat();
  imu::Vector<3> euler = quat.toEuler();

//  Serial.print("W: ");
//  Serial.print(quat.w());
//  Serial.print(F(" "));
//
//  Serial.print("x: ");
//  Serial.print(quat.x());
//  Serial.print(F(" "));
//
//  Serial.print("y: ");
//  Serial.print(quat.y());
//  Serial.print(F(" "));
//
//  Serial.print("z: ");
//  Serial.print(quat.z());
//  Serial.print(F(" "));

  Serial.print("Yaw: ");
  Serial.print(euler[0] * DEG);
  Serial.print(F(" "));
  Serial.print("Pitch: ");
  Serial.print(euler[1] * DEG);
  Serial.print(F(" "));
  Serial.print("Roll: ");
  Serial.print(euler[2] * DEG);
  Serial.print(F(" "));
  Serial.println("");
  delay(200);
}


Serial communication between an Uno and an Esplora by connecting their usb ports together I’m trying to send a character message from an arduino uno to an esplora by connecting their usb ports together.  The esplora has a micro usb port, while the uno uses a usb B port.  To hooked them up, I connected a micro usb to usb A cable to a usb A to usb B cable using a female to female usb A connector.  I even hooked up the uno and esplora grounds together.  But the two boards just don’t seem to communicate.  Ordinarily when hooking up the esplora to my computer, the tx light flashes whenever sending the message and the message appears as expected on the serial monitor.  I’ve also tested sending character messages from the computer to the uno and they seem to be read as expected.  But when connecting the esplora to the uno without going through the computer, those tx lights on the esplora do not seem light up at all and the uno rx lights don’t flash either.

Any idea what could be the issue here?

It will not work. USB communication is master/slave. There must be a 'host' and a 'device'. Uno and Esplora are two 'devices'.

Connect the boards over TTL Serial. Wire Rx and TX pins together, TX to RX and RX to TX. And ground of course.

Serial on Esplora is the USB interface. In 'core' I see the Esplora has a second serial interface called Serial1. According to schematics, the RX and TX pin of Serial1 on Esplora are on LCD header as DC_LCD (RX) and RESET_LCD (TX). Use this Serial1 to communicate with Uno.

On Uno side you should disconnect the Uno from computer to not disturb the Serial interface with USB connection. Or use SoftwareSerial to communicate with Esplora and have debug prints to Serial Monitor.


What kind of Arduino should I pick for a calculator? I am planning to build a calculator using Arduino as the base. I already know C and I love low-level stuff, so I guess the software part won't be a problem.

However, I've been stuck with Arduino. What I need is something capable of doing math (as I'm not even sure if Arduino has a FPU), and it to have enough inputs for more than the basic 0-9 + - / * keys.

I am a real newbie when it comes to hardware. I don't even have the slightest clue where to start. I barely understand Arduino's specifications, which is why I'm asking here.

I want to do something more than the classic calculator, because the software part is not a problem. I just need help on which hardware should I choose; both on the 'which Arduino' and 'which accesories for the Arduino' parts.

P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

Start with the biggest (AVR) Arduino you can afford, and worry about miniaturizing it once you have the basics in place. You may find that you don't actually want an Arduino in the end, but something like the ATmega169PA instead so that you have native LCD support (instead of having to use a discrete LCD module).

  P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

Doesn't matter. Most of your x86 assembly experience will easily transfer to AVR (but not all, since the AVR core is simpler than x86).


How to implement an alternating current using only two PWM pins on STM32 Nucleo L053R8? I am an arduino rookie and definitely not an expert in electronics, even if I do know the physics that is behind it.
Before burning my object of experience, I prefer to ask my silly question to the community.

Context :

I do use a bare stm32 based Nucleo L053R8 board which is arduino compatible.
I want a 1 minute long loop during which I send a 1.5V@20mA impulsion during 1 second and a -1.5V@20mA impulsion 30 seconds later.

Question :

can I simply use and wire two arduino PWM-able pins only to implement that alternating polarity low current? Or will it fail because of unsinked current?

It's quite hard to understand what you want from your question, it's quite "woolly".

However, I will note:

It's not possible to output a negative voltage from a normal microcontroller.
Getting a specific voltage (accurately) from PWM requires good filter design and a feedback system to keep the voltage within bounds.

I say it's not possible to output a negative voltage - that is with respect to ground. Depending on what you are feeding this voltage into you may not need to reference to ground. In this case it is possible to reference the voltage to another IO pin (steady state, output, not PWM). With it set HIGH the PWM pin's filtered voltage will be below that IO pin's voltage and thus appear, with respect to that IO pin, to be negative.  With the IO pin LOW it will appear, with respect to that IO pin, to be positive.

Once you have filtered your PWM signal you will need the output voltage from it to be monitored by an analog input. That can measure the voltage and make sure that your PWM is set to the right duty cycle. Note that the required duty cycle for any one specific voltage will depend largely on the filtering and the load on the output at the time. You will most likely need some form of PID algorithm to constantly adjust the PWM duty cycle. Also remember that your measured voltage will always be with respect to groud, so you will need to subtract your output reference voltage (the output state of your reference IO pin - high or low) from your measured voltage to get the voltage as seen with respect to the IO pin.


SPI between Master arduino and Slave arduino How can I send the string from Slave SPI to Master SPI?
I want to write code in Bare Metal.
The problem which I am facing is I can't make out what will be my blocking function in Master SPI code when receiving data from slave SPI.
As my SPIF bit is cleared in MAster code as soon as I shift out SPDR register from master to receive byte which is coming from the slave.
#define spi_data_reg SPDR
//Naster read byte function
    uint8_t MA_SPI0_read_byte()
    {
        spi_port &= ~(1<<SS);
        spi_data_reg = 0;
        while(!(SPSR & (1<<SPIF)));                  //Wait until transmission complete
        return(spi_data_reg);                                 //Return received data
       spi_port |= (1<<SS);
    }

    //Slave send byte function
    void SL_SPI0_send_byte(uint8_t data)
    {
        spi_data_direc=(1<<MISO);   //MISO as OUTPUT
        spi_data_reg = data;
        while(!(SPSR &(1<<SPIF)));
    }

Feel free to take a look at my YouTube videos. They are not monetized so I'm not self-promoting. You can even skip the videos and checkout my GitHub repo with the Master and Slave sketches.
https://youtu.be/A9oSX_dwJKQ
https://youtu.be/PSUzhCtNRRQ
https://github.com/linhartr22/Arduino_SPI_Master_Slave_Demo


Strange characters after typing an AT command in serial monitor I'm trying to test AT commands (I am working with an  Arduino Uno and a GSM/GPRS SIM900  shield; my system is ubuntu 14.10) . Yesterday when I was testing , all  ran well.. For example after typing AT+SAPBR=3,1,"APN","ooredoo" in the serial monitor it  showed me OK.. but But now it  shows me strange  characters.

This is my code

    #include <SoftwareSerial.h>
    SoftwareSerial GPRS(2,3);

void setup() {
  // put your setup code here, to run once:
 GPRS.begin(9600);
  Serial.begin(9600);
 Serial.write("start");

}

void loop() {

  // put your main code here, to run repeatedly:
     while(GPRS.available())
     Serial.write(GPRS.read());

  while(Serial.available())
    GPRS.write(Serial.read());

}

And this it is the result of AT+SAPBR=3,1,"APN","ooredoo" typed in the serial monitor

Thank you for helping me

for those who have this issue, i resolve this by changing the speed baud of my GPRS Shield :

GPRS.begin(2400);
Serial.begin(9600);

and if you want to test AT command directly on the serial monitor you must use 2400 anywhere

GPRS.begin(2400);
    Serial.begin(2400);

and don't forget to change also  the speed on the serial monitor to 2400
I hope this will help someone


Using an Arduino as a electrical mains switch How do I make an electrical switch using Arduino, that when it receives signal (wirelessly or through a LAN port) to switch off it disconnects the switch and then again told to turn on turns the switch on?

The main problem I am facing is that I need to give a 5V output to turn off the transmission between two wires having voltage rating of 230V.

You need to use Relays.  There all kind of relays.

Regular and Solid state ... for controlling a Regular Relay using Arduino you will need a transistor (so you will able to provide the right current to the relay to close a circle)

There are a lot of guides for Arduino and Relays (for example)


How does the microcontroller know which clock to use? I had seen some tutorials on how to assemble an Arduino on a breadboard. They all just place the external crystal oscillator according to the circuit and then, just burn the bootloader and it starts working. According to my little knowledge the fuse bits have to be set before using the external clock.

My question is - How does the microcontroller know which clock to use internal or external? Is there any setting already in the bootloader that tells the microcontroller to use the external clock?

Burning the bootloader via the Arduino IDE also sets the fuse bits according to its configuration files.


ESP8266 Nodemcu create custom PWM with 1.25us resolution I am trying to control some SMD LEDs WS2812B with the ESP8266-Nodemcu. I am using Arduino environment for coding. Actually I am trying to accomplish a PWM  that is precisely able to:

Go High for 850ns and then
Go Low for 400ns

According to the Spec this, this High Low change is considered as a bit with value 1.

I have tried to delay between the lows and highs, without an effort (delays only work for microseconds and above i suggest).

Do you have any idea how to accomplish that?

According to §1.7 (Pulse-Width Modulation) of espressif.com's ESP8266 technical reference document, “PWM frequency range is adjustable from 1000 μs to 10000 μs, i.e., between 100Hz and 1 kHz.”  That range is shown in other sections of that reference, and in other ESP8266 documents as well.  I don't know whether that range reflects any hardware limitations, or whether the PWM APIs enforce such limits or can be operated outside them.

Depending on what your intent is, you might instead consider use of UART capabilities.  For example, if you set the UART data rate to 2.5 MHz and transmit a 110110110... binary pattern synchronously, you will have 800 ns high alternating with 400 ns low.  [I've seen references to use of USARTs on ESP8266's but don't know with certainty whether synchronous protocol actually is supported.]

The I2S subsystem mentioned in §1.5 and described in §10 of the technical reference document also may be able to generate a bit stream as desired.  As noted in §10.2.1.5 one six-bit field selects an input clock prescale factor, and another six-bit field is used as the frequency divider of the communication clock signal.

Edit 1: As noted in cranphin's comments, cnlohr's esp8266ws2812i2s github page provides code that uses the I²S subsystem and DMA to drive WS2812 LED units.  Using DMA (direct memory access, ie transfer of memory data under control of a subsystem other than the CPU) means that once the CPU has set up a data buffer for a new display, it can turn actual transmission of the buffered data over to I²S / DMA and then go on with unrelated tasks while transmission occurs.  Note, cnlohr's page links to a youtube video that illustrates and briefly explains the process.


Trouble reading LM35 with long (?) Ethernet connection I have a quick question to ask.
I have an Arduino Uno reading 4 temperature sensors (LM35) in 4 different rooms. What happens is that the two nearest rooms give stable values, while the two further ones give very unstable measurements (the temperature keeps floating +-30C around the real values.)

I have connected all the sensors with Ethernet cables with the longest one being about 8-10m.

Is this problem due to noise picked up along the line? There are no strong electromagnetic sources along the way.
I have also measured the voltage values on Arduino end with a multimeter: the values are all stable (and correct) and do not reflect the behaviour detected by Arduino.

Also, I have tried to substitute the LM35 in the farthest room with a photoresistor (the one in the starter kit) and this time the values read by Arduino are perfectly stable. I know that the LM35 works because I have tested it on a breadboard.

Can someone give my some help? Any idea is greatly appreciated.

Edit: I am adding a sketch, although it is a very basic setup:
The only difference with the real layout is that there is also a Ethernet shield.

The LM35 has trouble driving any kind of capacitive load, so the long runs of cable are generally not a great idea if you are relying on a voltage signal. The datasheet for it (The one I have is from the Texas Instruments website), has a few strategies to reduce this problem somewhat.

The approach that I have used successfully, is to use a current signal, rather than a voltage signal. This has the advantage that you only need a two wire twisted pair cable (I made my own twisted pairs - it is easy for relatively short runs).

The idea is that you connect the LM35 output to the ground pin with a known resistor value (the datasheet example has a 200 Ohm resistor). Since the voltage is 10mv per degree, the current wil be 10/R mA per degree. There will be an additional small current from the LM35 device itself, but this is small, and almost constant. Then connect the supply and ground to one end of your twisted pair.

At the other end, it is necassary to convert the current signal back to a voltage so that your Arduino can read it. Simply put a resistor (again, 200 Ohms is that used in the datasheet example) between the low side of the twisted pair to OV, the high side connected to 5V, and measure the voltage across this resistor.

Figure 17 in the TI datasheet is the one to follow.

Other things that help to get more stable, acurate readings;

Choose a time to take readings when you are not running anything else that might interfere (wireless comms, ultrasonic sensors, motors, solenoids, etc).

Take several readings. Ignore the first two.

Take the median value of the remaining readings (eg take 5 readings, ignore the first two, and sort the others in order. Then take the middle value.).

Hope this helps.