text:
Compute yaw from magnetometer and accelerometer
I use an Arduino and a 9 DOF sensor (gyroscope, accelerometer and magnetometer) and I'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity.
I managed to correctly compute pitch and roll (the z and x axis in unity) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my yaw too, in a weird way.

Code in the arduino to get the heading
void getHeading(void)
{
  heading=180*atan2(Mxyz[0],Mxyz[1])/PI;
  if(heading <0) heading +=360;
}

void getTiltHeading(void)
{
  //float pitch = asin(-Axyz[0]);
  //float roll = asin(Axyz[1]/cos(pitch));
  float pitch = atan( Axyz[0] / sqrt( Axyz[1] * Axyz[1] + Axyz[2] * Axyz[2] ) );
  float roll = atan( Axyz[1] / sqrt(Axyz[0] * Axyz[0] + Axyz[2] * Axyz[2]));

  float xh = Mxyz[0] * cos(pitch) + Mxyz[2] * sin(pitch);
  float yh = Mxyz[0] * sin(roll) * sin(pitch) + Mxyz[1] * cos(roll) - Mxyz[2] * sin(roll) * cos(pitch);
  float zh = -Mxyz[0] * cos(roll) * sin(pitch) + Mxyz[1] * sin(roll) + Mxyz[2] * cos(roll) * cos(pitch);
  tiltheading = 180 * atan2(yh, xh)/PI;
  if(yh<0)    tiltheading +=360;
}

Pitch and roll
    float _Pitch  = (float)(180 / Math.PI * Math.Atan( m_ResultX / Math.Sqrt( m_ResultY * m_ResultY + m_ResultZ * m_ResultZ ) ) );
    float _Roll = (float)(180 / Math.PI * Math.Atan(m_ResultY / Math.Sqrt(m_ResultX * m_ResultX + m_ResultZ * m_ResultZ)));
    float _Yaw = (float)(m_TiltHeadingResult);

Don't hesitate to ask for details.

did u figure out why your yaw changes if you pitch/roll the sensor? and how was it addressed? any information would help me too.

I don't know how all your sensor's axis are lined up, but it looks like you should level the magnetometer readings by rotating them by -pitch and -roll to get back to the global reference frame, instead of rotating the magnetometer readings by the positive angles.
However, The pitch and roll angles in the code are both relative the horizon, not a set of euler angles that define a rotation between two states; because of this, they do not compose to rotate the magnetometer back into the global xy frame like I assume the equations are trying to do. The code is also only using atan for pitch and roll instead of atan2, so their range is only 180 degrees.
You need to make sure the rotation matrix you multiply your magnetometer reading by is based on the same conventions as the equations you use to get pitch and roll from the accelerometer, and that it cancels the observed rotation.
To do this correctly, I recommend you read into euler angles. You might also try searching around for a good library that handles 9-DOF sensor fusion for you.

I've read a bit about the euler angles but my math isn't that great nor had I time to investigate further but I managed to find a very good 9-DOF sensor fusion. Everything is ok now.

Would you provide a link to the sensor fusion you used?


text:
Do I need a lot of Arduinos?
I would like to make a smart home using Arduino. My system must be wireless. I want to control power outlets and lamps and I want to be able to turn off and on power outlets and lamps wirelessly, using my android app, using nRF24L01.
Do I need an Arduino for each power outlet and lamp? Do I need to put an Arduino, nRF24L01 and relay inside each power outlet and lamp?

Might I suggest using off the shelf remote controller power outlets. You can control these outlets using a single 433mHz transmitter. Probably about the same price as an Arduino+NRF24+AC-DC adapter+Relay, and already in a convenient package. They are also available in lamp socket. It also means you don't have to touch AC-mains.

You might also consider using ESP8266 + relay combinations, instead of Pro Mini + nRF24L01 + relay sets.  An Arduino IDE setup is available to support C code on ESP8266 systems (1,2,3).
Note:  As a consequence of its higher clock speed and larger RAM size (80 MHz or 160 MHz clock, and 80 KB DRAM, vs Mini's 16 MHz clock and 2 KB SRAM) a typical ESP8266 board uses more power than a Pro Mini + nRF24L01 does.  According to nrqm.ca/nrf24l01, the nRF24L01 draws around 11 or 12 mA when sending or receiving, and  22 μA in low-power standby mode.  According to wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module, an ESP8266 draws ~ 60 mA receiving and 135–215 mA sending.  (That current range covers a power output range of 5.5 dBm.  It probably supports a much bigger communication area than nRF24L01 does.)  Of course, if all your installations have mains power available, the power requirements might not matter much to you.  Note, ESP8266 boards typically run on 3.3 V power instead of 5 V power.
As far as cost goes, at the moment Pro Mini clones cost about $2.15 each.  nRF24L01's run about $0.90.  ESP8266 modules are $2–$3 depending on model and level of module (1,2).  You might save a few dollars on your whole system using ESP8266's, but the smaller-sized electronics they provide probably is more important.

One arduino can control multiple relays. Beyond that, how many you need will depend on the details of your project.
Once you have a working example, you can build it using less expensive alternatives than regular Arduino boards.

I need 22 arduino pro mini + 22 relay + 22 nRF24L01 and main arduino

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Converting float to String
How can I convert a float value into a String object without implementing any library?
I'd like to avoid using char array.

Why would you want to "avoid" a char array?  Surely the String is the one to avoid?

Why is char better than string?

Because Strings use dynamic allocation which is bad on a microcontroller with only 2K or RAM. With char you usually use static allocation and just allocate what you need. Strings are evil - a crutch for people who can't be bothered to do it properly.

I've been trying to convert integers, floats, dates and strings and String looked to be the easiest. So how can I convert all that in a char?

The conversion is the same, but the storage medium is all that is different.

So I will need a for loop to print the array?

No.  A "char array" is the native "string" format in C.  The String object is an Arduino specific wrapper around it that adds extra bloat.

What function can I use to convert from a Float? sprintf() works only for Ints

A "String object" is (implemented by) a library, so by definition, your question cannot be answered. dtostrf() will do the conversion for you.

@NickGammon, I deleted my comment.

If you want to do it manually, rather than using the standard tools (dtostrf() for example) then you need to think mathematically.
A floating point number is made up of two distinct parts - the integer part and the decimal part.
For instance the number 123.4567 is made up of the integer part 123 and the decimal part 4567.  Chopping off the integer portion is simple to do, and if that happens to be just one digit then you can simply add that as the first digit of your output.  In this case, though, it isn't.
So what to do?  Simple: keep dividing the number by 10 until it is just one digit.  But be sure to count the number of times you divide by 10.  So the example above would end up as 1.234567 with a divide count of 2.  This is the same as the scientific representation, 1.234567×10².
So now you have it divided you can chop off the integer (just cast it to an int), add that integer part to your string, then remove it from the source number.  So you end up with "1" and 0.234567 and a count of 2.
Now multiply by 10 and subtract one from your count, so you get 2.34567 and a count of 1.  Grab the integer portion and add it to your string, then remove it from your number.
Keep repeating until your count is 0, at which point you have now done all the integer portion - so you can now add a "." to your string.
You now just keep repeating the same process again and again until the absolute value of the count equals the number of decimal places you want to print.
For negative numbers you should start by placing a "-" in your string, then taking the absolute value of the number (the number as a positive).
Or you just use the standard library function dtostrf().

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Arduino Uno, Ethernet shield, MySQL
I'm trying to connect my Arduino Uno with MySQL.
This is my code:
#include <SPI.h>
#include <Ethernet.h>
#include <sha1.h>
#include <mysql.h>

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xC8, 0x0A, 0xA9, 0xAF, 0x83, 0x58 };
IPAddress server_addr(192,168,0,102);

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference
char user[] = "root";
char password[] = "fifa2005";
char INSERT_SQL[] = "INSERT INTO test_arduino.hello VALUES ('Hello from Arduino!', NULL)";

void setup() {
Ethernet.begin(mac_addr);
Serial.begin(115200);
delay(1000);
Serial.println("Connecting...");
if (my_conn.mysql_connect(server_addr, 3306, user, password))
delay(500);
else
Serial.println("Connection failed.");
}

void loop() {
}

I have the following database:
mysql> CREATE DATABASE test_arduino;
Query OK, 1 row affected (0.00 sec)
mysql> USE test_arduino;
Database changed
mysql> CREATE TABLE hello (source char(20), event_date timestamp);
Query OK, 0 rows affected (0.01 sec)

This is the output message:
Connecting... Connection failed.

I am not sure this is the right IP address: 192,168,0,102. I tried with the localhost IP address - 127.0.0.1, but nothing happened.

What kind of system is MySQL running on? E.g. Windows, Linux, MacOS?

Is 192.168.0.102 the address of the computer you're trying to connect to, or is that the address of the ethernet shield? I'm confused as to why you would try connecting to localhost...

My operating system is windows 7. 192.168.0.102  is ip adress of my laptop. At first I thought that I need to use IP address of the server but then I saw that actually need the IP address of my laptop

You need to use the IP address of the server running MySQL.

I use Apache to create a Mysql server and corresponding IP is 127.0.0.1. and it doesn't work with it. Ethernet shield and laptop are connected to the router. I think the problem is mac address or ip address which i used. I take the mac address from: cmd -> ipconfig -> Ipv4 address - 192,168,0,102. I take the mac address from : cmd -> getmac -> Physical Address.

I understand where is the problem. I have used the wrong port.I have to use port 3306 and add the following code:
'delay(500);
my_conn.cmd_query(INSERT_SQL);
Serial.println("Query Success!"); '
in the if statement

First you have to grant permission to the user!
Type the query in MySQL like:
GRANT ALL ON test_arduino.* TO root@'192.168.0.102' IDENTIFIED BY 'fifa2005';

Can't comment, so I put here. In your Arduino you shall use unique MAC address, that can't be same as in your laptop or any other node in network segment. And it can't be just any number because some bits have different meanings, so to be safe, use MAC from Ethernet shield samples (BTW in production units, MAC addresses have to be purchased, but unfortunately Ethernet shield comes without it).
127.0.0.1 is a "virtual" localhost address (alternative address used to access the services within same host), in your case you shall use MySQL server (your laptop?) host address, so
> server_addr(192,168,0,102);

is right.

authors: Γιάννης Τεβεκίδης


text:
Programming options other than C++
Can I program my Arduino using any programming language other than C++? If so, which programming languages? What software would I need for compiling and loading my code onto the Arduino?

Related: http://arduino.stackexchange.com/questions/105/programming-an-arduino-using-python-rather-than-c-c

Unfortunately, this is an effective duplicate of an non-Arduino.SE question: see here  I think the question I linked should be moved here after beta ends, but not just yet.

@anorton That question is asking about alternative IDEs. This question is not a duplicate because it talks about alternative programming languages.

@user2202326 Sorry... I seemed to recall more people responding with different languages than IDEs on that thread, but, apparently, I was wrong.  Carry on.

You could look into Netduino if you are familiar with C# (Visual Studio is the way to go, but there are other ways to compile C# code). I don't know what board you have and if it is compatible though. http://netduino.com/

Some commonly known ones:

Ada
Basic
Forth, alt, alt
Java
Pascal
Python
C (mac) and C (Windows)

In theory you should be able to extend avr-gcc to support other languages, though this is no small undertaking. I should also caveat that support for languages other than C typically comes with some fairly weighty restrictions on language components -- for instance, even with C++ it's discouraged to be instantiating new objects as malloc and free are extremely expensive in both memory space and cycles.
Besides using Google, the following references are applicable Click Here.

In theory, any compiler which outputs AVR assembly could be used (modulo limitations on code size, ram usage etc).
AVR backends exist for both LLVM and  GCC -- so in theory, with some effort, most languages which are supported by LLVM and GCC's front-ends could be compiled to AVR. A big question will be library support, etc.
Never the less, here's a couple of odd choices for the spirit of the question, rather than its letter [1].

AMForth, a forth dialect can be flashed onto an Arduino.
AVR-Ada: Ada for AVR micro-controllers.
BASIC: Bring back the Goto!

Oh, and you could write raw AVR Assembly!
[1]- I Haven't tried these though!

I'm surprised that nobody has mentioned AVR Assembly!
Assembly is not often thought to be the most interesting, or even an easy method of programming, but it's nonetheless, 100% possible with all AVR based arduino. SAM boards will likely not work with this flavor, but it's still possible to use assembly in their programming.
All Arduino boards (as of posting) support assembly programming via Atmel Studio, The SDK made for Atmel based chips.
Assembly is naitively supported by all Atmel devices, and requires no boot loader in order to work, so all programs are inherently real-time.

Note that assembly is also supported by the gcc toolchain, which is included in the Arduino IDE install.

@EdgarBonet Correct, which is why the __asm__("Assembly code here") works to add in-line assembly to any sketch. For most programs, this is a bad idea, however, as it's difficult to achieve platform independence with this method.

There are also some people working on Javascript node.js based systems. One that is already publicly available is Espruino and another is Tessel which launches in spring 2014.

Because avr-g++ should support all standard C / C++ constructs it is possible to code inline assembly. More info on this arduino.cc forum thread

Inline assembly isn't part of the C/C++ standards, but gcc and the microsoft c compiler support it, although incompatibly.

true, and so do the avr_gcc.

Nothing beats writing executable code in hex anyway.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Sending information through Bluetooth 4.0 (LE) with Tinyduino
My task is to measure distances quite rapidly and send the data to a computer. I need to do it with the following equipment:

Tinyduino Processor board
Tinyduino Bluetooth LE shield
Tinyduino Cell Battery
Ping))) Ultrasonic Distance Sensor

Distance

I have found the distance already and it is right now stored in an int.
Bluetooth

For the bluetooth I am using the BGLib
As mentioned above the distance is measured many times rapidly so I want to either transfer the data quickly or store the data somehow until measurement is done (after approximate 3 seconds). I have established connection to a connection already (GAP discoverabled undirected connectable).
Because I am using the Tinyduino Bluetooth LE shield, it already have a firmware that I cannot change. It consists of 2 charateristics: TX and RX. My problem is now I do not understand how to send the specific data to computer.
Do I need to write a response to a command by the computer, or do I send a command with the sendCommand function, or even a third?
And just another thing; is it better to store the data and wait till the measurement is over or should I try to transfer it while I measure it.
(if there are some comments you would like to know what means, just write because they are Danish)
My current code:
#include <BGLib.h>
#include <BGLibConfig.h>

#include <SoftwareSerial.h>
#include "BGLib.h"

//Uncomment denne linje for at debugge via USB
//#define DEBUG

//BLE er forkortelse for Bluetooth Low Energy

// ================================================================
// BLE FORBINDELSESTILSTAND
// ================================================================

// BLE TILSTANDSDEFINITONER
#define BLE_STATE_STANDBY           0
#define BLE_STATE_SCANNING          1
#define BLE_STATE_ADVERTISING       2
#define BLE_STATE_CONNECTING        3
#define BLE_STATE_CONNECTED_MASTER  4
#define BLE_STATE_CONNECTED_SLAVE   5

// BLE state/link status
uint8_t ble_state = BLE_STATE_STANDBY;
uint8_t ble_encrypted = 0;  // 0 = not encrypted, otherwise = encrypted
uint8_t ble_bonding = 0xFF; // 0xFF = no bonding, otherwise = bonding handle

// ================================================================
// HARDWARE FORBINDELSE OG GATT STRUKTUR SETUP
// ================================================================

#define LED_PIN 13  // Status LED-pin
#define PING_PIN 11  // Ping pin til at ultralydssensor

#define GATT_HANDLE_C_RX_DATA   17  // 0x11, supports "write" operation
#define GATT_HANDLE_C_TX_DATA   20  // 0x14, supports "read" and "indicate" operations

// Brug softwareSerial på pins D3/D4 for RX/TX (Arduino side)
SoftwareSerial bleSerialPort(3, 4);

// Opret BGLib objekt:
//  - use SoftwareSerial port for module comms
//  - use nothing for passthrough comms (0 = null pointer)
//  - enable packet mode on API protocol since flow control is unavailable
BGLib ble112((HardwareSerial *)&bleSerialPort, 0, 1);

#define BGAPI_GET_RESPONSE(v, dType) dType *v = (dType *)ble112.getLastRXPayload()

// ================================================================
// ARDUINO SETUP OG LOOP FUNKTIONER
// ================================================================

// Kør under startup
void setup() {
    // Klargør status LED
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, LOW);

    // BGLib lyttere
    ble112.ble_evt_system_boot = my_ble_evt_system_boot;
    ble112.ble_evt_connection_status = my_ble_evt_connection_status;
    ble112.ble_evt_connection_disconnected = my_ble_evt_connection_disconnect;
    //ble112.ble_evt_attributes_value = my_ble_evt_attributes_value;

    // Åben Arduino USB serial, hvis vi skal debugge
    #ifdef DEBUG
      Serial.begin(38400);
    #endif

    // Åben BLE software serial port
    bleSerialPort.begin(38400);

    my_ble_evt_system_boot( NULL);
}

// Main loop
void loop() {
    //Få afstand i microsekunder
    int *x = ping();

    // Bliv ved med at spørge efter ny data hos BLE
    ble112.checkActivity();

    // Få Arduino LED at blinke baseret på tilstand:
    //  - konstant = STANDBY
    //  - 1 puls per sekund = ADVERTISING
    //  - 2 puls per sekund = CONNECTED_SLAVE
    //  - 3 puls per sekund = CONNECTED_SLAVE med kryptering
    uint16_t slice = millis() % 1000;
    if (ble_state == BLE_STATE_STANDBY) {
        digitalWrite(LED_PIN, HIGH);
    } else if (ble_state == BLE_STATE_ADVERTISING) {
        digitalWrite(LED_PIN, slice < 100);
    } else if (ble_state == BLE_STATE_CONNECTED_SLAVE) {
        if (!ble_encrypted) {
            digitalWrite(LED_PIN, slice < 100 || (slice > 200 && slice < 300));
        } else {
            digitalWrite(LED_PIN, slice < 100 || (slice > 200 && slice < 300) || (slice > 400 && slice < 500));
        }
    }
}

int *ping()
{
    //Variabler til at lagre målte værdier
    int microseconds, cm;

    //Send ping, som bagefter skal læses
    pinMode(PING_PIN, OUTPUT);
    digitalWrite(PING_PIN, LOW);
    delayMicroseconds(2);
    digitalWrite(PING_PIN, HIGH);
    delayMicroseconds(5);
    digitalWrite(PING_PIN, LOW);

    //Aflæs tiden
    pinMode(PING_PIN, INPUT);
    microseconds = pulseIn(PING_PIN, HIGH);

    //Konverter mikrosekunder til cm. Det går 29 microsekunder pr centimeter.
    //Halver afstand, fordi vi vil ikke have afstanden både frem og tilbage, men derimod kun den ene vej.
    cm = microseconds / 29 / 2;

    #ifdef DEBUG
        Serial.print(cm, DEC);
    #endif

    return &cm;
}

// ================================================================
// APPLICATION HÆNDELSES FUNKTIONER
// ================================================================

void my_ble_evt_system_boot(const ble_msg_system_boot_evt_t *msg) {
    #ifdef DEBUG
        Serial.print("###\tsystem_boot: { ");
        Serial.print("major: "); Serial.print(msg -> major, HEX);
        Serial.print(", minor: "); Serial.print(msg -> minor, HEX);
        Serial.print(", patch: "); Serial.print(msg -> patch, HEX);
        Serial.print(", build: "); Serial.print(msg -> build, HEX);
        Serial.print(", ll_version: "); Serial.print(msg -> ll_version, HEX);
        Serial.print(", protocol_version: "); Serial.print(msg -> protocol_version, HEX);
        Serial.print(", hw: "); Serial.print(msg -> hw, HEX);
        Serial.println(" }");
    #endif

    // SYSTEM BOOT betyder at systemet er på standby
    //ble_state = BLE_STATE_STANDBY;
    // ^^^ Spring over fordi vi alligevel skifter til advertising nedenunder

    // Sæt advertisement interval to 200-300ms. Brug alle advertisement kanaler
    // (NOTE: min/max parametere er i 625 microsekunder)
    ble112.ble_cmd_gap_set_adv_parameters(320, 480, 7);
    while (ble112.checkActivity(1000));

    // USE THE FOLLOWING TO LET THE BLE STACK HANDLE YOUR ADVERTISEMENT PACKETS
    // ========================================================================
    // start advertising general discoverable / undirected connectable
    ble112.ble_cmd_gap_set_mode(BGLIB_GAP_GENERAL_DISCOVERABLE, BGLIB_GAP_UNDIRECTED_CONNECTABLE);
    while (ble112.checkActivity(1000));

    // set state to ADVERTISING
    ble_state = BLE_STATE_ADVERTISING;
}

void my_ble_evt_connection_status(const ble_msg_connection_status_evt_t *msg) {
    #ifdef DEBUG
        Serial.print("###\tconnection_status: { ");
        Serial.print("connection: "); Serial.print(msg -> connection, HEX);
        Serial.print(", flags: "); Serial.print(msg -> flags, HEX);
        Serial.print(", address: ");
        // this is a "bd_addr" data type, which is a 6-byte uint8_t array
        for (uint8_t i = 0; i < 6; i++) {
            if (msg -> address.addr[i] < 16) Serial.write('0');
            Serial.print(msg -> address.addr[i], HEX);
        }
        Serial.print(", address_type: "); Serial.print(msg -> address_type, HEX);
        Serial.print(", conn_interval: "); Serial.print(msg -> conn_interval, HEX);
        Serial.print(", timeout: "); Serial.print(msg -> timeout, HEX);
        Serial.print(", latency: "); Serial.print(msg -> latency, HEX);
        Serial.print(", bonding: "); Serial.print(msg -> bonding, HEX);
        Serial.println(" }");
    #endif

    // "flags" bit description:
    //  - bit 0: connection_connected
    //           Indicates the connection exists to a remote device.
    //  - bit 1: connection_encrypted
    //           Indicates the connection is encrypted.
    //  - bit 2: connection_completed
    //           Indicates that a new connection has been created.
    //  - bit 3; connection_parameters_change
    //           Indicates that connection parameters have changed, and is set
    //           when parameters change due to a link layer operation.

    // check for new connection established
    if ((msg -> flags & 0x05) == 0x05) {
        // track state change based on last known state, since we can connect two ways
        if (ble_state == BLE_STATE_ADVERTISING) {
            ble_state = BLE_STATE_CONNECTED_SLAVE;
        } else {
            ble_state = BLE_STATE_CONNECTED_MASTER;
        }
    }

    // update "encrypted" status
    ble_encrypted = msg -> flags & 0x02;

    // update "bonded" status
    ble_bonding = msg -> bonding;
}

void my_ble_evt_connection_disconnect(const struct ble_msg_connection_disconnected_evt_t *msg) {
    #ifdef DEBUG
        Serial.print("###\tconnection_disconnect: { ");
        Serial.print("connection: "); Serial.print(msg -> connection, HEX);
        Serial.print(", reason: "); Serial.print(msg -> reason, HEX);
        Serial.println(" }");
    #endif

    // set state to DISCONNECTED
    //ble_state = BLE_STATE_DISCONNECTED;
    // ^^^ skip above since we're going right back into advertising below

    // after disconnection, resume advertising as discoverable/connectable
    //ble112.ble_cmd_gap_set_mode(BGLIB_GAP_GENERAL_DISCOVERABLE, BGLIB_GAP_UNDIRECTED_CONNECTABLE);
    //while (ble112.checkActivity(1000));

    // after disconnection, resume advertising as discoverable/connectable (with user-defined advertisement data)
    ble112.ble_cmd_gap_set_mode(BGLIB_GAP_USER_DATA, BGLIB_GAP_UNDIRECTED_CONNECTABLE);
    while (ble112.checkActivity(1000));

    // set state to ADVERTISING
    ble_state = BLE_STATE_ADVERTISING;

    // clear "encrypted" and "bonding" info
    ble_encrypted = 0;
    ble_bonding = 0xFF;
}

/*void my_ble_evt_attributes_value(const struct ble_msg_attributes_value_evt_t *msg) {
    #ifdef DEBUG
        Serial.print("###\tattributes_value: { ");
        Serial.print("connection: "); Serial.print(msg -> connection, HEX);
        Serial.print(", reason: "); Serial.print(msg -> reason, HEX);
        Serial.print(", handle: "); Serial.print(msg -> handle, HEX);
        Serial.print(", offset: "); Serial.print(msg -> offset, HEX);
        Serial.print(", value_len: "); Serial.print(msg -> value.len, HEX);
        Serial.print(", value_data: ");
        // this is a "uint8array" data type, which is a length byte and a uint8_t* pointer
        for (uint8_t i = 0; i < msg -> value.len; i++) {
            if (msg -> value.data[i] < 16) Serial.write('0');
            Serial.print(msg -> value.data[i], HEX);
        }
        Serial.println(" }");
    #endif

    // check for data written to "c_rx_data" handle
    if (msg -> handle == GATT_HANDLE_C_RX_DATA && msg -> value.len > 0) {
        // set ping 8, 9, and 10 to three lower-most bits of first byte of RX data
        // (nice for controlling RGB LED or something)
        digitalWrite(8, msg -> value.data[0] & 0x01);
        digitalWrite(9, msg -> value.data[0] & 0x02);
        digitalWrite(10, msg -> value.data[0] & 0x04);
    }
}*/

Not an answer to your question, but your code has a potentially big issue: it is very bad programming practice to declare a variable in a function (cm in ping()) and returns a pointer to that variable (return &cm;) as its value will be overridden by the first call to any function after the return (ble112.checkActivity(); in your case). Just do return cm; in ping() instead.

Hello Highace2 have you made any headway with the tinyduino and the bluetooth Le Module? I am having a similar issue which I have posted about here please take a look I would really appreciate the help.

@har I'm afraid not. The project was submitted with an alternative solution because neither my team nor my teacher (who is a low current engineer with 10 years of experience) could get that thing working. The library is just plain rubish to people with little understanding of bluetooth 4.0 protocol (where it should be rather clear).

Highace2 thank you for your response, if you don't mind me asking what the alternative solution to your problem was? Did you still use BLE? Thank you.

@har No, we did not. Our goal was to use an accelerometer inside a plastic bottle but ended up using a range finder on top of tube in which the plastic bottle flew. That was our solution.


text:
How to connect a 12V power supply to an RGB LED strip receiving RGB values via Arduino Uno PWM pins?
Desired Behaviour
I want to send RGB values from my Arduino Uno PWM pins to an RGB LED strip.
What I've Tried
I've purchased this RGB LED strip and 12V power supply (specs below).
I'm trying to follow this adafruit tutorial but am finding the diagram references unclear.
I've mocked up a diagram but am not sure it would work:

( I haven't used the Vin pin before, so, just to be clear, that is the pin that is connected to the positive line on the breadboard - is that how to transfer the 12V power to the breadboard? )
Questions
01)  Is the above diagram safe and sound?
02)  How do I connect the power supply to the RGB LED strip?
03)  Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?
04)  I've seen references to grounding the power source, how do I do that?
05)  Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?
Printed Text on MOSFET:  IRF520 Y32K BE
MOSFET Datasheet:  Link (IRF520NPbF)
Specifications
RGB LED Strip

LED type:  5050 SMD
Color:  RGB
LED quantity:  300LED
Package:  5 Meter/REEL
Voltage:: 12V DC
Working Power:    14.4W
Working temperature: -20° to 50°
Size: ⌀180mm
Length :  5m
Life Span:    50000+hours
Weight:   0.3kg

Power Supply

Input Voltage: AC 100 - 240V
Output Voltage : DC 12V, 6A
Power : 72 Watts
Connector Size:
External Diameter: 5.5mm
Internal Diameter: 2.5mm

01) Is the above diagram safe and sound?

It looks to be OK, except one thing:
The current you can draw from the Arduino's VIN pin is limited to about 1A. That is a sixth of what your power supply can provide, and the LED strip when everything is on needs more than that (1.2A), so you could run into problems.  The limit is threefold:

The barrel jack itself is rated at up to 1A
There is a protection diode with a limit of 1A
The header pins are rated at up to 1A

And of course the Arduino itself needs to use some of that available 1A.  So you might be better off splicing your LED circuit into the power supply's wire before it enters the Arduino.

02) How do I connect the power supply to the RGB LED strip?

Power goes in (+) to the common pin of the LED strip and then out of any of the three colour pins that happen to be connected to the ground of the power supply. That is, the ground of the Arduino in your schematic since they are (as they should be) all shared.

03) Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?

Yes. There is circuitry on the Arduino that allows both the USB and barrel jack to be plugged in together.

04) I've seen references to grounding the power source, how do I do that?

That refers to connecting the external power supply's ground and the Arduino's ground together. By using the barrel jack that is all taken care of for you.

05) Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?

Not really.  They are designed to be switched with a higher voltage than the Arduino's IO pins provide.  While they will work, they may cause the LEDs to be dimmer than they should be, or the MOSFETs might get hot.  Basically a MOSFET has a "threshold" voltage range which is the voltage range at which the MOSFET transitions from off to on. That is 2V - 4V for that MOSFET, which while within the range of an IO pin isn't really that great. At 4V the MOSFET still isn't completely on. You may notice from the datasheet that the "R_DS(ON)" value - that is the resistance of the MOSFET when it is on, is measured with the gate voltage at 10V. That is a voltage where the MOSFET is guaranteed to be fully on. Anything less than that and the resistance will be higher causing more losses across the MOSFET.  I could see that instantly from the model number - it starts with "IRF".  There is a specific range from International Rectifier which is designed to be directly driven by an IO pin - these are the "IRL" (for International Rectifier Logic-level) series.  These have their R_DS(ON) values measured typically at a gate voltage of 4.5V and a threshold voltage in the region of 500mV to 1.5V. When directly driving from an Arduino these IRL (or equivalent from other manufacturers) are preferred.

It works! You have no idea how long I've been wanting to make this happen, thank you!  Soldering iron, accessories and other MOSFET's are arriving in the mail tomorrow so I can solder header pins on the LED wires and make more secure connections to the breadboard.  (These are the MOSFETS I've ordered - IRLB8721PBF - http://docs-asia.electrocomponents.com/webdocs/0f35/0900766b80f35037.pdf).

Just curious. R_DS is 0.2ohm at 10v (GS), which is pretty insignificant. Would the R_DS be so much higher that the leds will look dimmer, even at 1.2A?

Take a look at Fig3 of the datasheet and do the maths.  At 10V V_GS and 50V V_DS, R_DS calculates at around 1.6Ω. At 5V V_GS it calculates at around 11Ω. So we're talking 10x the resistance.


text:
Display issues with 4 Digit, 14 segment
I have this HT16K33 4 Digit 14-segment display I got brand new.
I connected it to my Arduino UNO, wired it up and uploaded some quick test code.
However, the display looks completely broken (see image below), only some segments turn on.

I soldered the connection pins to the HT16K33 board (see picture below). My solder isn't the best but it also shouldn't be too bad.

I did a quick resistance check on the connection pins to see if the pins were soldered correctly, and they seemed good. I'm not too sure how to test the ji2c pin though...

Here is the Wiring on my breadboard:

Finally here is the code i'm currently using:
#include "HT16K33.h"
#include <Wire.h>
HT16K33 seg(0x070);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Wire.begin();
  if(!seg.begin()){
    Serial.println("ERROR");
    while(1);
  }
  Wire.setClock(100000);

  Serial.println("displayTest()");
  seg.displayOff();
  delay(1000);

  seg.displayOn();
  seg.displayClear();
  seg.displayInt(5);
}

void loop() {
  // put your main code here, to run repeatedly:

}

I'm a bit troubled here and confused at what's going on... Help would be greatly appreciated

Can you provide a link to the used library? Have you tried the libraries example sketches? Do the shown LEDs light up right after powering or with the execution of displayInt()?

Are you sure that code example you've found matches the display module ?
That display has 14 segments plus a decimal point. The mappings between the pins of the HT16K33 and the display pins probably has no defined standard and could be completely arbitrary. Especially strange is the the '5' you intend to display appears spread over several digits. In the worst case, you are going to have to get the data sheet of the HT16K33 and the displays and work out the connections between the display pins and the HT16K33.

Do you see the "display off" state at the start of the sketch? And did you try different values for output? You might want to do investigate this systematically.

@chrisl I'm using https://github.com/RobTillaart/HT16K33 and its example demo1;

so @6v6gt's comment made me re-search for a library for a 14-segment HT16K33. It seems he/she was in the money since it started working after switching library. While I couldn't find any yesterday, I found this page today which covers 7-segment and 14-segment HT16K33:
https://learn.adafruit.com/adafruit-led-backpack/0-54-alphanumeric?view=all#library-reference-3052482
So I switched from the HT16K33 library to the "Adafruit_LEDBackpack" and "Adafruit_GFX" Libraries.

Code for those wondering:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"

Adafruit_AlphaNum4 alpha4 = Adafruit_AlphaNum4();

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

alpha4.begin(0x70);  // pass in the address

alpha4.writeDigitAscii(0, 'A');
alpha4.writeDigitAscii(1, 'B');
alpha4.writeDigitAscii(2, 'C');
alpha4.writeDigitAscii(3, 'D');
alpha4.writeDisplay();
}

void loop() {
}

One question I have is (which is an entirely different subject), how do I go from here to rotate the letters and alphabet 180 degrees?

To create custom characters, just to get you started, look here: https://github.com/adafruit/Adafruit_LED_Backpack/blob/master/Adafruit_LEDBackpack.cpp . You'll see an array static const PROGMEM uint16_t alphafonttable[]  . Make a local copy of the library and try changing the binary value marked say 'A' and see what happens.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
When a button is pressed, it interferes with TFT screen
I'm trying to build a simple device to monitor my heart rate. The components are the following:

A TFT 2.8" LCD screen to display relevant information for the user.
3 buttons for the user to interact with the device.
A PPG sensor to acquire the user's heartbeat.
An Arduino Uno.
A breadboard to connect the components.

The setup of the device looks like this:

which is connected in the following way:

I haven't included the TFT screen here in the drawing of the circuit because I'm using Tinkercad and they don't have it in the components. The screen has the following ports:

The code that I'm using is the following:
// Heartbeat sensor libraries
#define USE_ARDUINO_INTERRUPTS true
#include <PulseSensorPlayground.h>

// TFT screen libraries
#include <TFT.h>  // Arduino LCD library

// Heartbeat sensor variables
const int PulseWire = 0; // PulseSensor WHITE WIRE connected to ANALOG PIN 0
int Threshold = 550; // Determine which Signal to "count as a beat"
PulseSensorPlayground pulseSensor; // Creates an instance of PulseSensorPlayground

// TFT screen variables
#define cs   10
#define dc   9
#define rst  8
TFT TFTscreen = TFT(cs, dc, rst);

// Button variables
const int buttonUp = 2;
const int buttonDown = 3;
const int buttonOk = 4;

#define DELAY 1.0/64.0

void setup() {

   Serial.begin(9600); // For Serial Monitor

   pulseSensor.analogInput(PulseWire);
   pulseSensor.setThreshold(Threshold);

   pulseSensor.begin(); // Start heartbeat sensor
   TFTscreen.begin(); // Start TFT screen

   drawScreen(); // Draw content of the screen

   // Buttons
   pinMode(buttonUp, INPUT);
   pinMode(buttonDown, INPUT);
   pinMode(buttonOk, INPUT);
}

bool buttonUpPrev = false;
bool buttonDownPrev = false;
bool buttonOkPrev = false;

void loop(){

   if(buttonUpPrev == HIGH && digitalRead(buttonUp) == LOW){
      Serial.println("button up");
   }

   if(buttonDownPrev == HIGH && digitalRead(buttonDown) == LOW){
      Serial.println("button down");
   }

   if(buttonOkPrev == HIGH && digitalRead(buttonOk) == LOW){
      Serial.println("button ok");
   }

   buttonUpPrev = digitalRead(buttonUp);
   buttonDownPrev = digitalRead(buttonDown);
   buttonOkPrev = digitalRead(buttonOk);

   //Serial.println(pulseSensor.getLatestSample());

   delay(DELAY);
}

My problem is that when I press one of the buttons, the TFT screen flickers, as if less voltage gets to the screen. Also, sometimes I see "button down" in the Serial Monitor when nothing is being pressed. Overall the device works, but I wonder if I made a mistake.
My question is: Is there a problem with the cabling of this device? I've studied Computer Science and I just know the basics of electronics. Thank you!

try using internal pullup resistors ... remove the external pulldown resistors and connect the switches between the data pins and ground

Also instead of delay(1.0/64.0);, use delayMicroSeconds(15);.


text:
Constantly Stream data vía Bluetooth to monitoring
I am using a Bluetooth module HC-05 to Stream data from Arduino to My computer. In they computer I am using a python script to receive
They specifications:
Baud rate: 9600
But I am getting an error. The right data got in the computer should be:
b'123.098x726.8393x123x\r\n'
Which I almost always get, but sometimes I get the following:
b'123.098x726.8393x123x123.098x726.8393x123\r\n'. wrong
So I don't know happens, in python I use the method reset_input_buffer() and reset_output_buffer() and in Arduino ide I use Serial.flush()
The error keep happens, would it be the baudrate? I increase it would it be the solutionn?
Thanks in advance
String str;
String strs[8];

int pwm=9;

int tech;
String sync_fromApp = "?";
String sync_ok = "okx";

int cyc_num;
int PWM_0;
int PWM_i;
int PWM_f;

float volt;
float cur;
int t;

void setup() {
  // put your setup code here, to run once:
  TCCR1B = TCCR1B & B11111000 | B00000001;
  Serial.begin(9600);
  Serial.setTimeout(5);
  pinMode(A0, INPUT);
  pinMode(pwm, OUTPUT);
  analogWrite(pwm, 130);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  int strCount = 0;
  if (Serial.available() > 0) {

    str = Serial.readString();
    str.trim();

    if (str == sync_fromApp) {
      Serial.println(sync_ok);
      //Serial.flush();
    }

    while (str.length() > 0) {
      int index = str.indexOf('x');
      if (index == -1) {
        strs[strCount++] = str;
        break;
      }
      else {
        strs[strCount++] = str.substring(0, index);
        str = str.substring(index + 1);
      }
    }

    tech = strs[0].toInt();
    float E0 = strs[1].toInt() / 1000.0;
    float Ei = strs[2].toInt() / 1000.0;
    float Ef = strs[3].toInt() / 1000.0;
    cyc_num = strs[4].toInt();
    int scan_rate = strs[5].toInt();
    int t_chro = strs[6].toInt();
    int t_step_chro = strs[7].toInt();
    float e00 = ((995.0 / 1986.0) * 5.06 + (995.0 / 1004.0) * E0);
    PWM_0 = e00 * (255 / 4.99); //Starting Voltage
    float eii = ((995.0 / 1986.0) * 5.06 + (995.0 / 1004.0) * Ei);
    PWM_i = eii * (255 / 4.99)-1; //Min Voltage
    float eff = ((995.0 / 1986.0) * 5.06 + (995.0 / 1004.0) * Ef);
    PWM_f = eff * (255 / 4.99)+1; //Max Voltage
    long t = (4990000L) / (256L * scan_rate); //delay scan rate
    //default:
    analogWrite(pwm, PWM_0);
    switch (tech) {
      //---Cyclic voltammetry---
      case 1:
        delay(3000);
        for (int n = 1; n <= cyc_num; n++) {
          for (int val = PWM_0; val < PWM_f; val++) {
            analogWrite(pwm, val);

            volt = 0.01974563 * val - 2.558; //0.01974563
            cur = 0.51469 * (analogRead(A0)) - 255.226; //254.226

            Serial.print(volt, 3);
            Serial.print('x');
            Serial.print(cur, 3);
            Serial.print('x');
            Serial.print(val);
            Serial.println('x');
            Serial.flush();
            delay(t);
          }

          for (int val = PWM_f; val > PWM_i; val--) {
            analogWrite(pwm, val);

            volt = 0.01974563 * val - 2.558;
            cur = 0.50669 * (analogRead(A0)) - 255.226;
            //cur_ave = analogRead(A0);
            Serial.print(volt, 3);
            Serial.print('x');
            Serial.print(cur, 3);
            Serial.print('x');
            Serial.print(val);
            Serial.println('x');
            Serial.flush();
            delay(t);
          }
          PWM_0 = PWM_i;
          //Serial.println(n);
        }
        Serial.println("Nx");
        Serial.flush();
        analogWrite(pwm, 130);
        tech = 0;
        break;
      default:
        break;
    }
  }
  else {
    digitalWrite(13, HIGH);
    delay(200);
    digitalWrite(13, LOW);
    delay(200);
  }
}

Above left the arduino sketch.
Below is the python code
            self.ser.write(self.parametersToArduino.encode()) #command to start stream
            pass

        self.ser.reset_input_buffer()   #flush input buffer
        self.ser.reset_output_buffer()   #flush output buffer
        COM.stop_button["state"] = "active"

        while self.threading:
            try:
                data.RowMsg = self.ser.readline()  # read data from arduino
                data.DecodeMsg()                   #decode data from arduino
                if len(data.RowMsg)>0:
                    if b'N' in data.RowMsg:
                        #print("It's over")

                        self.threading = False
                        break
                    data.upXData()  #update a list to plot
                    data.upYData()  #update a list to plot
                    self.ser.reset_input_buffer()
                    self.ser.reset_output_buffer()
                    pass
                pass
            except Exception as e:
                print(e)
                pass

DecodeMsg is the code below
    def DecodeMsg(self):
        temporal = self.RowMsg.decode('utf8')
        if len(temporal)>0:
            if "x" in temporal:
                self.msg = temporal.split("x")
                del self.msg[-1]
                pass
            print(self.msg) #debugg
            pass
        pass

The problem could be on the Python side. Do you have some other means of monitoring that serial stream? The Arduino serial monitor, PuTTY, picocom, or even cat?

Thanks for the answer. Yes, I use serial monitor of Arduino IDE as well but I still got the error. It is like if the next data of the stream was send at the same time that the previous data

Do you still have the same error if you remove the Bluetooth module and run the serial flow through USB? If this is the case, it could be a bug in the Arduino sketch, and we may be able to help finding it if you share the code.

I haven't still tested with USB. I could test, but let me upload My Arduino sketch.

Ready, the Sketch is already uploaded, thanks.

reduce your code to continually sending b'123.098x726.8393x123x\r\n

Sorry I don't understand, what do You mean? You suggest that I delete the other operations? And My code is only with lines of Serial.print()?

I don't really understand what you're doing. In particular what input you're feeding this code. What I notice is that there doesn't seem to be much keeping strCount from overflowing strs

The behavior of input works fine, the problem is the output.

Post the python code.

Of course, let me post it

Update: I have uploaded the python code.

I'm not sure that this an answer, but it is easy to implement and may help you figure out what is going on.
I don't think it is a baud rate problem because the characters appear to be intact, but some are missing. I think it is a serial buffer overflow resulting in a mix of old and new characters.
To test this out, I would insert a counter into the beginning of the "packet" being sent. My suspicion is that when you see the error, you will be able to see that one packet is being messed up when it overflows. So, you might get something like this (where the first 3 digits are the packet number):
b'001123.098x726.8393x123x\r\n'
b'001123.098x726.8393x123x123.098x726.8393x123\r\n
b'003123.098x726.8393x123x\r\n'
It may not be definitive, but might help to more clearly see what is happening.
Before doing this, I would probably comment out:
TCCR1B = TCCR1B & B11111000 | B00000001;
which is increasing the PWM frequency on 9. That, just to see if this changes the behavior since it is so easy to test out.
Hope it helps, but I admit that it is just a suggestion.
BTW: interesting problem and I hope you will tell us what happens.


text:
Arduino Output Panel Font Color Change
I am using Arduino IDE 2.0.3.  When compiling code if there is an error it shows on a black background with a red font, that is hard for me to read.  Can I change either the background or the font?  Looking within the IDE I don't see how and not seeing anything on the internet.  TIA

Does it help if you select another theme? You can change the theme from the preferences. Open the Preferences dialog with Ctrl/Cmd+, and choose another theme, press OK.

Wow, now I feel stupid.  Themes did not even enter my mind.  Thank you for the suggestion and thank you for not point out that my question was pretty stupid.

Great! Suppose you or anybody else wants to install additional themes into the Arduino IDE, reference this excellent guide. The IDE does not yet support custom themes natively, but it's possible to install them as VS Code extensions manually. For the install guide, the credit goes to in0.

custom themes in v2.0.3 appear to be broken ... use 2.0.1 or nightly build

Thank you dankeboy36 for pointing out "Themes".  Fixed it right up.


text:
Startg the Arduino2 with the boards parameters
when the Arduino_2 starts the board is not selected.
Is it possible to run a program with such parameters (for example)?: "C:\Program Files\Arduino IDE\Arduino IDE.exe" --board arduino:avr:uno --С:\Users\scetch.ino

It's not something the Arduino IDE 2.x currently supports. However, the IDE should remember the selected board between IDE stop/start once selected. File > New Sketch should inherit the board selection from the currently opened sketch window. Please elaborate on why you find this feature helpful besides saving two clicks after the sketch opens. It can be implemented if there is a good reason.


text:
Arduino IDE 2.1.1 Mac M2 - Fails to upload, No drive to deploy, Raspberry Pico
I'm using Arduino IDE 2.1.1 on a Mac M2 and it's failing to upload, No drive to deploy, I have tried 3 different Mac's, and multiple Picos & USB cables.
Summary of what I've done:

Loaded Example Blink application
Selected board Raspberry Pico W from Raspberry Pi Pico Arduino core 3.3.2
Port selection initially UF2 which shows connected and successfully uploads, then shows as /dev/cu.usbmodem1101

The first time I do the above the blink application works but any further uploads to /dev/cu.usbmodem1101 fail, with the following output:
Resetting /dev/cu.usbmodem1101
Converting to uf2, output size: 660992, start address: 0x2000
Scanning for RP2040 devices
No drive to deploy.
Failed uploading: uploading error: exit status 1

I have only two ports available for upload

/dev/cu.Bluetooth-Incoming-Port
/dev/cu.usbmodem1101

It feels as if I'm either consistently missing some key configuration details or there's technical issues with Arduino IDE or the Pico's

I am not sure if you have the same problem, but I am positive the Arduino-Pico core has some issues in the platform definition regarding the pluggable discovery, and the monitor does not work. See arduino/arduino-ide#2100 (comment) for more details. You can start a discussion and ask the platform maintainers. I hope this helps.


text:
Just installed Arduino 2.0.3 - what is windows path to associated libraries?
Just installed Arduino 2.0.3 and I attempted to build a sketch which includes a library that I manually installed in version 1.8.19 and it can't be found:
In my program I have
#include <DS3231.h>
Now, attempting to compile it cannot find the library.
What is the path to the basic libraries in Arduino 2.0.3?

as in IDE1, it is the libraries folder in the sketchbook folder. the location of the sketchbook folder is in the Preferences dialog in the IDE

I found the location by examining the app while it was running.
The associated libraries are at:
%localappdata%\arduino15\Libraries
That will look like : C:\Users\<username>\AppData\Local\Arduino15\libraries
I created a new folder named DS3231 dropped in the .cpp, .h and .config files and now my sketch compiles with the #include <DS3231.h>
Kind of blows my mind that the Arduino 2.0.3 Libraries are found in a directory named Arduino15.  Is that an old version or something?
Here's what I see in preferences -- don't see a location for user libraries:

The best location will be your sketchbook location + a folder named libraries.
For example, in my case my sketchbook location is :
c:\users\<username>\dev\arduino
so my library folder should be:
c:\users\<username>\dev\arduino\libraries

"in a directory named Arduino15. Is that an old version or something?" The 15 comes from the the 1.5.x series IDE which first introduced support for boards other than the original set of AVR boards, was carried into arduino-builder, and arduino-cli were it remains relevant to current day IDEs. It is not a normal place to add user libraries.

@timemage Where would the place be to add user libraries?  I've added an image to the answer showing the Arduino 2.0.3 preferences but I don't see any location that would work.  Do you have an alternative path in mind that works for 2.0.3?  Thanks

do you see the location of the sketchbook folder in the Preferences dialog? then read my comment again and slow


text:
Strange characters on display st7920
My Display is showing texts with strange characters in Chinese. how can i fix this

        #include <Arduino.h>
        #include <U8g2lib.h>

        #ifdef U8X8_HAVE_HW_SPI
        #include <SPI.h>
        #endif
        #ifdef U8X8_HAVE_HW_I2C
        #include <Wire.h>
        #endif

          U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 18, /* data=*/ 23, /* CS=*/ 5, /* reset=*/ 22); // ESP32

        void setup(void) {
          u8g2.begin();
        }

        void loop(void) {
          u8g2.clearBuffer();                   // clear the internal memory
          u8g2.setFont(u8g2_font_ncenB08_tr);   // choose a suitable font
          u8g2.drawStr(0,10,"Hello World!");    // write something to the internal memory
          u8g2.sendBuffer();                    // transfer internal memory to the display
          delay(1000);
        }

run simple "hello world" code first

Your source is far too big to be examined. Please step back and write the most simple test program that still reveals the issue.

Looks like you're trying to print uft8

I put a simple code like hello world and still the same error

Have you double-checked your wiring, and that the display uses SPI? Do you have an oscilloscope to watch the transmitted signals, at least the initializing ones?


text:
I want to save the value of the scanned barcode on an SD Card (in a text file may do)
serial monitor output

#include <usbhid.h>
#include <usbhub.h>
#include <hiduniversal.h>
#include <hidboot.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>

/*
  SD card read/write
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)
 */

File myFile;
//SPIClass spiSD(HSPI);
String data = "";
class MyParser : public HIDReportParser {
  public:
    MyParser();
    void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
  protected:
    uint8_t KeyToAscii(bool upper, uint8_t mod, uint8_t key);
    virtual void OnKeyScanned(bool upper, uint8_t mod, uint8_t key);
    virtual void OnScanFinished();
};

MyParser::MyParser() {}

void MyParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
  // If error or empty, return
  if (buf[2] == 1 || buf[2] == 0) return;

  for (uint8_t i = 7; i >= 2; i--) {
    // If empty, skip
    if (buf[i] == 0) continue;

    // If enter signal emitted, scan finished
    if (buf[i] == UHS_HID_BOOT_KEY_ENTER) {
      OnScanFinished();
    }

    // If not, continue normally
    else {
      // If bit position not in 2, it's uppercase words
      OnKeyScanned(i > 2, buf, buf[i]);
    }

    return;
  }
}

uint8_t MyParser::KeyToAscii(bool upper, uint8_t mod, uint8_t key) {
  // Letters
  if (VALUE_WITHIN(key, 0x04, 0x1d)) {
    if (upper) return (key - 4 + 'A');
    else return (key - 4 + 'a');
  }

  // Numbers
  else if (VALUE_WITHIN(key, 0x1e, 0x27)) {
    return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1');
  }

  return 0;
}

void MyParser::OnKeyScanned(bool upper, uint8_t mod, uint8_t key) {
  uint8_t ascii = KeyToAscii(upper, mod, key);
  char c = (char)ascii;
  data += c;
  Serial.print((char)ascii);
  //myFile.print((char)ascii);
}

void MyParser::OnScanFinished() {
   digitalWrite(10, HIGH);
  digitalWrite(4, LOW);
   delay(100);
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");}
  myFile = SD.open("barcode.txt",FILE_WRITE);
  myFile.println(data);
  Serial.println(data);
   data = "";
  Serial.println(" - Finished");
//  myFile.print('\n');
  //myFile.print('\0');
  myFile.close();
  digitalWrite(4, HIGH);
  digitalWrite(10, LOW);
   delay(100);

    }

USB          Usb;
USBHub       Hub(&Usb);
HIDUniversal Hid(&Usb);
MyParser     Parser;

void setup() {
  pinMode(4, OUTPUT);
  pinMode(10, OUTPUT);
   SPI.begin();
   digitalWrite(4, HIGH);
   digitalWrite(10, HIGH);
  Serial.begin( 9600 );
  delay(100);

  digitalWrite(4, LOW);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
   delay(100);
  digitalWrite(4, HIGH);
   delay(100);
  digitalWrite(10, LOW);
  //Serial.println("Start");

  if (Usb.Init() == -1) {
    Serial.println("OSC did not start.");
  }
  delay( 200 );
  Hid.SetReportParser(0, &Parser);
   if (!SD.begin(4)) {
    Serial.println("initialization failed!");
}}

void loop() {
  // SPI.begin();
  Usb.Task();
}

I am using a QuickScan Lite Qw210 Datalogic USB Barcode Reader, USB Host Shield and Arduino Uno
I have coded everything and file is generating and barcode being scanned properly but prob is that file which is being generated is empty . Can anyone point out where the prob is happeining in my code why even after printing in file data is not getting saved

#include <usbhid.h>
#include <usbhub.h>
#include <hiduniversal.h>
#include <hidboot.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
File myFile;
String data = "";
class MyParser : public HIDReportParser {
public:
MyParser();
void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
protected:
uint8_t KeyToAscii(bool upper, uint8_t mod, uint8_t key);
virtual void OnKeyScanned(bool upper, uint8_t mod, uint8_t key);
virtual void OnScanFinished();
};
MyParser::MyParser() {}

void MyParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
// If error or empty, return
if (buf[2] == 1 || buf[2] == 0) return;

for (uint8_t i = 7; i >= 2; i--) {
// If empty, skip
if (buf[i] == 0) continue;

// If enter signal emitted, scan finished
if (buf[i] == UHS_HID_BOOT_KEY_ENTER) {
  OnScanFinished();
}

// If not, continue normally
else {
  // If bit position not in 2, it's uppercase words
  OnKeyScanned(i > 2, buf, buf[i]);
}

return;
 }
 }

  uint8_t MyParser::KeyToAscii(bool upper, uint8_t mod, uint8_t key) {
  // Letters
   if (VALUE_WITHIN(key, 0x04, 0x1d)) {
    if (upper) return (key - 4 + 'A');
     else return (key - 4 + 'a');
     }

     // Numbers
   else if (VALUE_WITHIN(key, 0x1e, 0x27)) {
     return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1');
     }

    return 0;
     }

   void MyParser::OnKeyScanned(bool upper, uint8_t mod, uint8_t key) {
    uint8_t ascii = KeyToAscii(upper, mod, key);
    char c = (char)ascii;
     data += c;
     Serial.print((char)ascii);
     //myFile.print((char)ascii);
     }

      void MyParser::OnScanFinished() {
          myFile = SD.open("barcode.txt",FILE_WRITE);
         myFile.println(data);
       Serial.println(data);
       data = "";
       Serial.println(" - Finished");
           myFile.close();
                }

          USB          Usb;
       USBHub       Hub(&Usb);
      HIDUniversal Hid(&Usb);
      MyParser     Parser;

          void setup() {
        pinMode(4, OUTPUT);
           pinMode(10, OUTPUT);
            // SPI.begin();
               //digitalWrite(4, HIGH);
           //digitalWrite(10, HIGH);
           Serial.begin( 9600 );
            //delay(100);

                //digitalWrite(4, LOW);

               if (!SD.begin()) {
        Serial.println("initialization failed!");
         return;
               }
             delay(100);
            //digitalWrite(4, HIGH);
        //  delay(100);
     // digitalWrite(10, LOW);
       //Serial.println("Start");

            if (Usb.Init() == -1) {
              Serial.println("OSC did not start.");
            }
        delay( 200 );
         Hid.SetReportParser(0, &Parser);
        }

       void loop() {
          Usb.Task();
         }

Did you mean this Juraj Pls have a look on changes and let me know

put SD.begin() only in setup. don't call SPI.begin(). don't set the CS pin of the SD card. let the library handle it.

thanks for the suggestion . I just wanted to know then how my library will know that i have connected my sd card module on 4th pin of arduino and im using usb host shield also which is using the 10 pin i think. Thanks in advance

And what about making pins high and low for chip select? shall I remove all of those digital write things from everywhere

yes SD.begin(4). but in setup(), only once. the CS pin is handled by the SD library

in setup() SD.begin(4)


text:
Free touch big electrodes (arduino zero)
I want to try making big electrodes 20cm*1 cm
but i got an effect i dont understand.
In the picture red and blue are the diffrent electrodes
at first touch the blue  one and it rises.
then i touched the red  one and it rises.
when i touch both electrodes both signals dropps ??
when itouch both with gloves both rise ??
i think its not allowed to touch the pure cooper
Also i would like to know whats the output from the mesure funktion of the  free touch libary  (physical dimension ,like time or voltage??)
#include "Adafruit_FreeTouch.h"

Adafruit_FreeTouch qt_2 = Adafruit_FreeTouch(A1, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);
Adafruit_FreeTouch qt_3 = Adafruit_FreeTouch(A2, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);

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

  while (!Serial);
  Serial.println("FreeTouch test");
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);

  if (! qt_2.begin())
    Serial.println("Failed to begin qt on pin A1");
  if (! qt_3.begin())
    Serial.println("Failed to begin qt on pin A2");

}

void loop() {
  int counter,result2,result3, result = 0;

  counter = millis();
  result = qt_2.measure();
  result2=result;

  counter = millis();
  result = qt_3.measure();
  result3=result;
    Serial.print(result2);
    Serial.print(" ");
    Serial.println(result3);
  delay(200);
}

the problem was that i touch de the electrodes on the copperside instead for the rearside

You need to provide more information. How have you wired the electrodes to the Arduino? Which library do you mean (provide a link to it)? And please show your code in your question. You can edit your question by clicking the "edit" link under it

is there a way using mutalcapactiance sensors without the qtouch lib   or do i have to use atmelstudio to use qtouch on my arduino zero


text:
ESP8266 cannot read POST parameters
I'm working on a simple REST server. I made method to handle http://<esp8266_IP>/test. The GET method works like a charm and I got the response. Then I tried to send a POST with a JSON data (I used PostMan) but I cannot read anything.
Searching online I read ESP8266 library cannot parse JSON and in that case I can found plain text into server.arg("plain"). I tried that but no success
How can I read the data into the POST method?

ESP8266WebServer server(80);
...

void handleTest()
{
    if (server.method() == HTTP_GET)
    {
        ...
    }
    else if (server.method() == HTTP_POST)
    {
        String message = "POST\nHeaders:\n";
        for (uint8_t i = 0; i < server.headers(); i++)
        {
            message += server.headerName(i) + ": " + server.header(i) + "\n";
        }
        message += "\nRequest params:\n";
        for (uint8_t i = 0; i < server.args(); i++){
            message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
        }
        server.send(202, "text/plain", message);
    }
}
...
void setup()
{
    WiFi.begin(ssid, password);
    Serial.println("");

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

    if (MDNS.begin("esp8266")) {
        Serial.println(F("[Server] MDNS responder started"));
    }

    server.on("/test", handleTest);
}

Please show your code.

i'm not sure it can do that, aside from uploading files...

@MarkSmith I don't think it will be usefull, btw I paste a section of code in my question.

Instead of using below in handleTest()
else if (server.method() == HTTP_POST)

try using below in setup()
server.on("/test", POST, handleTest);


text:
UART from Arduino to NodeMCU
I'm trying to connect an Arduino nano to a NodeMCU 1.0 via the hardware UART, in order to send information one way from the Arduino to the NodeMCU (and from there to the network).  I'm connecting the Arduino TX to the NodeMCU RX via a reduction of voltage from 5V to 3.3V but I'm getting nothing read at the serial.  The connectivity part is tested, since if I connect the NodeMCU via USB and write something with the Serial monitor, the data appears on the server.
Is there anything missing from the code on either parts?
The circuit is connected as follows:

and the code that runs on the Arduino (as a test) simply sends a string over and over, but at a low rate

    void setup() {
      Serial.begin(115200);
      while (!Serial) delay(10);
      pinMode(LED_BUILTIN,OUTPUT);
    }
void loop() {
  digitalWrite(LED_BUILTIN,HIGH);
  delay(100);
  digitalWrite(LED_BUILTIN,LOW);
  delay(100);
  Serial.println("Hello");
}

The code that runs on the NodeMCU is as follows:
WiFiClient client;

void connect_to_wifi()
{
  WiFi.begin(ssid, password);
  int tries=0;
  for(tries=0;tries<20 && WiFi.status()!=WL_CONNECTED;++tries)
  {
    digitalWrite(D0,(tries&1)==1?HIGH:LOW);
    Serial.print(".");
    delay(500);
  }
  if (tries>=20)
  {
    status=0;
    Serial.println("Failed to connect to WiFi");
  }
  else
  {
    Serial.println("Connected to WiFi");
    if (client.connect(addr, port))
    {
      Serial.println("Connected to server");
      client.println("Connected");
    }
    else
    {
      Serial.println("Failed to connect to server");
      status=0;
    }
  }
}

void setup() {
  pinMode(D0,OUTPUT);
  digitalWrite(D0,LOW);
  Serial.begin(115200);
  while (!Serial) delay(10);
  connect_to_wifi();
}

void loop() {
  if (status==0)
  {
    digitalWrite(D0,HIGH);
    delay(300);
    digitalWrite(D0,LOW);
    delay(300);
  }
  else
  {
    digitalWrite(D0,HIGH);
    delay(100);
    digitalWrite(D0,LOW);
    delay(100);
    int av=Serial.available();
    if (av>0)
    {
      client.println(av);
      for(int i=0;i<av;++i)
      {
        int c=Serial.read();
        client.print(char(c));
      }
    }
  }
}

EDIT 1:
I connected a scope to see the serial signal and see only high.  I then disconnected the NodeMCU and see a valid signal coming out of the Arduino.
Then I moved the receiving part to D5 on the NodeMCU and used a version of SoftwareSerial for this board, which worked.
For some reason, the hardware Rx is pulled high no matter what.
I would prefer to use hardware Serial, but if no solution can be found, I guess I will have to do with Software.

Your schematic is showing 3 resistors and only 2 are needed to a 5v to 3.3v logic adapter. Could you provide more details about that interface ?

The hardware receive pin is probably being driven high by the node MCU's onboard USB-serial chip, and your voltage divider means the signal from the arduino will clearly loose that battle.  See if you can disable the USB serial chip, perhaps by holding it in reset, or if there's a way to cut the connection.  If you have the CH340 version try making R10 a lot bigger, or else maybe put a diode in your level shifter or switch to a MOSFET style level converter so that you can actively drive low.

The reason for the 3 resistors is to make a 2/3 divider using 3 identical resistors.   Regarding a level shifter, I have tried that before and it didn't help.   If there's nothing that can easily be done in software to remove the pullup on the Rx pin, I'll settle for soft serial on another pin.   Thanks for the suggestions.

What about using a optocoupler to handle the different voltage issue?


text:
Making my own libraries
Does anyone know of a site or book where you can learn how to create, or for first reed, libraries. Because I think the libraries I use are sometimes unnecessary complicated, or have similar features, for example Wire and OneWire.
I think, these make my sketch unnecessary big, when I need both of them.

Wire and one wire are two different things. If you are looking for arduino libraries, there are tutorials on how to make your own on the arduino site, sparkfun might have something and I might be wrong here, but Arduino cookbook, might have.

Just look at the source code of a few libraries. That's the advantage of open-source.

http://www.arduino.cc/en/Reference/APIStyleGuide  -  http://www.cplusplus.com/

Arduino has a library tutorial here: http://www.arduino.cc/en/Hacking/LibraryTutorial
and a formal specification here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification
these explain the specifics to making arduino libraries, like the propeties files, the keywords file, and the directory structure. Most of that is unnecessary though.
Anyway, there are not many differences between the actual code in an arduino library and the normal code you write for arduino sktech. The only major ones being that

The arduino preprocessor doesn't generate function declarations - you have to make your own header file
You can't use setup or loop

Other than that, its just normal c++ code that exposes a particular interface and provides an implementation. If you want the library to work well for a lot of users, you will need to put in the extra work to make it run on all the different arduino hardware variants.
Making libraries for c++ often involves creating .a, .so, .dll etc. files of compiled code that new programs can link against, but arduino compiles everything from source for every sketch so you don't need to worry about that here.

To address your query about libraries making sketch code too big...
I have recently completed (or rather, am in the process of completing) my first library, SevenSegmentSL1255. I too was concerned about the growing size of the library, as I incorporated more and more ideas. So I decided to plan for a "Lite" version, SevenSegSL1255Lite, so that the casual user would not feel to overwhelmed and also to reduce the memory footprint, for simple sketches.
However, after reading the Arduino page on the build process, I discovered that the whole library is not necessarily included in all sketches:

The .c and .cpp files of the target are compiled and output with .o
  extensions to this directory, as is the main sketch file and any other
  .c or .cpp files in the sketch and any .c or .cpp files in any
  libraries which are #included in the sketch.
These .o files are then linked together into a static library and the
  main sketch file is linked against this library. Only the parts of
  the library needed for your sketch are included in the final .hex
  file, reducing the size of most sketches.

So you see, from a memory footprint point of view, no matter how big the library may be, the resultant compiled sketch can still be quite small, depending on the amount of the library that is called for the sketch. From my point of view, this makes the "Lite" version of my library now somewhat redundant. Although, the argument for a simpler, more user friendly library may still exist.
As an aside, the resources that I used in creating the library are listed below:

Writing a Library for Arduino
Arduino Style Guide for Writing Libraries
error in using overloaded constructor
Memory
Style Guide

True, as long as it's clear that the smallest unit that may be included or excluded is an entire library module, such as an EEPROM module. In the context, 'library' means 'collection of .o files, and 'parts of the library' means individual .o files. ...

... If your code doesn't call any functions contained in the EEPROM library module, and none of the library modules that you DO call makes any calls to the EEPROM module, then that module will not get linked into your code. If, however, there is one call to one tiny function in that module, the whole module will be linked (generally speaking; there is currently work being done delay all or most code optimization until link-time, which may possibly yield finer-grained inclusion/exclusion). Thus writing a Lite version or writing sub-modules may well be useful to keep the linked code image small.

@JRobert - Thanks, I may need to look into this further, as I appear to have mis-interpreted the quote in my answer.


text:
How to display a number using SevSeg library on 4 digit 7 segment LED display
I am getting error with this. It is displaying those segments which are not to be displayed, i.e., 3.141 is dark and other segments are red.
#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}

Are you sure you have the right type of common for your display?

There are two main types of seven segment display:

Common Anode
Common Cathode

The common refers to the fact that one end of the LEDs within a digit are linked, and need to be connected to either Vcc or GND, depending on the type of the display (see below). The other end of each led (one per segment) is used to switch them on, and it is these that go to the Arduino pins, or LED controller.
Common Anode

The common end is connected to the Vcc line. If you wish to light a segment, then the input pin for that segment needs to be pulled LOW.

Source: Four multiplexed 7-segment COMMON ANODE LED
Common Cathode

The common end is connected to the GND line. If you wish to light a segment, then the input pin for that segment needs to be pulled HIGH.

It sounds as if you have the logic inverted, so the wrong segments are lit, when they should be dark, and vice versa.
Either that, or you need to invert the logic in your code, and for example if you are currently pulling a pin LOW to light up a segment, then you need to change your code to pull the pin HIGH.

Image sources:
Electronics-Tutorials
Common Anode/Cathode 7-segment displays

You could try the following:
#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}


text:
Reading iBeacon Data using HC-05 bluetooth module
I have bought a HC-05 bluetooth module for Arduino.
My requirement is to read data transmitted from iBeacon, is it possible using HC-05 or I have to shift to HM-10?

did you come up with a plan? Because I am dealing with the same issue, would love to see an answer without having to post the same question.

The HC-05 doesn't support BLE, which is used for iBeacons.

Is it possible to read ibeacon data with Arduino using HM-10 module? If not then what's the best option?

Probably yes. But I'm not into BT.


text:
How to connect new OV7670 FIFO to Arduino?
I bought a new OV7670 FIFO camera to connect to my Arduino UNO a few days ago.
The picture of the cam board:

I found this forum, it is nice try but it looks chaotic and confusing with about 50 pages, where you can't find where the questions and where the answers are.
I also found this library which is for non-FIFO board and could not apply to my project. I also read the OV7670_FIFO and OV7670 and AL422 datasheets and I read I2C protocol and basics; and there are many success story on the internet but there is no schematic on them.
The problem is, I can't find any simple example for FIFO with schematic to start with. I don't know if this camera is so new or it is so hard to understand, this problem getting so serious that somebody wrote a book named "Beginning Arduino ov7670 Camera Development" about it, but I think it is a matter of an Arduino to FIFO cam schematic and example code. I ask if there is a such schematic and code for it on the web or how can I connect them?

I'm only on my phone so can't provide a full answer right now, but despair not, with a FIFO, things are a lot easier than they could be. With camera modules, usually it involves sending and receiving complicated and fast signals, on the edge of what an arduino is capable of handling. A FIFO, is a buffer, you can kind of think of it like RAM, and the way it works is you can take a picture, and instead of trying to receive it directly on the arduino, the data gets sent to the FIFO. Then, you can read the FIFO from your arduino, as fast, or as slow as you want.

So the two things you need to accomplish are, How do I send a command to the camera to take a picture? and How do I read the data from the FIFO? For the first, as far as I can tell all it is is connecting via i2c, so just the SDA and SCL pins (A4 and A5 respectively on the Uno) to their corresponding pins on the camera. For the FIFO, it is a parallel data bus, so it just means connecting the D0-D7 pins to digital pins on the arduino.

Are you 100% sure it's the FIFO version? I see no SPI or I2C (or are they labelled differently?).

The AL422B, as shown in the photo, is, to quote from the data sheet: ...a First-In-First-Output
(FIFO) video frame memory used to buffer
audio/video/graphic data...

I just received this exact model, QIFIO v1.0, exactly as yours. I am very interested in use this camera in full resolution, max sensitivy, with my dccduino UNO. I will try to get this camera working, I'm a very experienced programmer, but my fear is to burn it with a excessive voltage in signal pins. I wired the vcc to 3.3v, but I don't know if I must use 10k resistances in the rest of the signals (SIOC, SIOD, VSYNC, HREF, etc.). Thanks in advance

I recently brought this book off Amazon "Beginning Arduino ov7670 Camera Development".  I'm loathed to recommend it, because it has a nice 80 page introduction to the Arduino and OV7670 and the rest of the 250 pages are just double space annotated code.  That said, it does appear to be a very good introduction, with example code, for a OV7670-FIFO (the title of the book is incorrect).
It might be possible to find the code on the net and then you can decide if you want to buy the book or not.  Oh and I am not Robert Chin, I do not know him and I have nothing to do with the book, other than owning a rather new and once read copy of it.


text:
Measuring KWh connecting to the mains
I need to measure KWh of the mains, connecting something like a sensor to the mains and reading its value into analog. I already know to measure KWh from a KWh meter but I need to make my own.

You can put a current clamp around the wire, to measure the current. But you need to spit the live and neutral wires. Something you probably have to have an electrician done.

If i understand your question correctly, what you want to do is measure the current consumed from the mains by whatever load is connected to it (Fan, AC, computer etc).
What you need is basically a current sensor, have a look at https://www.sparkfun.com/products/8883 and https://www.sparkfun.com/products/11005
Please understand that you are playing with the mains and unless you take the required precautions, you can get seriously injured


text:
ESP8266 as I2C client
I've got an ESP8266 that takes instructions from a web page and sets a series of NeoPixels to flash in different sequences.
I noticed that when the Wi-Fi got data and parsed it, my LEDs would "stutter" as the processor ignored them for a moment while processing the incoming instructions.
So I added a 2nd ESP8266. This one just handles the LEDs. So the 1st ESP gets the Wi-Fi data and parses it. It then sends an interrupt to the 2nd ESP which breaks out of the LED display loop, checks the interrupt pin for HIGH or LOW and sets the LEDS based on HIGH/LOW.
However, I would like to send more data from the Wi-Fi ESP to the LED driving ESP. e.g. Colour data, transition speed, rotation direction etc. All of these settings I can send to the ESP from a web page.
I thought I2C (the wire library) would help but all comments seem to say that the ESP8266 cannot act as a slave so I can't send to it.
So it appears I'm left with Serial comms (the interrupt is over by the time comm start because I realize Serial does not work in an interrupt).
So my questions are:

Am I right that I2C will not work?
If I am wrong does anyone have a working end to end example?
If I am right is there an approved way to do ESP to ESP serial comms?

The issue with the ESP8266 is that it is multitasking, and only 80% of the CPU time is available to developers. This manifests as an outage of 100-200us every 500ms or so, which rather complicates all sorts of software serial interfaces, such as I2C, SPI and UART. As a bus master the ESP8266 hides these issues as it is responsible for the bus clock, but as a bus slave it needs to halt data transfer for the duration of these random events.
A typical solution for this inter-CPU issue is to provide an external RAM cache to act as a mailbox, where each CPU will periodically check to see if any actions are outstanding and leave any requested data.
Has anyone explored this option for the Arduino to ESP8266 interface?

If you wish to ask a question please use the "Ask Question" button in top right corner.

I assume that you are using the Arduino core for the ESP8266 (https://github.com/esp8266/Arduino)

Am I right that ic2 will not work?

I am not certain, but I get the same impression as you.  It seems that the Expressif SDK only supports master mode.

If I am right is there an approved way to do ESP to ESP serial comms.

There is no "approved way", but there are many ways you can do it.  A direct serial link will give you a simple pipe of data - what you put in at one end comes out the other.  It's up to you to decide how you format and interpret that data.
My ICSC library may help you with that - I use it to connect an ESP8266 to an BeagleBone Black through serial: https://github.com/MajenkoLibraries/ICSC

I am not certain, but I get the same impression as you.
  It seems that the Expressif SDK only supports master mode.

Sorry no.
Espressif SDK supports Slave Mode too.
official the Master works with 50 kHz (CPU 80MHz), and  100 kHz in technical referenz  and unofficial in my test with !1.2MHz you must switch then to the 160 MHz CPU and you must work for delays with
asm ("nop") 12.5 ns at 80MHz and 6.25 ns at 160 MHz
then you can toggle the pins at 80 MHz with 700 kHz and with 160 MHz with 1400 kHz. because there are instruction to the gpio ( toggle output low, "opendrain" clear output with pullup high ) it will be a netto rate of
620 kHz, and 1260 kHz.

best wishes
rudi ;-)

Read in
http://bbs.espressif.com/viewtopic.php?f=49&t=2092#p6897

youtube video:https://www.youtube.com/watch?v=P_KAMJCImzA


text:
Adding POE to Ethernet Board
If I was to use the Arduino A000024, would I be able to add a POE MODULE to the board to get a Ethernet board with POE to run my arduino project?

why not buy A100025 - Ethernet shield with POE?

Can't find a reliable reseller for that retired board.

If the pinout is what the Ethernet shield expects, then yes. The rows of holes at an odd angle are designed for a POE board similar to that. I can't vouch for whether the pinout is correct though.  It looks ok, but it depends on the dimensions of the board whether it fits the existing pinout.

I found the suggested POE module on another site that fits the pinning on this board, thank you for confirming this.


text:
Hot Swap Sensor
Is there a way to have a sensor be hot swappable, as in it can be disconnected and reconnected without locking up the Arduino? I have an I2C sensor that I want to be able to disconnect and reconnect without having to restart the board.

The i2c bus is not meant to have sensors disconnect and connect, but I think it can be done. Poll the sensor a few times per second and if it is reconnected, then initialize the sensor. Why do you want to do that? Is there an other way?

I am making a sensor that goes onto a filter loader and just wanted to make sure if the sensor got disconnected that it could be reconnected without issue or having to reset it. This is for a remote device from my office and I won't always be the one dealing with it.

Please see https://arduino.stackexchange.com/questions/31924/how-to-setup-an-i2c-bus-which-stays-valid-if-a-slave-is-powered-down-or-fails/31940#31940

The I2C bus is not blocking the operation, if the sensor isn't there. Also the Wire library will not block in this case. It will just return an error code, which you should handle in your code.
But this doesn't mean, that every library, which wraps the I2C workload for a specific sensor, is doing the same. Depending on the sensor and the used library you will have to check yourself, if it is blocking in any way. (This part is not better answerable without information on what sensor and what library will be used)
So: Yes, this is totally possible, but you will have to deal with the errors from disconnecting the sensor and handle them in your code. By polling the sensor in a regular fashion (like Jot mentioned in the comments) will give you the information, if there is a sensor with this address on the bus. The Wire.endTransmission() method will return 2 (received NACK on transmit of address), if no device with the specified address is reachable on the bus.
Depending on the used sensor, you might have to initialize the sensor correctly after every reconnect. Especially, if the disconnect happend during a transmission. Refer to the datasheet of the sensor to find out, what happens in this case with the sensor.
If you plan to use different sensors, you have to check for their specific addresses (since different types of sensor often have different hardwired addresses/address spans) and - if the sensors are controlled differently - determine, what sensor is actually connected. The least may be possible by reading their status registers, which can work for many sensor types.


text:
Getting better results from DHT22
I am working on a dew point sensor, and I am using the Arduino Uno board with the DHT22 sensor. I have it taking a reading once ever 2 seconds and I am using the DHT.h library.
The problem I am having is when I compare the values to our standard here the Humidity reads high and the Temp reads low. Is there anyway to get the values to read closer to what the standard is?

personal opinion - use a better sensor ... my DHT reads humidity low (very low in fact) and temperature high ... so opposite to your problem. I've had better success with the BME280, or a DS18B20 for temperature plus a HopeRF HH10D for Humidity

calibrate the sensors

See this article which includes a section about calibration. https://www.allaboutcircuits.com/projects/how-to-check-and-calibrate-a-humidity-sensor/

Thanks for the answers, there were kind of what I was expecting.

Using a RH and Temp Calibrator I had access to I was able to get better results by all lines to adjust the RH and Temp to a better value. Basically a correction equation.


text:
Connect NodeMCU (ESP8266) with normal Switch (Regular 1 way Home button)
i am new to these circuit things, i am using Node MCU (ESP8266) board with relay board. To connect to a bulb, but i want to keep my old (one way) switch as it is. Also i want to add internet switching to this button.
How my circuit should look like? Two way switch will be compulsory to use here?  What my circuit should look like? with two way switch and one way switch.
Thank you! (in advance)

are you ok with the light switch being "wrong" if you change it remotely? if so, then just use a relay and have the nodeMCU toggle the relay on switch change, as well as from http. you connect the relay module to GND, VIN, and GPIO 4 or 5. Connect the switch to GND and the other GPIO 4/5, and set the pin mode to INPUT_PULLUP. Connect the AC hot to the relay. done.

First of all, a light bulb works on regular 110 or 230V AC depending on where you live, so directly connecting a wire to, for example, see if the hardware switch is turned on, would fry the NodeMCU. You'll need a relay break-out board that can handle these outputs on the COM/NO/NC (which most of them do) but they usually operate on 5V DC.
A NodeMCU can thus only supply the trigger signal to the relay, you'll need for example a AC to 5V DC power supply (like an iPhone adapter) to power your circuit. The circuit will contain of the relay board (connected with its DC in and out to the adapter and the com port to one of the GPIO's from the NodeMCU) and the NodeMCU itself as the 'brain' of the operation.
I don't exactly know what you mean by 'two-way switch' but the way I'd handle the situation is to wire the switch to the NodeMCU. This means the switch is connected to the 5V power adapter and when the switch is on, the nodeMCU will know because there will be a positive value at one of the GPIO's (whichever you choose). You can then also handle both commands from a server and the switch itself.
I'm doing kind off the same thing here with a NodeMCU working as a garageport opener with MQTT communication to a Homebridge server and MQTT broker running on a Raspberry Pi. If you want the code (still work in progress though) let me know ;)
EDIT
Here is the schematic you asked for. not the prettiest thing but it should make things clear. Let me know if you have any more questions!

simulate this circuit – Schematic created using CircuitLab
-BM

Hello, thank you for great explanation, but i want to know the circuit diagram. Is that possible from your side.
I am using proper system as your mentioned. But i am not getting the circuit connections to connect the switch from relay to bulb. Can you help me with its suggestion?

I edited the answer with a schematic for you @user3201500

OK sure i will check and revert you soon.

That's not exactly "keeping the old switch as it is" - However, to keep the old switch, as long as it's a "two-way" switch, then, yes, you can keep the old switch, but you still have to make a minor change to it's wiring - and then wire in the relay

@JaromandaX Yea, I know... but there is no other way to let the NodeMCU have full control over the circuit. If you wanna attach an app to the system which controls the lights and if you just wire in the relay to the existing circuit, then when the power switch is flicked, the NodeMCU would not know about it. You have to have a input which signals the nodemcu that the switch is flicked. It's better this way, trust me I'm an engineer :D

Indeed, I see your point. I guess either way would require some rewiring anyway, so your solution is ideal


text:
Is ESP8266 dropping an interrupt?
I want to use interrupts on my ESP 8266 to monitor the digital outputs of a power meter and water meter.
The idea is to increment a counter in the ISRs and at some point to take the value of the counter and to set the counter back to 0 in the loop() function.
I've red about critical sections, noInterrupts() and interrupts() and then I started to wonder if an ISR will be executed while the code is between noInterrupts() and interrupts(). On theory it should be because the interrupt flag in the chip will be raised and the ISR will be invoked after the code exits the critical section. I wrote a program to test it, but my findings prove the opposite.
#include <Arduino.h>

#define REPORT_TIME 5000
#define INTERRUPT_PIN D1

unsigned long base_time;

volatile unsigned int interrupt_counter = 0;

void IRAM_ATTR isr() {
  interrupt_counter++;
}

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

  // The interrupt will be FALLING EDGE
  pinMode(INTERRUPT_PIN, INPUT_PULLUP);
  pinMode(LED_BUILTIN_AUX, OUTPUT);
  digitalWrite(LED_BUILTIN_AUX, HIGH);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), isr, FALLING);

  base_time = millis();
}

bool written = false;

void loop() {

  if (!written)
  {
    written = true;
    for (int i = 0; i < 100; i++)
    {
      digitalWrite(LED_BUILTIN_AUX, LOW);
      digitalWrite(LED_BUILTIN_AUX, HIGH);
    }
  }

  unsigned long time_now = millis();
  if (time_now - base_time >= REPORT_TIME)
  {

    written = false;

    base_time = time_now;

    unsigned int interrupt_counter_local;

    //Guard the critical section
    noInterrupts();
    interrupt_counter_local = interrupt_counter;
    interrupts();

    digitalWrite(LED_BUILTIN_AUX, LOW);
    digitalWrite(LED_BUILTIN_AUX, HIGH);

    Serial.print("counter ");
    Serial.println(interrupt_counter_local);
    Serial.println();
  }
}

Using a wire I attached the pin of the builtin led to the interrupt pin and in the serial monitor I could see the values are:
counter 100
counter 201
counter 302

When I modify the critical section to be like:
noInterrupts();
interrupt_counter_local = interrupt_counter;
digitalWrite(LED_BUILTIN_AUX, LOW);
digitalWrite(LED_BUILTIN_AUX, HIGH);
interrupts();

I expect the same output as above but the values are:
counter 100
counter 200
counter 300

Am I missing something or the interrupts doesn't work as I expect?

After some additional experiments I found that moving
digitalWrite(LED_BUILTIN_AUX, HIGH);

utside the critical section gives me the expected result, so I'm not blocked anymore and more importantly the chip will not drop an interrupt.
If someone knows why it doesn't work with my initial version I will be happy to hear the answer.


text:
How do I find which values are corresponding to the changing values from my phototransistor?
I am new to using serial input. I have an IR emitter and a photo transistor hooked up to my Arduino, I am trying to see which values corresponds to the colored object I put over my IR emitter and phototransistor.
How do I find which values are corresponding to the changing values from my phototransistor?

Could you add code and a terminal dump from the monitor please?


text:
Remove unused boards from Arduino IDE
In the current project I'm programming simultaneously an UNO board and a Leonardo one.
Switching back and forth between the two boards in the Tools menu takes too much time because of the other 18 boards that I do not own anyway.
Is there a way to remove those boards from the Tools menu?

After some more investigation of the IDE folder, I found a text file called boards.txt in the following path.
 [Arduino Path]/hardware/arduino/boards.txt

EDIT: Be sure to make a copy of the file in case you mess up the following part.
Between two series of '#' characters there will be all the information on a specific microcontroller (e.g uno.name=Arduino Uno). Deleting every line of text between the two '#' series will have the desired effect of removing the board from the Tools menu.

I'll have to wait 2 days before I can do it, but surely I'll do it.

You can open two Arduino IDE windows, and use Tools / Board to set each of them to one of the two kinds of boards you are programming.   Ie, you can have multiple IDE windows open, with different options selected in each.  I've programmed an Uno and a Nano device with the same program from two different windows simultaneously (ie, RX lights blinking on both boards at the same time) without problems.
You can use one USB cable and one port, or can use a separate USB cable for each window.  You might need to use Tools / Port occasionally if the port number changes when you recable things.
I have the external editor option selected.  Text in each Arduino IDE window updates when I click Verify or Load, rather than each time I save the file in emacs.  I don't know how it works if you aren't using an external editor and have the same file open in two IDE windows.


text:
Arduino Mini Pro 3.3 V Issue with Bluetooth Mate
I have an Arduino Mini Pro 3.3 V powered from a coin cell(3.6 V, CR2450) and connected to Bluetooth Mate Gold. I have checked the connections and they are fine. I can also connect to the bluetooth from while trying to upload the file and also from Android bluetooth terminal.I am not sure if it could be bootloader issue as I have checked 2 Arduino Mini Pros that give the same problem running the sample sketch on the bluetooth hookup guide.

Arduino: 1.6.5 (Mac OS X)
Board: "Arduino Pro or Pro Mini, ATmega328 (3.3V, 8 MHz)"

The error is:
Sketch uses 2,412 bytes (7%) of program storage space. Maximum is 30,720 bytes.
Global variables use 210 bytes (10%) of dynamic memory, leaving 1,838 bytes for local variables. Maximum is 2,048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I burned the bootloader again but no success.
I get the same with UNO. However with UNO, when I press the reboot button before the program uploads is works.
Could someone point me out to the solution to this? Thanks

How did you connect the arduino reset pin to the BT-module?

@Gerben I used this hookup guide. For Pro-Mini the pins just match. Isn't it?

That guide doesn't connect the reset. So you have to manually reset the arduino just before programming.


text:
what is 400 bad request and how to solve this
AT+CIPSEND=65
link is not valid

ERROR

OK

OK

OK

OK
STATUS:2

OK
\x0BQ\xADUART_DEF=115200,8,1,0,0ATE0
AT+CWMODE=3
AT+CIPMUX=0
AT+CIPMODE=0
AT+CIPSTATUS
AT+CIPSTART="TCP","api.thingspeak.com",80
AT+CIPSTATUS
CONNECT

OK
STATUS:3
+CIPSTATUS:0,"TCP","52.0.107.28",80,38071,0

OK

OK
> AT+CIPSEND=65
GET api.thingspeak.com/update?api_key=M
Recv 65 bytes
E5K4JWXT2ZBSBZ8&field1=0

SEND OK

+IPD,272:HTTP/1.1 400 Bad Request
Server: awselb/2.0
Date: Tue, 23 May 2023 05:45:13 GMT
Content-Type: text/html
Content-Length: 122
Connection: close

<title>400 Bad Request</title>

400 Bad Request

CLOSED

your HTTP request does not match the HTTP protocol

The server name does not belong to the GET request line: it has to be
provided in the Host request header.
Try something this:
server.println("GET /update?api_key=ME5K4JWXT2ZBSBZ8&field1=0 HTTP/1.0");
server.println("Host: api.thingspeak.com");
server.println();  // empty line means "end of request headers"


text:
Ardutester Millenium I2c Lcd Not Showing Anything!
Hiii Friends....,
I am Trying to Build Components tester Using Arduino Specifically Atmega328p Chip .
I Downloaded The Ardutester Millenium Code From Here ..  https://create.arduino.cc/projecthub/plouc68000/ardutester-millenium-the-ultimate-uno-mega-versions-c81db4
Edited Makefile.h By Enabling i2c lcd Interface And Adding My I2c Lcd Adress ...   But it wont work
I tried On Uno And Mega Also Serial Monitor Output seems ok But It Doesnt Display anything on 16*2 lcd
Thanks ...... :)

Code is available at that page sir...
Thanks for your reply

please add minimal code that exhibits the problem to your post ... also include the wiring diagram that you used to connect the modules

"By Enabling i2c lcd Interface And Adding My I2c Lcd Adress ... But it won't work", based on your schematic, it doesn't seem to be a I2C interface... Also please add your code.

The schematic you posted is not for I2C. You have a connection to the regular 2x16 LCD character display. For the I2C an SSD1306.