text:
LED not turning on with following code
LED is not turning on with the following code. Have tried multiple LED's and double checked wiring. What's wrong? Using an uno.
int ldr = A1;
int  ldrVal = ldr;
int led = 6;
int lvalue = 900;

void setup() {
  pinMode(led, OUTPUT);

  Serial.begin(9600);

delay(1000);

}

void loop() {

Serial.println(analogRead(ldrVal));
if (ldrVal > lvalue) {

digitalWrite(led, HIGH);
}
delay (50);

if (ldrVal < lvalue)
{
  digitalWrite(led, LOW);
}
delay (1000);

}

Start by using good names for the variables. Use the term "pin" in the name of a variable that is a pin numer. For example ledPin and ldrPin. Do not mix the value of a sensor with the pin number. The level at which the led is turned on can be called "triggerLevel" or "switchLevel" or something else. Do not use two statements in a single line (for example Serial.print and analogRead). Use the same style for the text everywhere. Use text indents in the same way.

This is incorrect: int  ldrVal = ldr; and this: Serial.println(analogRead(ldrVal)); There is an example sketch (AnalogInput.ino) that comes with the IDE which would be a great starting point.

Apart from the bad indentation and the bad variable naming, which makes your code not only look ugly, but messy and poorly readable, you have multiple problems in your few lines of code.
One problem is the variable lvalue never gets set, meaning its value remains 900 no matter what's the value you are reading through analogRead().
A second mistake is your ldrVal, which should represent the boundary between lit and powered off, is set to A1, which in turn is a macro define for a valid integer, but a very small value (less than 20).
In other words the code that should decide to turn on/off the LED continously compare 900 and 20 with no opportunity for those values to change: not surprising the LED won't change state, do you agree?
BTW, 50ms is a very short time interval: if you want to be able to see the LED turn on and then off, increase the delay to 200 or more.

Your code is wrong. analogRead(ldrVal) does not read the analog pin's value and store it into ldrVal, it is a function who's result is the analog pin value.
Try this edit:
void loop() {

int newValue = analogRead(ldrVal);
Serial.println(newValue);
if (newValue > lvalue) {  //Check newValue, not ldrVal
    digitalWrite(led, HIGH);
}
delay (50);

if (newValue < lvalue)
{
    digitalWrite(led, LOW);
}
delay (1000);
}


text:
Powering a Tiny Arduino Project
I'm trying to build a tiny project. After I program the board, to power the dev board - how can I power it to run the code?
Question:

I was curious as to how I would be able to power the ATtiny85 USB Mini Dev Board by using a 90mAh 3.7V LiPo battery which is connected to a TP4056 5V micro USB Lipo battery charger? The power is regulated to 5V by a  3v to 5v 1a USB Charger DC-DC Converter feeding the 5V pin on the ATtiny85.
If now, how else can I power the ATtiny85 USB Mini Dev Board with a rechargeable battery?

New Circuit

Old Circuit

Final Circuit

The old circuit will not work as you expect. While the ATtiny85 can run happily with 2.7 to 5.5V in this setup it expects 5V. I assume this is due to the high CPU clock setting. To run stable at a high CPU clock it requires 4.5V.
The VIN pin is connected to a linear regulator that has a 2V drop-out. Thus the supplied voltage has to be at least 2V about the target voltage. That is why the shopping page states a 5V (direct) or 7-35V (regulated at VIN) power supply.
Your LiPo charger already has a boost converter built in that boosts the battery voltage (3.0 - 4.2V) to 5V. No need to use a separate DC-DC boost converter here.
Just connect OUT+ to 5V and you are done.

Thanks, so the final circuit would be correct? It would have enough power to light up standard 3mm leds  connectected to the pins?

Yes, this is the wiring one would expect.

@Kwasmisch I have one more question. Would you kindly be able to help me out please?

source: Stack Exchange

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

sort: votes


text:
When does a pre/post increment occur?
Editing here to clarify. The headline asks the question but the example given was not ideal. This was a more general Q than about the example code.
Compilers have sequence points, places where you can be assured that the equations have been evaluated etc and no lingering effects will occur: the compilation is stable. When I couldn't test the original example I went looking for theory, and came across SE/SO posts where there was some discussion about issues like:
   int a = 1;
   int b = a++ - a++ + a++;

What would you expect the values of a and b to be after this? It turns out it hinges on whether the arithmetic operators are sequence points. Apparently this was not well settled in early versions of C, and in other languages (like Java) the results may differ yet again.
I now understand that an expression like (item++ > max) contains no sequence points -- the > operator does not trigger evaluation, but assignment operators and some arithmetic operators do.
//================================
Original Q:
I've read several Qs here concerning x++ vs ++x but I don't see this specific case. I'm still something of a C novice here.
Do these two code fragments do the same thing?
  // assume itemNum == maxItem on entry

if (++itemNum > maxItem) itemNum = 0;

if (itemNum++ > maxItem) itemNum = 0;

I gather that when the increment takes effect depends on the occurrence a 'sequence point' but I don't know if the comparison creates such an inflection.

why don't you just write a short sketch that prints out the value of itemNum and ++itemNum, then itemNum and itemNum++

@jsotola - Didn't have any platform to test on. As I comment elsewhere, this is more a question about what constitutes a 'sequence point' - about when the ++ occurs than what ++ is.

Both ++x and x++ increment the value of x. The difference is whether you evaluate the value of x in your expression (formula) before or after incrementing it.
int x1 = 0;
int y1 = 0;

int x2 = x1++; //Post-increment: Move current value of x1 (0) to x2, THEN increment x1
int y2 = ++y1; //Pre-increment: Increment y1. Then move the NEW value of y1 (1) to y2.

In the above, x2 will be 0, and y2 will be 1.
The same logic applies to your if expression. If you use pre-increment, your if statement makes its decision on the new value after incrementing it.
If you use post-increment, the if statement makes its decision based on the value before it's incremented.

I do understand the concept of pre/post ++, it just wasn't / isn't clear to me what constitutes a 'sequence point' which forces the increment to occur. This apparently has changed with different versions of C.

I am not aware of any differences in the handling of pre and post increment/decrement operators in C. Where are you getting that information?

There are several discussions here on the topic. Here's one: https://stackoverflow.com/questions/4865599/post-increment-with-respect-to-sequence-points

@JimMack But where is the description of how it's different in different versions of C?

Look at the discussion under https://stackoverflow.com/questions/4445706/ This is about C++, not C, but it's where I got the notion

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


text:
Slow refresh rate on I2C OLED screen
I'm trying to create a small handheld console with 6 buttons and an I2C 0.96" OLED display:
https://i.stack.imgur.com/gWqZP.jpg
The directional buttons use the analog pin and different resistors technique to save space while the two remaining buttons use a digital pin each.
However, despite using the same libraries as other projects, the sketch seems to run very slowly, resulting in a lowered screen refresh rate.
Here is the code:
#define wid 64  // Defines half of the width of the screen for graphic reference
#define hei 32

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display;  // Create display

int av;
const float sp = 3;
float pos[2]={0,0};  // Cursor position

void setup() {
   delay(100);  // Gives the screen time to setup
   display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // Initialize display with the I2C address of 0x3C
   display.clearDisplay();
   display.setTextColor(WHITE);
   display.display();   // Clears the screen of any remaining images
  }

void loop() {
  av=analogRead(A0);  // Reads the directional input
  av=inputRefine(av); // Assigns it to a direction
  switch (av)         // Changes the cursor position accordingly
  {
    case 1:
    pos[1]-=sp;
    break;

    case 2:
    pos[0] += sp;
    break;

    case 3:
    pos[1] += sp;
    break;

    case 4:
    pos[0] -= sp;
    break;
  }
  display.clearDisplay();

  display.setCursor(5,5);
  display.print(millis());  // Prints the system time on the corner of the screen

  display.drawCircle(wid + pos[0], hei + pos[1], 5, WHITE);  // Draws a circle on the cursor position
  display.display();
  }

int inputRefine(int av)
{
  int a=0;
  if (av>500&&av<600) a=2;
  else if(av>1000) a=3;
  else if(av>920&&av<950) a=4;
  else if(av>680&&av<720) a=1;

  return a;
}

What is slowing the execution down?
EDIT: Even commenting out any unnecessary line doesn't remove the lag
EDIT 2: The problem might reside in the screen itself. Unfortunately, I don't have a backup one. I'll order one as soon as possible and test this theory.

I'd suggest using int instead of float for float pos[2]={0,0};. I'd suggest adding some code that measures how many ms each part of your code uses, and prints it to the serial console.

Here's a great way to debug this kind of thing, especially since the sketch is pretty simple. Comment out everything but the lines which update the display. Leave them in using dummy values for pos. Now you know how fast it can update. Then add things back, one by one, and when it slows down you'll know where the problem is. Also, I second @Gerben's comment about floats - never use them on this kind of processor unless you absolutely have to; they're very very slow compared to integers.

I edited out any unnecessary lines and only left the display.print(millis());
 graphical command, but the lag still remains. Could it be a hardware issue?

Did you calculate the possible update frequency? Check what happens on "display.display();", https://github.com/adafruit/Adafruit_SSD1306/blob/master/Adafruit_SSD1306.cpp#L886. How many bytes are transferred? How long time will this take?

I'm terribly inexperienced in how library source code is handled, but i did try to swap every piece of equipment involved in the console (the only piece i don't own at least two copies of is the screen) and the lag didn't cease. I think the screen could be the problem.

Solved by updating the Adafruit sdd1306 library and the Adafruit GFX library
EDIT: Why am I being downvoted?

Your question was down voted automatically by the "system" because there is very little content. I have up voted it to cancel the down vote. Please edit your answer to remove the EDIT and add just a little bit more information. Perhaps the version numbers of the libraries that didn't work and the version numbers that you are using now.


text:
Custom sleep function for Nextion
I have a Nextion 7 inch enhance type display.
I have enabled sleep using thsp = 120 and thup = 1 line of code. Now display become sleep mode after 2min, if there is no any touch event.
But, this sleeping is completely turn off the display.
I have several pages and I want to reset to a specific page, if there is no any touch event in any page instead of sleep function.
Greatly appreciate if someone can give a solution for this.

I solved the problem using a Nextion timer. (tm0)
I got a timer and change tim value. ( unfortunately Nexion allow to maximum to 65535mS). vscope should be globle, otherwise you cant use timer in every page.
I reset the timer in page touch event. In timer event I put this code.
if(tm0.tim==60000) //reset time in mS
{
   page 0 //specific page to load
}

The Nextion screen has a command for this. It is called wup and defines the id of page that the screen should go to on wake from sleep. The default is set to 255, which means that the display wakes up on the page it was on before the sleep event.
16 wup Wake Up
 Page wup=2, n0.val=wup
Sets which page Nextion loads when exiting sleep mode
 min is 0, max is # of last page in HMI, or default 255
 When wup=255 (not set to any existing page)
– Nextion wakes up to current page, refreshing components only
 wup can be set even when Nextion is in sleep mode

Thanks for your answer. But, I want to sleep to a specific page. Not wake up.
wup sets wake up page. Not sleep page.


text:
avrdude: Error: butterfly programmer uses avr_write_page() but does not provide a cmd() method
When trying to flash my sketch, I see many errors such as:
 ***failed;
 ***failed;
 ***failed;
avrdude: Error: butterfly programmer uses avr_write_page() but does not
provide a cmd() method.
 *** page 127 (addresses 0x7400 - 0x747f) failed to write

And also:
avrdude: error: programmer did not respond to command: set addr

How can I successfully flash my sketch?

After much frustration in trying things, I came across this forum post which advised:
sudo systemctl stop ModemManager.service

If this works, disable the service from starting next boot:
sudo systemctl disable ModemManager.service

It seems like setting ENV{ID_MM_DEVICE_IGNORE}="1" in a udev rule is insufficient.


text:
I need help with U8GLIB library
I have a project which uses a 128x64 oled display. I have to use the U8GLIB as the available displays change from SSD1306 to SSH1106 depending on when you buy it which that library covers both displays.
I don't want the program for the display to eat up the memory of the arduino so I use u8glib instead of u8g2! for this project I need to display numbers 0 to 9, decimal point, omega (ohm symbol) and metric prefixes such as μ,m,k,M, etc...
I first tried to create a bitmap font (.bdf) and convert it to a C file because that was what was hinted at on a few posts. There were no tutorials and after messing about with the different formats and trying to add the font to the library I just gave up because I couldn't figure it out. Instead I decided to use this website which generates bitmaps from TTF files:
https://littlevgl.com/ttf-font-to-c-array
Now I can use those bitmaps and have my few characters which use very little memory (about 20% as opposed to more than 70% using a complete symbols font in u8g2!) but this makes things really awkward as I have to translate every number I get into separate digits and then into a bitmap! also I can only use font sizes which have a height in multiples of 8 because for some weird reason this library expects width in number of bytes and height in number of pixels!

cnt: Number of bytes of the bitmap in horizontal direction. The width
of the bitmap is cnt*8.

so I can do fonts of size 48 for example, but not 50 or 52 which would be more suitable for my application!
I'm not sure if anyone else has had this issue but there must be a way to display the characters you want without destroying your entire memory space like u8g2 does! Just getting to this point took me 2 days (on the left there is a 0.96" SSD1306 and on the right there is a 1.3" SSH1106):

Please help if you have any idea on how to deal with this library as it's driving me insane at the moment!

While this may not exactly answer your question, there may be some information about u8g2lib that you have not seen. The library source code is linked here: u8g2lib
Within that repository is the FAQ documentation which includes such gems as:

Q: U8g2 requires a lot of memory. How to reduce this?
  - Visit https://github.com/olikraus/u8g2/wiki/u8g2optimization
  - Disable U8g2 features if possible (see u8g2.h)
  - Limit the font size. If possible avoid "f" fonts, instead use "r" or "n" fonts
  - If the I2C interface is not required, then uncomment #define U8X8_HAVE_HW_I2C in U8x8lib.h   (Background: Due to a problem in
  Wire.h, the I2C Arduino lib is always included)

and

Q: How can I generate my own font. A: The font must be available in
  bdf file format. Then use bdfconv to generate the font data. The font
  data can be pasted into an existing file of your project. There is
  also a nice Windows Bitmap Font Editor "Fony"
  (http://hukka.ncn.fi/?fony)  which can export .bdf files. A copy of
  Fony 1.4.7 is available here:
  https://github.com/olikraus/u8g2/tree/master/tools/font/fony

The tools/font directory includes several utilities, including what looks like one that converts OTF fonts to BDF format
Once you get a BDF format font, you use bdfconv to create the C file that holds the font array. One of the arguments for bdfconf is the -m 'map' option. You can place in there a list of Unicode ranges that limit which characters get included. So, you can create a font that has ONLY the characters you need.
For example -m '45-46,48-57,77,107,109,181,937' gets you minus, decimal, 0-9, 'M', 'k', 'm', mu, omega. Unicode character map at https://unicode-table.com/en/
The benefit to creating a font is that the u8g2lib library itself does all the mapping to bitmaps and calculating the character widths, etc. so you don't have to.

this is really helpful,specially with memory reduction part, but I'm still not sure how to use the bdfconv tool, it seems to be used with linux command line, not windows. Also even when I get the C file, I'm not sure how to use it. should I add something to the u8g2_fonts.c? should I just copy and paste the generated file into my .ino sketch? please link to a full tutorial if you can, or at least create a basic walk through, thanks!

I'm not sure there is a full tutorial. Look in https://github.com/olikraus/u8g2/tree/master/tools/font/bdfconv for a .exe windows version of bdfconv!. The resulting .c font file: Just #include "fontfile.c" in your program, and put the file in the same folder as your sketch. That will bring in the font without having to edit the existing fonts file.

when I run the .exe file nothing happens. Should I download and modify the "  Makefile" as well? The instructions are really vague and lacking tbh.

I downloaded https://github.com/olikraus/u8g2/blob/master/tools/font/bdfconv/bdfconv_2_22.exe and it runs fine.

does it not require any other files and runs on it's own? for me it opens and closes immediately afterwards! I think I have to stick with creating manual bitmaps :(

You have to run it from a command prompt. It's not a graphical program.

Another note -- if the fonts you want to use are taking up 70% of flash space, but you aren't hitting 100%, then what's the problem?

because it's the display aspect of the program only! if I add the rest of the project, it won't fit!


text:
How to re-construct audio from series of analog integer input?
I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.   At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.
I'm new to working with these types of break out boards, so I found an online project that I'm using as a starting point:
Streaming audio from ESP8266 to pyaudio working in Arduino IDE
I figure I start troubleshooting my popping sound issue by inspecting the UDP packets my ESP8266 code.  Below is the source code I'm working from:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "change this";
const char* password = "change this";
int contconexion = 0;

WiFiUDP Udp;

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

  pinMode(5, OUTPUT);  //D1 Led de estado
  digitalWrite(15, LOW);

  WiFi.mode(WIFI_STA); //para que no inicie el SoftAP en el modo normal
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED and contconexion <50) { //Cuenta hasta 50 si no se puede conectar lo cancela
    ++contconexion;
    delay(250);
    Serial.print(".");
    digitalWrite(5, HIGH);
    delay(250);
    digitalWrite(5, LOW);
  }
  if (contconexion <50) {
      //para usar con ip fija
      IPAddress Ip(192,168,1,180);
      IPAddress Gateway(192,168,0,1);
      IPAddress Subnet(255,255,255,0);
      WiFi.config(Ip, Gateway, Subnet);

      Serial.println("");
      Serial.println("WiFi conectado");
      Serial.println(WiFi.localIP());
      //digitalWrite(5, HIGH);
  }
  else {
      Serial.println("");
      Serial.println("Error de conexion");
      //digitalWrite(15, LOW);
  }
}

void loop()
{
  Udp.beginPacket("192.168.0.26", 1234);

  for(int i=0; i<1024;i++){
    int old=micros();

    float analog = analogRead(A0);
    if (analog > 255) {
      analog = 255;
    }
    else if (analog < 0){
      analog = 0;
    }
    Udp.write(int(analog));
    Serial.print(int(analog));
    Serial.print(",");
    while(micros()-old<87); // 90uSec = 1Sec/11111Hz - 3uSec para los otros procesos
  }
  Serial.print(";;;;;");
  Udp.endPacket();
  delay(5);
}

Notice near the bottom of the file, I print out each analog value separated by a comma, and each data packet separated by five semicolons.
Can someone suggest a way for me to re-construct these series of integers into a sound file that I can inspect via listening with my own ears?  Then I can tell if the sound data being sent is complete?  Or let me know if there's a better way to test if all the data packets are being sent correctly.
UPDATE
I tried to create a wav file by doing this:

Take the list of all integers from Serial.print(int(analog)) and paste it into a file. I make sure all integers are space delimited (ie. no more commas or semicolons)
I copied the file over to a linux machine that had ffmpeg installed
I ran the command ffmpeg -f u8 -ar 11111 -ac 1 -i myfileofintegers -y test.wav

When I listen to the test.wav file, I just hear a series of rapid popping noises.  Not sure if I created the wav file properly?

You could convert it to the .wav file format. The simplest file format available.

I just updated my question to show my attempt at making a wav file.  Did I do it correctly?  I hear more popping noises.

convert what to wav? 2) prints take time 3) what is wired to A0? 4) range of analogRead is 10 bit. you cut the input to 255

@Juraj To answer you questions 1) I'd like to convert the list of integers given by Serial.print(int(analog)) to a wav file.  3) A0 receives the output voltage of a pre-amplified electret microphone.  The voltage amplitude seems to range between 0mv and 300mv.

I gather because I was following the same guide. Unfortunately I do not receive any quality sound but only small pulses, the microphone that uses in the video is made by him, I have used two different types of microphones: KY-038 and / or MAX4466 with the same result. My need is to receive audio, send it to UDP and save it in WAV. Can someone help us?

I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.

You have described several problems; one needs to break big problems into small problems:

Sample the audio
Send it to another computer
Decode and playback the sound

At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

This sounds like you have got your timebases messed up; it is likely that you aren't recording enough data or playing it back incorrectly. N.b. it looks like you are recording ~92ms of audio data each 'packet' and if you get a series of pops at 2hz you are likely playing less than 1/10 of a second of audio for ever 5/10 of time, so your speaker moves for 1/10th of a second then stays still for 4/10ths and repeats; this produces your 2hz popping noises.
Your code has some other problems as well:

Serial.print() is Slow! Don't use it where performance matters!
Intertwining sampling and sending
Incorrectly scaling the analog reading
11.1khz can only record signals up to 5.5khz

Lets start with the audio sampling. We have some sort of audio circuitry presenting a signal to an analog input, we need to sample it regularly and uniformly! The code presented is trying to sample at 11.1 kHz, but only does so for 1024 samples before hitting a discontinuity. We do not have circuitry dedicated to this so we will have to use the ADC circuitry on the Arduino.
First thing you will want to get you sampling regular and continuous. You will want to use an interrupt on the Arduino for this. The interrupt should take a single sample from the ADC and add it to a buffer or signal the main loop to read/buffer it.
This interrupt will need to fire regularly at the sample rate or the data will be ruined.
Second the audio circuitry should prepare the signal so that it is between 0-5v with a ~2.5v bias, this will use the ADC hardware to its fullest.
so in Pseudo code:
// include any libs etc.
// set up variables ect.
void interupt_sample();
// register and attach interrupt
void setup() {
//do your setup etc.
}
void loop() {
// if(new_sample) add_to_buffer(new_sample);
// if(buffer_full) send_and_flush_buffer();
}

Specific to converting a list of integers to an audio file, I found a solution here https://stackoverflow.com/questions/55286149/what-ffmpeg-command-to-use-to-convert-a-list-of-unsigned-integers-into-an-audio/55288084


text:
Number of cycle depending on the number and type of statements
I did this little experiment to count the number of cycles per second in two different configurations:
1-The variable a is initialized at zero and incremented by one each cycle of the loop.
 -The value of a is written each cycle
 -at millis() = 1000, the incrementation ends, and the value of millis() is written to check the precision of timing.
Code:
long a = 0;
int v = 1;

void setup() {

Serial.begin(9600);

}

void loop() {

if (v == 1){
a = a + 1 ;

Serial.println(a);

if (millis() >= 1000){
Serial.println(millis());
v = 0;}

}
}

Result:
1
2
.
.
.
227
1000
2-Same as 1, but the value of a is written only at the end.
Code:
long a = 0;
int v = 1;

void setup() {

Serial.begin(9600);

}

void loop() {

if (v == 1){
a = a + 1 ;

if (millis() >= 1000){
Serial.println(millis());
Serial.println(a);
v = 0;}

}
}

Result:
1000
265174
-So, 227 cycles for 1, and 265174 for 2, is this correct, and can such a simple modification slow the cycling by 1000?

Serial.print() takes a lot of time, so result is correct.

Writing via the serial interface takes a lot of time (just consider the baud rate you selected).
You should always keep in mind that changing the amount you are printing might change your programs behaviour.
That means, your 2. configuration is (more) reliable.

When the serial buffer (64 bytes) is full the print waits until bytes are send away at 9600 baud.

You could use micros() as well to increase resulution to 4uS, vs 1000uS.
Up the speed to 115200, that should show some improvement as well.


text:
Displaying characters as bitmaps
I have resorted to creating bitmaps for each number and a few letters for a 128x64 Oled module. This was to save memory and get around limitations of libraries such as the u8glib. If I had linux I could use the tools they provided to fix some of these but that's out of the question for now. I wanted to know if there's a simple way of mapping each character to it's bitmap so a function similar to XXX.print(); be used, in order to parse the characters and display the corresponding bitmaps automatically. That would make my life so much easier! thanks!

Example: Font and Character handling for PCD8544. https://github.com/mikaelpatel/Arduino-LCD/blob/master/src/Driver/PCD8544.h#L304. The class implements the Print::write() virtual member function and reuses all the print() member functions.

I would split it down into functions.
First write a function which takes a character and a pair of coordinates, then draws the bitmap corresponding to that character at the given coordinates on the screen.
Then you want a function that is the "next level up". You just pass it a single character, and it remembers the current coordinates and uses those with the character to call the first function. It's then the job of this function to move the coordinates to the next character location ready for the next time it's called.
Finally you want an outer layer (or a few outer layer) functions that take different data types (const char * for example) and send each character in turn to the second function above.
If you were to make a class to wrap it all in you could inherit the Print class. That means you just need to provide the size_t write(char) function which is equivalent to the second function above (of course you still need the first function). The wrappers for different data types are then all provided for you.

my biggest problem now is that I can't use any other structure except const uint8_t var[] PROGMEM = {}; for my bitmaps. They will be changed by the compiler as soon as I delete the PROGMEM line. Also when I do this, there is no way I can pass the bitmap into anything (other than manually typing it which defeats the purpose!).As soon as I copy it, even using memcopy_P it is altered when it's displayed! I'm losing my mind over this!

Maybe I can write a huge case statement rather than a lookup table, but that seems awfully wasteful and bad practice. I played around with using structures, pointers, etc with no real luck in solving anything! it seems to be cursed!


text:
ESP12e pin 13 won't set to output/won't work
I have an ESP12e and running a basic blink code on it. The problem is that GPIO13 of esp12e wont turn on. I have noticed that this has happened from time to time. Earlier I thought that the ESP was faulty so i just changed them. But now I have a lot of 10 ESPs and all of them have the same problem. Pin 13 wont turn on setting to HIGH.
What could be going wrong? Is there something that I am missing?
EDIT:
However, on the same piece of esp12, for some test, i tried putting the gpio12 to input and that worked.
Code:
void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
}

and this is with no other hardware or libraries?

How are you determining that GPIO13 is not high?

Basic blink code uses, LED_BUILTIN ... on a generic module this is preset to 1 ... have you remembered to set LED to 13

@dandavis Ya, nothing else.

@JaromandaX umm, the led that I connect to it wont light up, nor does any reading show on a multimeter. And yes, the pin is set to gpio13.

i tried putting the gpio12 to input ... how is that relevant to gpio13 as output?

@JaromandaX, In the prodct that we are using this for, the gpio12 is working as input. I thought none of the gpios on that side were working. But the problem seems with just gpio13.

so, to summarise, you have 10 (at least) EPS12E, and not one gpio13 is working using the ESP8266 library blink code example - can you post in the question the code you are uploading to the ESP12E? I ask because it may be different with the version of arduino for esp8266 you are using compared to the one I'm using


text:
Oscillating Output from Arduino Pins when not in use, why?
I have A1 set to be an input, have the program read it, and then print to the serial monitor. My question is, when the circuit is not receiving power, but is grounded, and is still connected to A1, when do I see an output pattern of, for example:
0,0,0,0,7,23,16,9,4,0,0,0,0,3,18,21,15,0,0,0.....

I have a different detector inputing to A0 and if I don't have A1 connected then I get a reading that is similar to what I would see if I was actually reading A0 (around 900). Then if I plug back into A1 the value drops to around 350. When A0 is unplugged and only A1 is plugged in I only get noise (ie the pattern above in the code section).

Looks like the input pin is 'floating', picking up stray signals from the air. Do the numbers go higher as you move your hard closer, and decrease as you move farther?

looks like a sine wave to me, maybe AC coupling? Drawing current on the connected module could also pull up the ground, like seen on a shunt resistor.

@dandavis what can I do to prevent this?

@VE7JRO that's not exactly what I'm getting at, but thanks for the thought

I'm thinking along the same lines as CrossRoads and dandavis above. Would you be able to post a circuit diagram? If you haven't grounded the input, it could be floating or picking up noise from the surrounding environment. A 5k pulldown resistor may fix the problem, depending on what your circuit looks like and the environment its in.

. Please for give me for any breach of standard practice, MechE by training haha

any thoughts @SirBagels?

@RyanB Without knowing more about what your'e trying to do with that circuit, it's hard to tell. The first thing I noticed was the 3M resistors, it seems pretty large. What caused you to pick that value? 5V/3M is approx 1.5uA. It doesn't take a ton of current to hit the high side of your Analog input. Try a few smaller values, 100k, 10k, etc. and see how that affects your results. I'd guess your're picking up noise from somewhere and the 3M resistor is kicking that into a readable voltage.


text:
SoftPWM update limitations
i'm using arduino to dimmer 9 led strips with different output pins after an FFT audio analysis gives results at 60Hz = 16ms. [FFT is performed by a PC and sent to arduino using a RF24 module]
I started the project using SoftPWM on pins D2->D9 & A4 with a lower frequency update but now i'm having problems increasing the frequency update. I have already wired 6 copies of that board and i'm looking for a software solution
To diagnose the problem i performed a test sending a pwm value and zero at a certain frequency, if the frequency is high you can only see a lower emitted power
If I set the pwm once I have a stable signal (led intensity)
If I set the pwm every ~10ms (10ms on @ certain pwm, 10ms at pwm=0) I have an unstable intensity, repeating the test on the pin 6 with a normal analogWrite i don't have the problem. With 10ms i clearly see it blinking at a random frequency (~20Hz=50ms), with 15ms I only see it random fluctuating
I'm using arduino Pro mini - 5V - 2kB
Without signals arduino performs 16k cycles/second (most without changing anything), with a 10ms signal it runs at 14k cycles/second so it seems not a load problem.
Can someone help me regarding this problem?

Should I change library
Should I move to a lower level to rewrite a more performing library
Should I use only 6 std pwm, draw again the board, print them again, weld all components again, and test it again?

Thanks!
PS: I can't create the SoftPWM tag for a reputation problem, can a moderator do that?

there's only so much an AVR can do in software, they are limited in "horsepower". Coupled with your FFT workload, it sounds like you're pretty lucky it works as well as it does. analogWrite is "hardware accelerated" so to speak, so if you can use it instead, that should provide higher capacity. You can get external GPIO expanders or DACs, or use a 2nd pro-mini talking to the 1st over uart.

Sorry, I wasn't explicit. FHT is done by a PC, results are sent to arduino using an RF24 module. If not really needed i want to avoid to modify the hardware, since it's inside a printed PCB and i'm worried I must redesign it to handle a new module. I have 6 identical board that receive RF24 packets and enable/disable leds

The problem is not a SoftPWM limitation but a physical one. SoftPWM have a PWM cycle at 60Hz, that makes impossible to update output faster than 34mS and that explain why I see low frequency trying to change the state with every 10 ms.

Hardcoding the IRS I can reach a much faster PWM cycle, keeping the same PWM frequency I have roughly 60% less of CPU used. With a full CPU load and latest version of the code I can reach ~600Hz PWM cycle. I decided to use a ~300PWM cycle to have enough CPU to perform other tasks (mainly handle RF24 to receive packets @ 60Hz and, if needed, forward them too other bases)
Even at higher frequencies average intensity is not stable, but higher the frequency more stable the result. That can be explained because the eye "average" incoming light and that average is not very stable

Since leds are used to produce visual effects I don't need a very accurate output, and 300Hz are enough. (I also don't have big mosfets and I don't want to stress them with higher frequencies)


text:
Arduino IDE can't program my Arduino Pro Micro
I have a lot of Arduino Pro Micros that I can't program through the Arduino IDE.
I'm on Windows.
I'm using the SparkFun Pro Micro board information downloaded from SparkFun's website.
I've tried manually reassigning the Pro Micro's COM port in the device manager. It seems to be no different whether I'm at COM1 or COM255.
If I use an Arduino ISP or USBASP to burn the bootloader onto the problematic Pro Micro, it responds for usually one or two more USB programmings but that's about it.
When they get into this problematic state, they are still running their code (I can see the Blink sketch flashing my LED for instance), they just can't be reprogrammed. I can even still open their Serial communications.
Verbose output during the uploading process on first attempt yields the following:
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
Uploading using selected port: COM2
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM2 -b57600 -D -Uflash:w:C:\Users\Thompson\AppData\Local\Temp\arduino_build_668056/BareMinimum.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM2
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

That last line is where it freezes for an indefinite period. I close and reopen the Arduino IDE and try to reupload, and this is my result:
processing.app.debug.RunnerException
        at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
        at cc.arduino.UploaderUtils.upload(UploaderUtils.java:82)
        at processing.app.SketchController.upload(SketchController.java:736)
        at processing.app.SketchController.exportApplet(SketchController.java:703)
        at processing.app.Editor$DefaultExportHandler.run(Editor.java:2039)
        at java.lang.Thread.run(Thread.java:748)
    Caused by: processing.app.SerialException: Error touching serial port 'COM2'.
        at processing.app.Serial.touchForCDCReset(Serial.java:107)
        at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
        ... 5 more
    Caused by: jssc.SerialPortException: Port name - COM2; Method name - openPort(); Exception type - Port not found.
        at jssc.SerialPort.openPort(SerialPort.java:167)
        at processing.app.Serial.touchForCDCReset(Serial.java:101)
        ... 6 more

This exact same message (with a different COM number of course) plays out on any Windows machine I try this with.
In the above example I was trying to upload the Bare Minimum example.
Are all of my Pro Micros dead? Is there something wrong with the IDE? Is there an alternative IDE I can get a second opinion from?
EDIT: An update; I've gotten Atom installed with PlatformIO and I was able to write a few sketches to an Arduino Pro Mini. I attempted the same sketches on the Arduino Pro Micro and got the same error and freeze: programmer is not responding

the Micro has a MCU with native USB port handled by the sketch (the part from Arduino core). if the sketch hangs, USB is not handled. then you must activate the bootloader by reset or double reset

That's really useful information. So do you mean that if I have a ten second delay in my main function, the serial port would only be handled once every ten seconds?

no. it runs with interrupt

After experimenting some more, it looks like this issue is related to a one second watchdog that I have enabled in my sketch. After removing the watchdog, I've had no problems (so far) with uploading code.

It is OK to accept your own answer as the solution to the problem.


text:
Using SoftwareSerial on a Wemos D1 to get data from a GPS Shield
I am trying to use a Wemos D1 R2 to connect to my NEO-6M GPS module. I am able to make the module work fine with an Arduino UNO. I'm having significant trouble with the D1. Based upon other posts I have read here, I have included the appropriate Pins_Arduino.h include file and used the aliased settings. Here is the code I am using:
#include <Pins_Arduino.h>
#include <SoftwareSerial.h>
#include <TinyGPS++.h>

// The serial connection to the GPS module
SoftwareSerial ss(D2, D3); // Here are the aliased pins
TinyGPSPlus gps;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  ss.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (ss.available() > 0){

    gps.encode(ss.read());
    if (gps.location.isUpdated()){
      //int value = analogRead(lightPin);
      //Serial.print("Light= ");
      //Serial.println(value);
      Serial.print("Latitude= ");
      Serial.print(gps.location.lat(), 6);
      Serial.print(" Longitude= ");
      Serial.println(gps.location.lng(), 6);

      Serial.println(gps.time.value());

      // Hour (0-23) (u8)
      Serial.print("Hour = ");
      Serial.println(gps.time.hour());
      // Minute (0-59) (u8)
      Serial.print("Minute = ");
      Serial.println(gps.time.minute());
      // Second (0-59) (u8)
      Serial.print("Second = ");
      Serial.println(gps.time.second());
      // 100ths of a second (0-99) (u8)
      Serial.print("Centisecond = ");
      Serial.println(gps.time.centisecond());
    }
  }
}

I have ensured that I have the RX and TX pins correct, even reversing them to test the connection. Am I doing something wrong with the pins? Or do I have to just drop seven and punt on the D1 and get an ESP8266 shield for my UNO?
To help explain the ultimate purpose of this project, plan to use an esp8266 based web server to pull geographic based data from other sensors on the board. If I can't get the GPS to work here, I'll need to re-engineer my project.
Thanks. I apologize if this is a duplicate question, but my petrified brain just isn't searching correctly if it is.
Update:
If I use an Arduino UNO, everything works fine. I tried using the WeMos D1 R2 over the weekend and received data for about 5 seconds and then it stopped. I used pins D4 and D5 for RX and TX respectively. I'm not sure if the data was in the serial buffer when I uploaded a new Sketch or if it was actually returned from the GPS.
I'm going to punt on making the WeMos board work for now and ordered an ESP-01S to use with my Arduino UNO. I'm also reaching out to a supplier for assistance on this. Thanks for the help.
I'm going to leave this open for now in case someone else can provide some insight.

what is  <Pins_Arduino.h>? if you select D1 R2 in tools menu, you have the Dx constants. D3 has external pull-up. it could disturb SoftwareSerial. SoftwareSerial of esp8266 doesn't work good in 2.4.x versions

Ah! I am using the 2.4.2 version of the board. Which version would you suggest?

I never used SoftwareSerial with esp8266. I only know from forum and SE about the problems. And I saw some changes for SoftwareSerial in the GitHub repo of the esp8266 Arduino package. Try 2.5 beta version in Boards Manager. And pins D1 D2 (without  <Pins_Arduino.h>)

Post that as an answer. I'll give it a try and accept if it works. As an aside, I only added the Pins... include as a last ditch effort.

try it first. there was other question about SoftwareSerial of esp8266 yesterday without result https://arduino.stackexchange.com/questions/61313/esp8266-to-send-data-to-thingspeak-while-doing-unblocked-read-on-serial-readstri#comment130813_61313

I'd steer clear of D3 (gpio0), D4 (gpio2) and D8(gpio15) unless you know exactly what you're doing and what those pins are for

pins overview https://electronics.stackexchange.com/questions/402066/esp8266-free-gpios-for-relay-switching/404845#404845

does the GPS work over your USB-Serial adapter?

Juraj, post an answer with the Pin Overview. I'll accept it as a co-worker and I just made the bloody thing work. I guess I had to consult a PhD for this to work :)

Wemos board have watchdog to protect the board from infinite loop. Try to add yield() at the end of looping. It will bypass the watchdog. Tell me if it work.

@Madere. How did you make the Wemos work with NEO-6M GPS module?


text:
Arduino Uno Force-Sensitive Resistor
Would any one know how many Force-Sensitive Resistors that a Arduino Uno can handle being hooked up to at one time?

Theoretically as many as you like. You just have to set your bounds.

what is Force-Sensitive Resistor ..... how does it transmit its data?

@jsotola: it think he's talking about stretchy bands, like used in the power glove. To answer, about 8 without adding additional complexity or cost to the UNO.


text:
How do you make a stepper motor move in accordance to earthquake data using arduino?
I am new to arduino. I can import the acceleration data from a text file into arduino and I can also make the motor run at that acceleration with a distance calculated from an equation. I use the AccelStepper library but I notice that per acceleration data, the motor stops abruptly and moves  again in a very short delay, causing a lot of vibrations. Is there any easier way to make a stepper motor run with acceleration values from a text file?
The text file is also placed on an SD card, and I use the function Serial.parseFloat() to get the data from the file.
Here is my code:
#include <SPI.h>
#include <SD.h>
#include <AccelStepper.h>
int STP = 4;
int DIR = 3;
const int chipSelect = 53;
double Acceleration = 0;
double Previous_Acceleration = 0;
double Velocity = 0;
double Previous_Velocity = 0;
double Distance = 0;
double Previous_Distance;
AccelStepper stepper(AccelStepper::DRIVER,STP,DIR);
void setup(){
  pinMode(STP,OUTPUT);
  pinMode(DIR,OUTPUT);
  Serial.begin(38400);
  Serial.println("Starting Program");
  delay(1000);
  while (!Serial){
    ;
  }
  Serial.println("Initializing SD Card...");
  if (!SD.begin(chipSelect)){
    Serial.println("SD Card Error");
    while(1);
  }
  Serial.println("Card Initialized");

  File dataFile = SD.open("sinx.txt");

  if (dataFile){
    while (dataFile.available()){
      Acceleration = dataFile.parseFloat();
      Velocity = ((Previous_Acceleration + Acceleration)/2) + Previous_Velocity;
      Distance = ((Previous_Velocity + Velocity)/2) + Previous_Distance;
      stepper.setSpeed(Velocity);
      stepper.setAcceleration(Acceleration);
      stepper.runToNewPosition(Distance - Previous_Distance);

    }
  }
  else{
    Serial.println("Error");
  }
}

void loop(){

}

Have you confirmed that the values you are getting out of your file reading and calculations are actually correct?

Yes, they are the same values if applied in Excel.

However, when ran, the motor stops after a loop is done and resumes. The delay is so short that it seems that it runs continuously, but this causes vibration of the motor causing the readings of the accelerometer to be inaccurate. This may be the cause of a blocking function ( I am inexperienced so I may be wrong ), so is there any way to make the stepper motor move with acceleration without putting distance?

were you able to solve this problem? Would like to hear from you if you were able to solve it.


text:
AccelStepper Library: How do I go to a position without decelerating?
When I make the motor move at a certain distance with setMaxSpeed(), setAcceleration(), and moveTo(), it always accelerates and decelerates. Is there a way to disable the deceleration?

Acceleration and deceleration causes less mechanical stress. Why don't you want that?

Because I am trying to make it move in accordance to a set of acceleration data from an earthquake, and it seems weird that per value of acceleration (and distance from double integration), it accelerates and decelerates (and if the differences are too low, the motor can easily be heard vibrating)

AccelStepper, as hinted by the name, uses acceleration always. By setting the acceleration high, you reduce the amount of time spent accelerating to the set speed.
setAcceleration() sets the rate in steps per second per second. If your MaxSpeed is 200 steps per second, then setting the acceleration to 200*10 means all acceleration is over in 1/10 second. You can go higher, etc.


text:
Arduino scrolling text program freeze after some time
I use a 16x2 character lcd to display some text. What I want is first line will stay, but the second line should scroll text.
I wrote a program which works fine but the problem is after some time arduino does not respond. I suspect there might be a bug or memory leak in the code.
The relevant code is like this.
void scrollTextFromRight(int line, char text[])
{
    const char space[16] = "                ";
    char screen[16];
    char * longText;

    longText = malloc(sizeof(char) * (sizeof(text) + 17));

    memset(longText, '\0', sizeof(char) * (sizeof(text) + 17));
    memset(screen, '\0', sizeof(screen));

    for (int i = 0; i < 16; ++i)
    {
        longText[i] = space[i];
    }

    for (int j = 0; j < sizeof(text) + 17; ++j)
    {
        longText[16+j] = text[j];
    }

    for (int i = 0; i < sizeof(text) + 17; ++i)
    {

        lcd.setCursor(0, line);
        strncpy(screen, longText + i, 17 );
        lcd.print(screen);
        delay(350);
    }
}

I call this function from main program like this:
scrollTextFromRight(1, "Scrolling text");

you don't free the memory taken by malloc(). don't malloc() on Uno. even if you would free the memory the small heap gets fragmented fast. you can do the same with a buffer on stack

You malloc but don't free. Of course it's going to leak. Also sizeof(text) doesn't work like that. Instead you can do strlen to get the number of characters in a null-terminated char array.
You can do this without the longText buffer by doing partial copies into screen.
const char space[16] = "                ";
char screen[16];

for (int i = 0; i < sizeof(text) + 17; ++i)
{
    lcd.setCursor(0, line);
    strncpy(screen, space, i); // copy i spaces
    strncpy(screen+i, text, min(17-i, strlen(text))); // copy the rest of the string up to the end whichever is shorter.
    screen[17] = '\0'; // force null termination
    lcd.print(screen);
    delay(350);
}


text:
Wrong conversion of time_t to char
I have a simple sample of code that i want to convent a time_t to char array in order to concatenate it after, in an other array.
Code:
time_t unixt;
char exm [40];

unixt = RTC.get();
Serial.println(unixt);
dtostrf(unixt, 10, 0, exm);
Serial.println(exm);

The problem that i face is that, the console is printing different the second one every time like this:
1548258220
1548258200

I tried also with unsigned long with no result either. Can someone point me what's wrong or an other way of doing this?

Use ultoa() instead of dtostrf(). The former is meant to serialize
unsigned long integers, while the later is for floating point numbers.
By using dtostrf(), you are implicitly converting unixt to a
floating point number. The Arduino Mega only supports single precision
floating point, so this conversion incurs some loss of precision, hence
the result you see.

Thanks a lot! That was exactly what i needed.


text:
How to remove or only show part of the data received?
I'm using the ble_client.ino example and I can't figure out how to only show some of the notifyCallback data. I'm getting three different types of data from one service UUID.
static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {

  static unsigned long lastPrinted;
  const unsigned long printInterval = 100;
  if(millis() - lastPrinted >= printInterval) {
    lastPrinted = millis();
    Serial.println();
    }
    Serial.printf(" Data:%X", pData[16]);

}

This is what get in the serial monitor

Data:A9 Data:B9 Data:F5
  Data:A9 Data:B9 Data:F5
  Data:A9 Data:B9 Data:F5
  Data:A9 Data:B9 Data:F5

I just want the

Data:B9
  Data:B9
  Data:B9
  Data:B9
  Data:B9

to be shown. How to?

use an if statement  ..... Serial.printf() executes only when data is B9

the value with change. can't use if

You only want each first and second value and not each third? Or you don't have found a clear condition which values you want? You need to find out a precise condition, and use it in an if statement as jsotola proposes.

You say the value can change, but then you also say that you only want "Data:B9" to be printed.  Do you see how that is ambiguous?  So do you want it printed only when it is B9?  Or what?  What determines that it should be printed?  Can you see how that is an important piece of information?


text:
Arduino Mini and USB2Serial not uploading sketch
I am trying to upload my sketch to an Arduino Mini Pro.
My programmer is the Arduino USB2Serial.
I am running the Windows store app on a Windows 10 machine.
I wired everything up according to the Arduino Mini guide.

I got different errors just stating something like "error while trying to upload the sketch" before but now I'm always getting this error message after the programmer takes a very long time trying to upload:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x68
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I also didn't forget the capacitor. I added one that is well above the required 100nF and the reset seems to work as the mini came preloaded with the blink example and it briefly stops before the programmer tries to upload.
I did also try to manually reset at different times before and after klicking the upload button.
I also noticed the programmers RX LED lights up briefly flashing three times shortly after resetting the Arduino but the TX one never lights up.
I also checked if there was an error with the programmer but whenever send something through the serial console while connecting the RX and TX of the programmer it always returns what I typed and both LEDs light up so it should work.
I also manually installed the Arduino USB drivers. The programmer now shows up as "Arduino USB Serial Light Adapter" in the device manager.
I did set the arduino Mini board in the Arduiono IDE settings and also the right port. Though I am not really sure which programmer to choose. I tried pretty much all of them that made sense to me with exactly the same results in every case.
In my memory when playing with these components years ago I thought it was also possible to just connect an Arduino Mini "upside down" like this (I am so sure I remember this working but it won't when trying now):

So right now I don't know what else to try. I even tried multiple different Arduino Minis from different manufacturers and tried resoldering all pins to make sure I didn't mess up.
I also tried pretty much everything from the troubleshooting guide mentioned in the error message.
Any suggestions what else I could try?
Update: I now also tried using an old Arduino Uno as programmer like described in the Arduino Mini guide and I tried different versions of the Arduino IDE down to ver 1.0.1 all with the same results.
I even tried installing the drivers from the older versions but Windows 10 wouldn't let me and insisted that the default drivers were suited best.
I managed installing drivers from the newest Arduino IDE but it didn't change anything.
I read in this question That it might be an issue having to do with older Arduino Mini boards (mine are a few years old). But the fixes suggested there did nothing for me.
The only thing I can think of left to try would be using a machine running an older version of windows in order to be able to use older drivers. But I'm really not sure if it's worth the trouble.
I'm also starting to suspect that my programmer might be broken. But then again why did it work looping back serial messages?

the USB adapter is not a programmer. the Upload button in IDE does a Serial upload over USB (virtual com port) and doesn't care about Programmer selection it Tools menu. (In Sketch menu there is an option "Upload with programmer" for upload over a programmer connected to the ICSP header)

the wiring on second picture (reset on adapter to DTR pin on Mini) should work. I don't know if Minis had different bootloaders, but you could try to burn a current bootloader, if you have a ISP programmer or a working Arduino (for Arduino as ISP)

the Arduino USB to TTL adapter uses FTDI chip which is supported by everything. any OS, any version

Ok I'm gonna try to burn the bootloader next time


text:
Is there a more elegant way to check highest / lowest sample data?
N00b question,
Is there a better way for readability / elegance / DRY etc to check various sensor values for high/low record value?  This code works, but looks like the long way round.
  void checkRecord() {

if ( temp.current > temp.high) {
  temp.high = temp.current;
}

if ( temp.current < temp.low) {
  temp.low = temp.current;
}

if ( pressure.current > pressure.high) {
  pressure.high = pressure.current;
}

if ( pressure.current < pressure.low) {
  pressure.low = pressure.current;
}
if ( humidity.current > humidity.high) {
  humidity.high = humidity.current;
}

if ( humidity.current < humidity.low) {
  humidity.low = humidity.current;
}

if ( rainfall.current > rainfall.high) {
  rainfall.high = rainfall.current;
}

if ( rainfall.current < rainfall.low) {
  rainfall.low = rainfall.current;
}
if ( altitude.current > altitude.high) {
  altitude.high = altitude.current;
}

if ( altitude.current < altitude.low) {
  altitude.low = altitude.current;
}
}

Thanks!

If it works and is clear, what else do you need?  if statements execute quickly and I doubt you are calling the function quickly enough for execution time to matter.  Alternatively you could consider storing the data in an array rather than each variable separately - could make export easier.

nothing wrong with the code ..... formatting is incorrect .... the whole checkRecord() block should be indented  ..... it is only a readability issue ..... you could single-line all the if statements .... if ( temp.current > temp.high)   temp.high = temp.current; ..... then you could neatly line up everything in a column .... put all the equal signs under each other

This is a variation on the struct idea with an object-oriented flavor.
If you put the current, low and high values of any sensor inside a
struct, you could also morph this struct into a class and give it
an update() method that, in addition to updating the current value,
keeps the low and high updated:
class LowHigh
{
public:
    LowHigh() : current(0), low(INFINITY), high(-INFINITY) {}
    void update(float value) {
        current = value;
        if (current < low)
            low = current;
        if (current > high)
            high = current;
    }
    float get_low() { return low; }
    float get_high() { return high; }
private:
    float current, low, high;
};

I am assuming float data here, you may have to adapt to whatever type
is appropriate for your sensors.
You would use the class as this:
LowHigh temp, pressure, humidity, rainfall, altitude;

void loop()
{
    temp.update(temp_sensor.get_reading());
    pressure.update(pressure_sensor.get_reading());
    humidity.update(humidity_sensor.get_reading());
    // ...
}

I like this, it may require a bit of rework to my code, but a Sensor class is exactly how I should go about it to learn OOP and not think so procedural about things.  Thanks for your example!  I like the INFINITY for setting initial high/low, I had used  large and small values out of range.

I edited your answer to make the argument of the update method a float instead of int. Good explanation.

Thanks @MichelKeijzers, that was an oversight of mine.

You could write something like:
temp.high = (temp.current > temp.high) ? temp.current : temp.high;
temp.low  = (temp.current < temp.low) ? temp.current : temp.low;
...

Most of the time there are min/max macros defined already like:
#define MAX(a, b)   ((a > b) ? a : b)
#define MIN(a, b)   ((a < b) ? a : b)

So you can then simply write:
temp.high = MAX(temp.current, temp.high);
temp.low  = MIN(temp.current, temp.low);
...

Which expands to the exact code as given above.

I achieves the goal of looking a bit more tidy... Thank you!

Jeff Wahaus, you can go one step further. Can you make a macro for that with float numbers?

Unfortunately this way is slower, because every loop it updates the values of temp.high and temp.low. The original code updated that value only when conditions where true.

@FilipFranik actually, it is exactly as fast as the if-statements. The compiler seems to be able to optimize it.

Yes, the optimizer sees 'a=a' and optimizes it out unless you declare 'a' volatile.

These macros are already defined in Arduino.h, but they are spelled in lowercase: min() and max().

If the temperature, pressure, humidity, rainfall, and altitude structs were elements of an array of structs, you could iterate over those elements setting each one's high and low values with only two handwritten 'if-then' statements. If you also used an enum to name the indices of the structs, then in other parts of your code you could address each of them by a descriptive name:
// Declare a data struct and define an array of them.
struct {
   int16_t current;
   int16_t high;
   int16_t low;
} data[5] = {0, 0, 0, 0, 0};

// Name the structs by index
enum kind {
   temperature = 0,
   pressure,
   humidity,
   rainfall,
   altitude
};

// Assign one kind of data:
data[temperature].current = getTermperature();

// Set maxes & mins for all of the kinds of data:
for( i = 0; i < sizeof(data)/sizeof(data[0])); ++i ){
   if ( data[i].current > data.high) {
      data[i].high = data[i].current;
   }

   if ( data[i].current < data[i].low) {
      data[i].low = data[i].current;
   }
}

Update:

I'm strugling with the data[5] {0,0...} part in struct.

I can't see your whole sketch but you probably have allocated 5 separate structs named "temp", "pressure", ... , etc. I'm suggesting you allocate an array of 5 structs (which I collectively called "data"), one for each of your individual ones. I included an initializer ( '= {0,0,0,0,0}') to set everything to zero before the start of the run.

all of enum kind{} and how it becomes data[pressure] etc.,

The enum is a quick way to make 5 symbols that stand for consecutive integers, in this case, the index into the array of each struct, using a descriptive name for that struct's data. So 'data[pressure]' is the same as data[1] (in this case) but is more understandable.

the sizeof(data)/sizeof(data[0]) in the loop

That expression gives the number of structs in the array (the total byte-size of the array divided by the byte-size of one struct). We could write '5' instead, but when you someday add another member or two (wind_direction, wind_speed, perhaps?), you'd have to remember to also fix your for() loop. By using this calculation, the compiler will do it for you, leaving you one less opportunity to make a mistake you'd then need to debug.

and finally I think
  altitude.high in the if statement is a paste typo? should be
  data[i].high?

Absolutely right! Fixed now.
Update:

For defining initial values can you just assign an initial value in
  the struct such as int16_t low = INFINITY; and so on instead of
  {0,0,0,0,0}?

Yes - Without knowing your data and application, I chose the simplest initializer. The full syntax to do what you want would look like this:
// Declare a data struct and define an array of them.
struct {
   int16_t current;
   int16_t high;
   int16_t low;
} data[5] = {
  {0, 0, INFINITY},
  {0, 0, INFINITY},
  {0, 0, INFINITY},
  {0, 0, INFINITY},
  {0, 0, INFINITY}
};

You don't need (and may not) specify each data type and name; the struct declaration already provides that information. The initializers are positional and each one must be compatible with the data-type it matches up to.

Thanks, I don't understand a few things because n00b. I'm strugling with the data[5] {0,0...} part in struct.  all of enum kind{} and how it becomes data[pressure] etc., the  sizeof(data)/sizeof(data[0]) in the loop and finally I think altitude.high in the if statement is a paste typo?  should be data[i].high?

Thank you so much, the explanation of enum kind{}, and the expression in the loop was very helpful in understanding how it all fit together.  For defining initial values can you just assign an initial value in the struct such as int16_t low = INFINITY; and so on instead of {0,0,0,0,0}?  Since a default value of 0 for low will not work properly if the temp is above freezing.


text:
Forbidden characters in TCP/IP
I'm trying to send data from my ESP8266 to a NodeJS TCP server, the connection and basic charakters (48-90) are working fine, but if I use others like ASCII-Code (0,1,2,3...)  I don't get any usefull data out of it. So what I was thinking about that there are some character which aren't allowed to send over TCP/IP.
By the way,
I'm using this to write to the server, and I work with the standard WiFi Client library
char arr[255]
for(int i = 0; i < 255; i++){
   arr[i] = (char)i;
}
client.print(arr);

Nodejs File:
// Load the TCP Library
net = require('net');

var mysql = require('mysql');

// Keep track of the chat clients
var clients = [];
var uploadCounter = 0;

initMySQLConnection();

// Start a TCP Server
net.createServer(function (socket) {

    // Identify this client
    socket.name = socket.remoteAddress + ":" + socket.remotePort

    // Put this new client in the list
    clients.push(socket);

    // Send a nice welcome message and announce
    socket.write("Welcome " + socket.name + "\n");
    broadcast(socket.name + " connected\n", socket);

    // Handle incoming messages from clients.
    socket.on('data', function (data) {
        broadcast(">> " + data, socket);

        uploadData(data);
    });

    // Remove the client from the list when it leaves
    socket.on('end', function () {
        clients.splice(clients.indexOf(socket), 1);
        broadcast(socket.name + " disconnected.\n\n");
    });

    // Send a message to all clients
    function broadcast(message, sender) {
        clients.forEach(function (client) {
            // Don't want to send it to sender
            if (client === sender) return;
            //client.write(message);
        });
        // Log it to the server output too
        process.stdout.write(message)
    }

}).listen(10101);

// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 10101\n");

var connection;
function initMySQLConnection() {
    connection = mysql.createConnection({
        host: "host",
        user: "user",
        password: "pass",
        database: "database"
    });

    connection.connect(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
        }
    });

    connection.on('error', function (err) {
        console.log('db error', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
                                    // lost due to either server restart, or a
        } else {                                      // connnection idle timeout (the wait_timeout
            throw err;                                  // server variable configures this)
        }
    });

    setInterval(function () {
        connection.query('SELECT 1');
    }, 60000);
}

function uploadData(data) {
    data = String(data);

    console.log("Package Length: " + data.length);
    console.log("GOT ASCII CODE: ");
    for (var i = 0; i < 255; i++) {
        console.log(data.charCodeAt(i));
    }

    //upload Code
}

what does this mean? ... I don't get any usefull data out of it  ................ what are you expecting for ASCII-Code (0,1,2,3...)?

The print function takes an array of characters as zero terminated c-string. It prints until a byte with value 0. You have zero at arr[0] so it is an empty string.
To send bytes, write function is used. The print functions convert parameters to text or expect text as zero terminated char array.
In your case it should be client.write(arr, length); where length is the number of bytes you want to send from the buffer arr.

now I get values from 0-127 but all above is 65533. so the error seems to be in my nodejs file, i will add it above

ASCII code are only until 127. why do you read it as String and chars?

Doesnt the extended ascii code go until 255?

tell it to data.charCodeAt(i) :-)

So you mean without the data = String(data)?

try ArrayBuffer


text:
How to make a stepper motor move at sinusoidal acceleration?
I am new to arduino but I know basic concepts. How do I make the motor move at sinusoidal acceleration? I used the accelstepper library and it seems that at the end of each loop of distance with acceleration, the motor abruptly stops and begins accelerating again. Is there any way to stop this abrupt pause?

wow, you're doing this code line by line from answers here

Similar questions: https://forum.arduino.cc/index.php?topic=557838.0 and https://forum.arduino.cc/index.php?topic=365301.0  Symplaz, is this for school? Please show us your sketch.


text:
Arduino IDE 1.8.8 built in 1.2.1 Temboo Library?
I am weirded about the built-in "latest Temboo library" with the latest Arduino IDE; when a previous older code says to download the latest Temboo version < 2?
(which I found this: https://temboo.com/download)
http://wirebeings.com/arduino-intruder-alarm.html
I am using Arduino Uno or Arduino Leonardo + an iDuino Yun shield to recreate the experiment above.
I keep getting errors like this:
No matching function for call to 'TembooChoreo::TembooChoreo()'? TembooChoreo SendSMSChoreo; Error Help
Arduino: 1.8.8 (Windows 10), Board: "Arduino Leonardo"
Build options changed, rebuilding all
In file included from C:\Users\user\Documents\Arduino\intruderAlarmTest\intruderAlarmTest.ino:6:0:
E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:43: error: expected identifier before '(' token
#define TEMBOO_ERROR_ACCOUNT_MISSING      (201)
                                       ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'
         TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

         ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:43: error: expected '}' before '(' token
#define TEMBOO_ERROR_ACCOUNT_MISSING      (201)
                                       ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'
         TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

         ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:44: error: expected unqualified-id before numeric constant
#define TEMBOO_ERROR_ACCOUNT_MISSING      (201)
                                        ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'
         TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

         ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:44: error: expected ')' before numeric constant
#define TEMBOO_ERROR_ACCOUNT_MISSING      (201)
                                        ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'
         TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

         ^

In file included from C:\Users\user\Documents\Arduino\intruderAlarmTest\intruderAlarmTest.ino:7:0:
E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h: In member function 'char* TembooCoAPChoreo::getResponseData()':
E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:247:41: error: 'm_respData' was not declared in this scope
     char* getResponseData() {return m_respData;}

                                     ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h: In member function 'char* TembooCoAPChoreo::getHTTPResponseCode()':
E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:248:45: error: 'm_httpCodeStr' was not declared in this scope
     char* getHTTPResponseCode() {return m_httpCodeStr;}

                                         ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h: At global scope:
E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:277:5: error: expected unqualified-id before 'protected'
 protected:

 ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:280:27: error: 'm_client' declared as reference but not initialized
     TembooCoAPClient& m_client;

                       ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:311:5: error: expected unqualified-id before 'protected'
 protected:

 ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:314:1: error: expected declaration before '}' token
};
^
exit status 1
Error compiling for board Arduino Leonardo.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Update:
I found that   by adding #include TembooYunShield.h
and TembooYunShieldChoreo  SendSMSChoreo;
instead of TembooChereo SendSMSChoreo;
fixes most of the errors
except the @Temboo and @Twilio problem.

Sounds like they made a mess of it. Just delete it and download the official latest version of the library manually.

yeah how, I don't even understand there are different programming languages that I extracted from .zip or .jar. to raw folders and files and replaced my older Temboo with it.
but it still doesn't work, I can't make https://temboo.com/download seem to work so I stick with the built in latest 1.2.1 Temboo library from Arduino 1.8.8.

Can anyone help me with this temboo? Who is really knowledgable with this?

https://arduino.meta.stackexchange.com/users/84/jfpoilpret
https://stackexchange.com/users/2147199/cormac-driver
Please, any of you kind sirs help me regarding the temboo latest version issue? to be uploaded to arduino-1.8.8\libraries\Temboo?
anyone?

The problem appears to be because you are compiling for the Leonardo. If I compile for the Yun the examples work. If I compile for the Leonardo they fail with the messages you see.

I think the problem is that if you compile for the Yun it assumes a connection through the Yun and works. If you compile for anything else you have to give it details of your internet connection (WiFi shield, Ethernet shield, etc) and work in a completely different way. Since you have a Yun shield you would have to compile it for a Yun. Theoretically there should be no difference between a Yun and a Leonardo + Yun shield.


text:
DHT11 Reading Too High Values
When I run the program, there are no syntax errors or anything. All it does is give me values for the temperature in the hundreds. I don't know if there is a way to turn these abstract and unexpected values into the actual temperature.
I originally expected that it would print out the temperature around 20 Celsius, but instead, it prints around 600. This is my code:
#include <Adafruit_Sensor.h>
#include "DHT.h"

int sensor_pin = A0; // Analog Pin sensor is connected to
int output_value ;

void setup(){

  Serial.begin(9600);
  delay(5000);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(5000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    output_value= analogRead(sensor_pin);

    Serial.println("temperature = ");
    Serial.println(output_value);
    Serial.println("*C");
    if (output_value < 60) {
    Serial.println("Increase temperature by ");
    Serial.println(output_value);
    Serial.println("*C");
} else {
    Serial.println("Temperature does not need to be increased.");
}

    delay(5000);

}// end loop()

My bad, I did not include my code. Here it is:

What should I do?

I changed that, but what should I do now

anyway, back to your problem .......... you  are not printing the temperature ..... you are printing the value that relates to the voltage at the input pin ....... the voltage goes from 0V to 3.3V (or 0V to 5V depending on the model of Arduino) ..... the reading of 0 equals 0V and maximum reading is equal to 3.3V(5V) ...... you have to refer to the sensor data sheet to determine how the reading relates to the temperature

I am giving the dht11 3.3V but I don't know how to find the sensor data sheet

if we only had a way to access vast amounts of information ..... we could find data sheets and tutorials .... hmmmm .... i wonder .......... lol ......... sorry, i could not help it

@StrawberryMilk you have a arduino uno? I'm not sure which temperature sensor you have. Can you give a link to it, or a photo?

The DHT11 is a digital device. You cannot read from it with analogRead().
While temperature is an analog value, that's not how the DHT11 communicates with an Arduino. There is a specific digital protocol.
In your code, it appears you have added the headers for the Adafruit Sensor library and DHT library, but you never actually call the functions provided therein.
The Adafruit repository for the DHT sensor library has an example:
https://github.com/adafruit/DHT-sensor-library/blob/master/examples/DHTtester/DHTtester.ino
You can see how to create an object from the DHT class, and how to call it's member functions, such as readTemperature() and so on.


text:
How to initialize and run PCA9685?
I'm trying to write a simple code for initializing and running the PCA9685. I tested the board with Adafruit library and it's working.
But I just want to develop a simple code to include it in my various modules library for future projects.
I wrote a code, but I think I'm not understanding the work of the internal registers.
But according to the datasheet I configured only the auto increment and left the rest to default settings. Then I headed up to the last registers which are the all_led_on and all_led_offas wanting to run the outputs on/off to blink the LEDs. But I think these two registers are for enabling/disabling the pins. Is that right?
This is my code:
void pca9685_init(void){
    uint8_t i,val[]={0x20,0x04};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_MODE1);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

void pca9685_all_on(void){
    uint8_t i,val[]={0x00,0x10};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_ALL_LED_ON_L);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

void pca9685_all_off(void){
    uint8_t i,val[]={0x00,0x10};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_ALL_LED_OFF_L);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

If you want it simple, then use the arduino Wire library and stop fooling around with i2c code that does not work. It took many years to remove bugs from the arduino wire library. The i2c bus is not that simple, so you might never get the quality level of the arduino wire library. What you do is making it overcomplicated and wasting your time. Sorry for my harsh words, I want to make very clear that you should not continue this way. Well, that is at least my opinion, trying to help you.

Absolutely I understand you and respect your goal that you don't want me to waste time with the actual communication library. But my i2c library worked for all my i2c modules and revised different i2c libraries to get it not perfect, but at least to run the basic functions of sending and receiving. Writing my own code helped me a lot in learning how to write code, it's difficult to me to go into projects without learning the internals. But I agree an internal library like Wire should be a very good choice.

@PerchEagle You shouldn't be afraid of the space bar. I know it's big and imposing, but don't be scared of pressing it once in a while ;)

I got you, the code looks so compact lol.

I thought about the space aspect just a moment, but I have a question: what are the appropriate locations to put space into? My most important location is when I use arithmetic, logical or rational operators. But I don't put them to the braces, or after the functions' names. It feel it well fit, but maybe you're right, it maybe more compact than what I feel.

@Jot Just to update what you told me about how the fails could be from my I2C library. You're right! My I2C library is missing something which is doing faulty behavior in the program!

The registers aren't for just turning the LEDs on or off.  They are for setting the ON and OFF times of the PWM. Bit 12 of each combined value is used as a "full" setting, so:
To set the LEDs on to full brightness you need to set:

PCA9685_ALL_LED_OFF_L to 0x00
PCA9685_ALL_LED_OFF_H to 0x00
PCA9685_ALL_LED_ON_L to 0x00
PCA9685_ALL_LED_ON_H to 0x10

This sets the off time to 0 counts and the on to be "full on".
It doesn't really matter what value you set the OFF to as long as you set ON to "full on" and off isn't set to "full off".
For off you should set the ON to 0 and the OFF to "full off" (reverse the above settings).
Section 7.3.3 of the datasheet says:

The turn-on time of each LED driver output and the duty cycle of PWM can be controlled independently using the LEDn_ON and LEDn_OFF registers.
There will be two 12-bit registers per LED output. These registers will be programmed by the user. Both registers will hold a value from 0 to 4095. One 12-bit register will hold a
  value for the ON time and the other 12-bit register will hold the value for the OFF time. The ON and OFF times are compared with the value of a 12-bit counter that will be running
  continuously from 0000h to 0FFFh (0 to 4095 decimal).
Update on ACK requires all 4 PWM channel registers to be loaded before outputs will change on the last ACK.
The ON time, which is programmable, will be the time the LED output will be asserted and the OFF time, which is also programmable, will be the time when the LED output will be
  negated. In this way, the phase shift becomes completely programmable. The resolution for the phase shift is 1⁄
  4096 of the target frequency.

So you have to set all 4 registers together for anything to happen.
There are also some examples shown in the datasheet as well which explain it better.
In simple terms:

There is a free-running counter that counts from 0 to 4095
When the ON time matches the counter the LED turns on.
When the OFF time matches the counter the LED turns off.
If a channel is "FULL OFF" it will be off regardless.
If a channel is "FULL ON" and not "FULL OFF" it will be on regardless.
"FULL OFF" always takes priority over everything else - even "FULL ON".

Some simple examples:

All off: ON=0x0000 OFF=0x1000
All on full: ON=0x1000 OFF=0x0000
50% duty: ON=0x0000 OFF=0x0800
25% duty: ON=0x0000 OFF=0x0400
25% duty with phase shift: ON=0x0100 OFF=0x0500

Yep, you're right. I did it, I have to update the 4 registers for all_on state, and again all 4 registers for all_off state.

@PerchEagle The datasheet isn't that obvious. As you can see by the edit history of my answer it took me a while to understand it fully.

Thanks dude again for the help I really appreciate it, it's not the first time you help me, now I learned that, I can proceed to go to the pwm operations and develop the library.

I have a quick question, why there's 12-bit for on and 12-bit for off. I wrote different values for only on time and got certain results and different results for off time, and also got different results. So what's the deal exactly with this chip? Is the full range of this device is 4096 ON + 4096 OFF = 8192.

No. There is a single 12 bit counter. It turns on or off when the counter matches the on or off value. That way you can control the phase as well as the duty cycle.

Anyway I haven't mastered this module, I need a lot more practice or just to know what does on/off time means? are they the same? Should I use one and that's enough or using both have more functionality? These are the questions I have for this module.


text:
How to use virtual connection between matlab simulik and arduino in isis proteus?
I don't know how to connect between matlab simulik and arduino card in isis proteus by using a virtual ports

have you looked at any of the tutorials on the internet?

Yes, but i didn't find answer to this question by tutorial

were you able to create a virtual port in proteus?

I don't know how to create it

then, you are asking the wrong question and you are searching for the wrong tutorial on the web ............ find a tutorial about creating a virtual port in proteus  ..... find one about creating a virtual port in matlab also ...... i think that you only have to do one for your purpose


text:
Arduino I2C Register Read
I am trying to read a specific register from a device. In this case I am trying to read the value stored in register 0X1F from slave device 0x08. On the scope I see writes for
ADDRESS_SLAVE(Wire.beginTransmission), ADDRESS_TESTCOMP0 (Wire.write)

and
ADDRESS_TESTCOMP0 (Wire.requestFrom(ADDRESS_TESTCOMP0,8))

but I don't see the register values reading out.  Here is my code:
#include <Wire.h>

int ADDRESS_SLAVE = 0X08;
int ADDRESS_TESTCOMP0 = 0X1F;

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

void loop()
{
   Wire.beginTransmission(byte(ADDRESS_SLAVE));
   Wire.write(byte(ADDRESS_TESTCOMP0));
   Wire.endTransmission(byte(ADDRESS_TESTCOMP0));

   Wire.requestFrom(ADDRESS_TESTCOMP0,8);
   char read = Wire.read();
   Serial.println(read);

   delay(1000);
}

please format your code  as code ..... select the code text and click {} ..... or just indent each line by 4 more spaces

maybe the arduino is "talking" too fast

Remove the Wire.setClock. The arduino mega 2560 can not do 3.4MHz. Only 100 kHz and perhaps 400 kHz with short wires. The Wire.endTransmission does not take data as a parameter, only a parameter for a stop condition. The Wire.requestFrom takes the slave address as a parameter, not the register address. The second parameter of the Wire.requestFrom is the number of bytes that you want, since you want just 1 byte, make that 1 and not 8. Which device is it? I hope not a device that runs at 3.3v. Start here: https://www.arduino.cc/en/reference/wire and read the reference pages of the functions.

Wire.begin sets default clock. the setClock line is not applied

Thank you for all the feedback. Code is still not accomplishing what I need it to and maybe I am going about it all wrong. Here is what I am trying to do:

I corrected set clock to 100K, eliminated the parameter in end transmission, corrected the request from parameter and set it to 1 byte....I am still not reading the register I am looking for. This is a 5 volt device. I've read the reference section on the wire library on the Arduino website exhaustively, which is why I am here now.

errors corrected
#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

void setup()
{
 Wire.begin();
 Wire.setClock(400000); // set I2C 'full-speed'
 Serial.begin(9600);
}

void loop()
{
   Wire.beginTransmission(ADDRESS_SLAVE);
   Wire.write(REGISTER_XY);  // set register for read
   Wire.endTransmission(false); // false to not release the line

   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH); // request bytes from register XY
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}

if you read only one register of the device, you can setup the device in setup() and in loop() only read the data from the register:
#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

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

  Wire.begin();
  Wire.setClock(400000); // set I2C 'full-speed'

  Wire.beginTransmission(ADDRESS_SLAVE);
  Wire.write(REGISTER_XY);  // set register for read
  Wire.endTransmission();
}

void loop() {
   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH);
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}

we don't know if the register address is 8-bit or 16-bit. Perhaps the slave is a microcontroller and needs a delay. The Wire.read does not take parameters, it reads a single byte. You were thinking about Wire.readBytes? We don't know how long the wires are and we don't know what the slave device is or how it behaves.

@Juraj Wow...thank you very much Juraj! That works! It seems like I was pretty far off the mark with what I was trying to do. Do you know of an available reference I can use for these types of problems i.e. text/book?


text:
How to upload arduino code using xbee module ( pro s2c)?
I have three arduino ATMega2560 boards, all have xbee pro s2c attached to them. Now i want to update the code i had previously written on the arduino board but without connecting it to the computer. So basically I want to upload a code to arduino board via the xbee module I have attached to it, code is transmitted to this xbee from another xbee. Anyone with any type of ideas please share....

You could do it like I update the application in Mega in ArduinoOTA library https://github.com/jandrassy/ArduinoOTA/blob/master/src/InternalStorageAVR.cpp it requires to changed the bootloader to Optiboot with copy_flash_pages function https://github.com/jandrassy/ArduinoOTA#atmega-support

updated application binary is received to upper half of the flash memory with Optiboot's do_spm function and after then copied to the beginning of the flash with copy_flash_pages function of Optiboot. copy_flash_pages then resets the MCU.

thanks a lot @Juraj i will try that and let you know if this was helpful


text:
Having really weird experience with string concat
Having really bad day with concat. I'm not quite sure where i did wrong..
Have a look at my function below.
void sim900aSendHttp(String bid, String lati, String longi) {
  Serial.println("BUSID:"+bid+",LAT:"+lati+"LONG:"+longi);
  String httpget = "http://uumresearch.com/bustracking/update_location.php?busid="+bid+"&latitude="+lati+"&longitude="+longi+"";
  //String httpget = "http://uumresearch.com/bustracking/update_location.php?busid=KDF8860&latitude=6.533415&longitude=106.33345";
  Serial.println(httpget);
  serialSIM800.println("AT+HTTPPARA=\"URL\",\"" + httpget + "\"");
  delay(3000);
  serialSIM800.println("AT+HTTPACTION=0");
  delay(8000);
}

The problem is with:
String httpget = "http://uumresearch.com/bustracking/update_location.php?busid="+bid+"&latitude="+lati+"&longitude="+longi+"";

where serial monitor only  shows
http://uumresearch.com/bustracking/update_location.php?busid=KDF8860

missing "lat" and "longi" variables in the string concat.
Both variable confirmed available to the function as printed by
Serial.println("BUSID:"+bid+",LAT:"+lati+"LONG:"+longi);

Which arduino board do you use?

+ on const char * increments the pointer. only String has + overloaded as concatenation of the right operand (not left). so "abc" + str + "efg" will not work even if str is String. What will work is String("abc") + str + "efg", but small Strings will fragment the heap memory of the MCU very fast and the sketch will crash.
Print the parts directly to serialSIM800 or use snprintf to build the strings or try CStringBuilder from my StreamLib


text:
Myoware reading multiple fingers?
So I have recently been trying to use the Myoware Muscle sensor to control an 3d printed arm, but it is only able to read the muscle of the entire arm. Is there anyway i could make the Myoware sensor read different fingers at the same time?

I don't think so. I have already a lot of trouble to have a consistent results with Myoware. The muscles for the fingers are smaller and a little deeper. I think that you can not use the muscles to measure motion of the fingers. You need to measure the mechanical motion or bending of the fingers, for example with a glove with stretch sensors.

Ooo ok then thx for the help, i'll see what i can do

Our MyoWare sensor is a single channel EMG sensor and should only be used to detect a single muscle at a time. BUT, if you have 5 sensors, then you can indeed use them to measure each finger's flexion or extension individually. It would take 10 sensors to do both flexion and extension of all your fingers.
However, keep in mind that there are many muscle groups on top of each other in the forearm (e.g. finger muscles, wrist muscles, forearm rotation muscles) and the MyoWare uses surface electrodes. The sensor will detect the activity of any muscle(s) that get activated under the area of the electrodes and you could get a lot of cross-talk between these muscles. For example, the muscles that control your wrist are under the muscles that control your fingers. Any activation of your wrist muscles when trying to measure the finger muscles would cause the sensor to falsely register activity for your finger muscles.

If you are thinking of using it to detect finger position, I would advise using a flex sensor or something similar than a muscle sensor. Muscle sensor sensors are usually used to detect force or as an on/off switch given a threshold value to activate the switch.

I would also recommend using the MyoWare Cable Shield with electrodes smaller than the standard 1" ones that are usually sold along side the sensor. This would help you target smaller muscles without as much cross-talk from adjacent muscles.

Ok i will keep that in mind thx